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
@@ -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