fix(db): Added db to actual price
This commit is contained in:
1 parent
39cc73d71a
commit
beb94d2b0d
4 files changed
+364
-134
No files matched your search
@@ -12,7 +12,7 @@ def get_all_categories_with_attributes(db_name: str = 'pipe_store.db') -> List[D
|
||||
cursor.execute("""
|
||||
SELECT id, name, image_path
|
||||
FROM categories
|
||||
WHERE parent_id IS NULL OR parent_id = 1
|
||||
WHERE parent_id IS NULL
|
||||
ORDER BY id
|
||||
""")
|
||||
|
||||
@@ -21,7 +21,7 @@ def get_all_categories_with_attributes(db_name: str = 'pipe_store.db') -> List[D
|
||||
for cat_row in cursor.fetchall():
|
||||
category_id = cat_row['id']
|
||||
|
||||
# Получаем все фильтры для товаров в этой категории
|
||||
# Получаем все фильтры для товаров в этой категории и подкатегориях
|
||||
cursor.execute("""
|
||||
SELECT DISTINCT f.id, f.name, f.filter_key
|
||||
FROM filters f
|
||||
@@ -29,10 +29,13 @@ def get_all_categories_with_attributes(db_name: str = 'pipe_store.db') -> List[D
|
||||
SELECT DISTINCT pf.filter_key
|
||||
FROM product_filters pf
|
||||
JOIN products p ON pf.product_id = p.id
|
||||
WHERE p.category_id = ?
|
||||
WHERE p.category_id IN (
|
||||
SELECT id FROM categories
|
||||
WHERE id = ? OR parent_id = ?
|
||||
)
|
||||
)
|
||||
ORDER BY f.id
|
||||
""", (category_id,))
|
||||
""", (category_id, category_id))
|
||||
|
||||
attributes = []
|
||||
|
||||
@@ -46,21 +49,24 @@ def get_all_categories_with_attributes(db_name: str = 'pipe_store.db') -> List[D
|
||||
SELECT DISTINCT pf.value, COUNT(*) as count
|
||||
FROM product_filters pf
|
||||
JOIN products p ON pf.product_id = p.id
|
||||
WHERE p.category_id = ? AND pf.filter_key = ?
|
||||
WHERE p.category_id IN (
|
||||
SELECT id FROM categories
|
||||
WHERE id = ? OR parent_id = ?
|
||||
)
|
||||
AND pf.filter_key = ?
|
||||
GROUP BY pf.value
|
||||
ORDER BY pf.value
|
||||
""", (category_id, filter_key))
|
||||
""", (category_id, category_id, filter_key))
|
||||
|
||||
vals = []
|
||||
for val_row in cursor.fetchall():
|
||||
# Генерируем уникальный ID для значения
|
||||
val_id = hash(f"{category_id}_{filter_key}_{val_row['value']}") % 1000000
|
||||
vals.append({
|
||||
"id": val_id,
|
||||
"val": val_row['value']
|
||||
})
|
||||
|
||||
if vals: # Добавляем только если есть значения
|
||||
if vals:
|
||||
attributes.append({
|
||||
"id": filter_id,
|
||||
"name": filter_name,
|
||||
@@ -97,12 +103,28 @@ def get_category_by_id(category_id: int, db_name: str = 'pipe_store.db') -> Opti
|
||||
|
||||
row = cursor.fetchone()
|
||||
if row:
|
||||
# Получаем подкатегории
|
||||
cursor.execute("""
|
||||
SELECT id, name, image_path
|
||||
FROM categories
|
||||
WHERE parent_id = ?
|
||||
""", (category_id,))
|
||||
|
||||
subcategories = []
|
||||
for sub_row in cursor.fetchall():
|
||||
subcategories.append({
|
||||
"id": sub_row['id'],
|
||||
"name": sub_row['name'],
|
||||
"image": sub_row['image_path']
|
||||
})
|
||||
|
||||
return {
|
||||
"id": row['id'],
|
||||
"name": row['name'],
|
||||
"description": row['description'],
|
||||
"image": row['image_path'],
|
||||
"parent_id": row['parent_id']
|
||||
"parent_id": row['parent_id'],
|
||||
"subcategories": subcategories
|
||||
}
|
||||
return None
|
||||
|
||||
@@ -111,3 +133,34 @@ def get_category_by_id(category_id: int, db_name: str = 'pipe_store.db') -> Opti
|
||||
return None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def get_subcategories(parent_id: int, db_name: str = 'pipe_store.db') -> List[Dict[str, Any]]:
|
||||
"""Получить подкатегории для родительской категории"""
|
||||
conn = sqlite3.connect(db_name)
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT id, name, description, image_path
|
||||
FROM categories
|
||||
WHERE parent_id = ?
|
||||
ORDER BY id
|
||||
""", (parent_id,))
|
||||
|
||||
subcategories = []
|
||||
for row in cursor.fetchall():
|
||||
subcategories.append({
|
||||
"id": row['id'],
|
||||
"name": row['name'],
|
||||
"description": row['description'],
|
||||
"image": row['image_path']
|
||||
})
|
||||
|
||||
return subcategories
|
||||
|
||||
except sqlite3.Error as e:
|
||||
log.error(f"Ошибка при получении подкатегорий для {parent_id}: {e}")
|
||||
return []
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -77,11 +77,13 @@ def get_products_with_filters(
|
||||
# Формируем атрибуты товара
|
||||
attributes = {}
|
||||
|
||||
# Добавляем все возможные атрибуты
|
||||
if row['color']:
|
||||
attributes['color'] = row['color']
|
||||
if row['length']:
|
||||
attributes['size'] = f"{row['diameter']}x{row['wall_thickness']}x{row['length']}" if row['diameter'] else str(row['length'])
|
||||
if row['length'] and row['length'] > 0:
|
||||
if row['diameter'] and row['wall_thickness']:
|
||||
attributes['size'] = f"{row['diameter']}x{row['wall_thickness']}x{row['length']}"
|
||||
else:
|
||||
attributes['size'] = str(row['length'])
|
||||
if row['diameter']:
|
||||
attributes['diameter'] = str(row['diameter'])
|
||||
if row['wall_thickness']:
|
||||
@@ -91,18 +93,30 @@ def get_products_with_filters(
|
||||
if row['application_type']:
|
||||
attributes['application_type'] = row['application_type']
|
||||
|
||||
# Получаем дополнительные атрибуты из product_filters
|
||||
cursor.execute("""
|
||||
SELECT filter_key, value
|
||||
FROM product_filters
|
||||
WHERE product_id = ?
|
||||
""", (row['id'],))
|
||||
|
||||
for filter_row in cursor.fetchall():
|
||||
if filter_row['filter_key'] not in attributes:
|
||||
attributes[filter_row['filter_key']] = filter_row['value']
|
||||
|
||||
# Определяем количество в упаковке (можно вынести в отдельную таблицу)
|
||||
attributes['amount'] = get_pack_amount(row['id'], conn)
|
||||
attributes['amount'] = get_pack_amount(row['id'], row['diameter'], conn)
|
||||
|
||||
items.append({
|
||||
"id": row['id'],
|
||||
"name": row['name'],
|
||||
"description": row['description'] or f"Труба ПВХ {row['diameter']}мм",
|
||||
"price": calculate_price(row), # Функция для расчета цены
|
||||
"description": row['description'] or f"Труба ПВХ {row['diameter']}мм" if row['diameter'] else "Товар",
|
||||
# Цена не хранится в БД - возвращаем 0 или None
|
||||
"price": None,
|
||||
"categoryId": category_id,
|
||||
"images": get_product_images(row['id'], row['image_path'], conn),
|
||||
"attributes": attributes,
|
||||
"inStock": check_stock(row['id'], conn) # Проверка наличия
|
||||
"inStock": check_stock(row['id'], conn)
|
||||
})
|
||||
|
||||
return {
|
||||
@@ -122,13 +136,6 @@ def get_products_with_filters(
|
||||
def get_product_by_id(product_id: int, db_name: str = 'pipe_store.db') -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Получить товар по ID с полной информацией
|
||||
|
||||
Args:
|
||||
product_id: ID товара
|
||||
db_name: Имя базы данных
|
||||
|
||||
Returns:
|
||||
Dict с полной информацией о товаре или None
|
||||
"""
|
||||
conn = sqlite3.connect(db_name)
|
||||
conn.row_factory = sqlite3.Row
|
||||
@@ -148,29 +155,46 @@ def get_product_by_id(product_id: int, db_name: str = 'pipe_store.db') -> Option
|
||||
if not row:
|
||||
return None
|
||||
|
||||
# Получаем все изображения товара (если есть несколько)
|
||||
images = get_product_images(product_id, row['image_path'], conn)
|
||||
|
||||
# Формируем полное описание
|
||||
# Получаем дополнительные фильтры
|
||||
cursor.execute("""
|
||||
SELECT filter_key, value
|
||||
FROM product_filters
|
||||
WHERE product_id = ?
|
||||
""", (product_id,))
|
||||
|
||||
extra_attributes = {}
|
||||
for filter_row in cursor.fetchall():
|
||||
extra_attributes[filter_row['filter_key']] = filter_row['value']
|
||||
|
||||
full_description = generate_full_description(row)
|
||||
|
||||
# Формируем атрибуты
|
||||
attributes = {
|
||||
"color": row['color'],
|
||||
"diameter": str(row['diameter']) if row['diameter'] else None,
|
||||
"wall_thickness": str(row['wall_thickness']) if row['wall_thickness'] else None,
|
||||
"length": str(row['length']) if row['length'] and row['length'] > 0 else None,
|
||||
"stiffness_class": row['stiffness_class'],
|
||||
"application_type": row['application_type'],
|
||||
}
|
||||
|
||||
if all([row['diameter'], row['wall_thickness'], row['length'] and row['length'] > 0]):
|
||||
attributes["size"] = f"{row['diameter']}x{row['wall_thickness']}x{row['length']}"
|
||||
|
||||
# Добавляем дополнительные атрибуты
|
||||
attributes.update(extra_attributes)
|
||||
|
||||
return {
|
||||
"id": row['id'],
|
||||
"name": row['name'],
|
||||
"full_name": row['full_name'],
|
||||
"description": full_description,
|
||||
"price": calculate_price(row),
|
||||
"price": None, # Цена не хранится в БД
|
||||
"categoryId": row['category_id'],
|
||||
"images": images,
|
||||
"attributes": {
|
||||
"color": row['color'],
|
||||
"diameter": str(row['diameter']) if row['diameter'] else None,
|
||||
"wall_thickness": str(row['wall_thickness']) if row['wall_thickness'] else None,
|
||||
"length": str(row['length']) if row['length'] else None,
|
||||
"stiffness_class": row['stiffness_class'],
|
||||
"application_type": row['application_type'],
|
||||
"size": f"{row['diameter']}x{row['wall_thickness']}x{row['length']}" if all([row['diameter'], row['wall_thickness'], row['length']]) else None
|
||||
},
|
||||
"attributes": attributes,
|
||||
"inStock": check_stock(product_id, conn),
|
||||
"created_at": row['created_at']
|
||||
}
|
||||
@@ -182,57 +206,34 @@ def get_product_by_id(product_id: int, db_name: str = 'pipe_store.db') -> Option
|
||||
conn.close()
|
||||
|
||||
def get_product_images(product_id: int, main_image: Optional[str], conn: sqlite3.Connection) -> List[str]:
|
||||
"""
|
||||
Получить список изображений товара
|
||||
(В текущей структуре только одно изображение, но можно расширить)
|
||||
"""
|
||||
"""Получить список изображений товара"""
|
||||
images = []
|
||||
if main_image:
|
||||
images.append(main_image)
|
||||
|
||||
# Здесь можно добавить логику для получения дополнительных изображений
|
||||
# Например, из отдельной таблицы product_images
|
||||
|
||||
# Если нет изображения, возвращаем заглушку
|
||||
if not images:
|
||||
images.append("/images/products/default.jpg")
|
||||
|
||||
return images
|
||||
|
||||
def calculate_price(row: sqlite3.Row) -> float:
|
||||
"""
|
||||
Рассчитать цену товара на основе параметров
|
||||
(В реальном проекте цена должна быть в базе данных)
|
||||
"""
|
||||
# Временная логика расчета цены
|
||||
base_price = 500
|
||||
|
||||
if row['diameter']:
|
||||
base_price += (row['diameter'] - 50) * 5
|
||||
|
||||
if row['length']:
|
||||
base_price += row['length'] * 0.1
|
||||
|
||||
if row['stiffness_class'] == 'SN4':
|
||||
base_price *= 1.2
|
||||
|
||||
return round(base_price, 2)
|
||||
|
||||
def check_stock(product_id: int, conn: sqlite3.Connection) -> bool:
|
||||
"""
|
||||
Проверить наличие товара на складе
|
||||
(В реальном проекте должна быть таблица stock)
|
||||
"""
|
||||
"""Проверить наличие товара на складе"""
|
||||
# Временная логика - все товары в наличии
|
||||
# В будущем можно добавить таблицу stock
|
||||
return True
|
||||
|
||||
def get_pack_amount(product_id: int, conn: sqlite3.Connection) -> str:
|
||||
def get_pack_amount(product_id: int, diameter: int = None, conn: sqlite3.Connection = None) -> str:
|
||||
"""
|
||||
Получить количество в упаковке
|
||||
(В реальном проекте должно быть в базе данных)
|
||||
В реальном проекте должно быть в базе данных
|
||||
"""
|
||||
# Временная логика
|
||||
return "4"
|
||||
# Временная логика на основе диаметра
|
||||
if diameter:
|
||||
if diameter == 110:
|
||||
return "6-10"
|
||||
elif diameter == 160:
|
||||
return "2"
|
||||
return "1"
|
||||
|
||||
def generate_full_description(row: sqlite3.Row) -> str:
|
||||
"""Сгенерировать полное описание товара"""
|
||||
@@ -247,8 +248,10 @@ def generate_full_description(row: sqlite3.Row) -> str:
|
||||
if row['application_type']:
|
||||
parts.append(f"Тип применения: {row['application_type']} канализация")
|
||||
|
||||
if row['diameter'] and row['wall_thickness'] and row['length']:
|
||||
if row['diameter'] and row['wall_thickness'] and row['length'] and row['length'] > 0:
|
||||
parts.append(f"Размеры: {row['diameter']}x{row['wall_thickness']}x{row['length']} мм")
|
||||
elif row['diameter']:
|
||||
parts.append(f"Диаметр: {row['diameter']} мм")
|
||||
|
||||
if row['stiffness_class']:
|
||||
parts.append(f"Класс жесткости: {row['stiffness_class']}")
|
||||
|
||||
Reference in new issue
Block a user