169 lines
6.1 KiB
Python
169 lines
6.1 KiB
Python
import re
|
||
import sqlite3
|
||
from loguru import logger as log
|
||
|
||
def add_category(conn, name, description=None, parent_id=None, image_path=None):
|
||
cursor = conn.cursor()
|
||
|
||
try:
|
||
cursor.execute('''
|
||
INSERT OR IGNORE INTO categories (name, description, parent_id, image_path)
|
||
VALUES (?, ?, ?, ?)
|
||
''', (name, description, parent_id, image_path))
|
||
|
||
cursor.execute('SELECT id FROM categories WHERE name = ?', (name,))
|
||
result = cursor.fetchone()
|
||
category_id = result[0] if result else None
|
||
|
||
return category_id
|
||
except sqlite3.Error as e:
|
||
log.error(f"Ошибка при добавлении категории: {e}")
|
||
return None
|
||
|
||
def add_filter(conn, name, filter_key, filter_type='single'):
|
||
cursor = conn.cursor()
|
||
|
||
cursor.execute('''
|
||
INSERT OR IGNORE INTO filters (name, filter_key, filter_type)
|
||
VALUES (?, ?, ?)
|
||
''', (name, filter_key, filter_type))
|
||
|
||
def parse_product_data(product_text):
|
||
application_match = re.search(r'(ВНУТРЕННЕЙ|НАРУЖНОЙ)', product_text)
|
||
application_type = "внутренняя" if application_match and application_match.group(1) == "ВНУТРЕННЕЙ" else "наружная"
|
||
|
||
color_match = re.search(r'цвет\s+([^)]+)', product_text)
|
||
color = color_match.group(1).strip() if color_match else None
|
||
|
||
stiffness_match = re.search(r'SN(\d+)', product_text)
|
||
stiffness_class = f"SN{stiffness_match.group(1)}" if stiffness_match else None
|
||
|
||
size_match = re.search(r'(\d+)х(\d+[,.]?\d*)х(\d+)', product_text.replace(',', '.'))
|
||
if size_match:
|
||
diameter = int(size_match.group(1))
|
||
wall_thickness = float(size_match.group(2))
|
||
length = int(size_match.group(3))
|
||
else:
|
||
diameter = wall_thickness = length = None
|
||
|
||
short_name = f"Труба ПВХ {diameter}мм {application_type} {length}мм"
|
||
|
||
return {
|
||
'short_name': short_name,
|
||
'full_name': product_text,
|
||
'diameter': diameter,
|
||
'wall_thickness': wall_thickness,
|
||
'length': length,
|
||
'color': color,
|
||
'application_type': application_type,
|
||
'stiffness_class': stiffness_class
|
||
}
|
||
|
||
def add_product(conn, product_text, category_id, image_path=None):
|
||
"""Добавление товара с парсингом параметров и изображением"""
|
||
cursor = conn.cursor()
|
||
|
||
product_data = parse_product_data(product_text)
|
||
|
||
try:
|
||
cursor.execute('''
|
||
INSERT INTO products (
|
||
name, full_name, description, category_id,
|
||
diameter, wall_thickness, length, color,
|
||
application_type, stiffness_class, image_path
|
||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
''', (
|
||
product_data['short_name'],
|
||
product_data['full_name'],
|
||
f"Труба ПВХ для {product_data['application_type']} канализации",
|
||
category_id,
|
||
product_data['diameter'],
|
||
product_data['wall_thickness'],
|
||
product_data['length'],
|
||
product_data['color'],
|
||
product_data['application_type'],
|
||
product_data['stiffness_class'],
|
||
image_path
|
||
))
|
||
|
||
product_id = cursor.lastrowid
|
||
|
||
filters_to_add = [
|
||
('diameter', str(product_data['diameter'])),
|
||
('length', str(product_data['length'])),
|
||
('application_type', product_data['application_type']),
|
||
('color', product_data['color']),
|
||
]
|
||
|
||
if product_data['wall_thickness']:
|
||
filters_to_add.append(('wall_thickness', str(product_data['wall_thickness'])))
|
||
|
||
if product_data['stiffness_class']:
|
||
filters_to_add.append(('stiffness_class', product_data['stiffness_class']))
|
||
|
||
for filter_key, value in filters_to_add:
|
||
if value:
|
||
cursor.execute('''
|
||
INSERT OR IGNORE INTO product_filters (product_id, filter_key, value)
|
||
VALUES (?, ?, ?)
|
||
''', (product_id, filter_key, value))
|
||
|
||
return product_id
|
||
|
||
except sqlite3.Error as e:
|
||
log.error(f"Ошибка при добавлении товара: {e}")
|
||
return None
|
||
|
||
def get_categories_by_page(conn, page_number=1, items_per_page=9):
|
||
"""Получить категории для определенной страницы"""
|
||
cursor = conn.cursor()
|
||
offset = (page_number - 1) * items_per_page
|
||
|
||
cursor.execute('''
|
||
SELECT * FROM categories
|
||
ORDER BY id
|
||
LIMIT ? OFFSET ?
|
||
''', (items_per_page, offset))
|
||
|
||
return cursor.fetchall()
|
||
|
||
def get_products_by_page(conn, page_number=1, items_per_page=9, category_id=None):
|
||
"""Получить товары для определенной страницы"""
|
||
cursor = conn.cursor()
|
||
offset = (page_number - 1) * items_per_page
|
||
|
||
if category_id:
|
||
cursor.execute('''
|
||
SELECT * FROM products
|
||
WHERE category_id = ?
|
||
ORDER BY id
|
||
LIMIT ? OFFSET ?
|
||
''', (category_id, items_per_page, offset))
|
||
else:
|
||
cursor.execute('''
|
||
SELECT * FROM products
|
||
ORDER BY id
|
||
LIMIT ? OFFSET ?
|
||
''', (items_per_page, offset))
|
||
|
||
return cursor.fetchall()
|
||
|
||
def get_total_categories_pages(conn, items_per_page=9):
|
||
"""Получить общее количество страниц категорий"""
|
||
cursor = conn.cursor()
|
||
cursor.execute('SELECT COUNT(*) FROM categories')
|
||
total_categories = cursor.fetchone()[0]
|
||
return (total_categories + items_per_page - 1) // items_per_page
|
||
|
||
def get_total_products_pages(conn, items_per_page=9, category_id=None):
|
||
"""Получить общее количество страниц товаров"""
|
||
cursor = conn.cursor()
|
||
|
||
if category_id:
|
||
cursor.execute('SELECT COUNT(*) FROM products WHERE category_id = ?', (category_id,))
|
||
else:
|
||
cursor.execute('SELECT COUNT(*) FROM products')
|
||
|
||
total_products = cursor.fetchone()[0]
|
||
return (total_products + items_per_page - 1) // items_per_page
|