Update app.py
Browse files
app.py
CHANGED
|
@@ -25,7 +25,7 @@ load_dotenv()
|
|
| 25 |
app = Flask(__name__)
|
| 26 |
app.secret_key = 'your_unique_secret_key_gippo_312_shop_54321_no_login'
|
| 27 |
DATA_FILE = 'data.json'
|
| 28 |
-
SYNC_FILES =
|
| 29 |
REPO_ID = "Kgshop/metas"
|
| 30 |
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
|
| 31 |
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
|
|
@@ -209,7 +209,8 @@ def get_env_data(env_id):
|
|
| 209 |
env_data = {
|
| 210 |
'products': [], 'categories':[], 'orders': {}, 'employees':[], 'blocks':[],
|
| 211 |
'organization_info': default_organization_info,
|
| 212 |
-
'settings': default_settings
|
|
|
|
| 213 |
}
|
| 214 |
|
| 215 |
if 'products' not in env_data: env_data['products'] =[]
|
|
@@ -219,6 +220,7 @@ def get_env_data(env_id):
|
|
| 219 |
if 'settings' not in env_data: env_data['settings'] = default_settings
|
| 220 |
if 'employees' not in env_data: env_data['employees'] =[]
|
| 221 |
if 'blocks' not in env_data: env_data['blocks'] =[]
|
|
|
|
| 222 |
|
| 223 |
settings_changed = False
|
| 224 |
for key, value in default_settings.items():
|
|
@@ -234,15 +236,17 @@ def get_env_data(env_id):
|
|
| 234 |
if 'views' not in product:
|
| 235 |
product['views'] = 0
|
| 236 |
products_changed = True
|
| 237 |
-
if 'stock' not in product:
|
| 238 |
-
product['stock'] = 0
|
| 239 |
-
products_changed = True
|
| 240 |
-
if 'variant_stock' not in product:
|
| 241 |
-
product['variant_stock'] = {}
|
| 242 |
-
products_changed = True
|
| 243 |
if 'tags' not in product:
|
| 244 |
product['tags'] =[]
|
| 245 |
products_changed = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
if products_changed or settings_changed:
|
| 248 |
save_env_data(env_id, env_data)
|
|
@@ -1977,6 +1981,10 @@ REPORTS_TEMPLATE = '''
|
|
| 1977 |
th, td { padding: 12px; border-bottom: 1px solid #eee; text-align: left; }
|
| 1978 |
th { background: #f8f9fa; color: #135D66; }
|
| 1979 |
.btn-back { display: inline-flex; align-items: center; gap: 8px; margin-bottom: 20px; color: #135D66; text-decoration: none; font-weight: 600; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1980 |
</style>
|
| 1981 |
</head>
|
| 1982 |
<body>
|
|
@@ -1984,6 +1992,14 @@ REPORTS_TEMPLATE = '''
|
|
| 1984 |
<a href="{{ url_for('admin', env_id=env_id) }}" class="btn-back"><i class="fas fa-arrow-left"></i> Назад в админ-панель</a>
|
| 1985 |
<h1><i class="fas fa-chart-pie"></i> Отчеты (Режим 2 в 1)</h1>
|
| 1986 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1987 |
<div class="summary-cards">
|
| 1988 |
<div class="card">
|
| 1989 |
<h3>Всего заказов</h3>
|
|
@@ -2030,6 +2046,254 @@ REPORTS_TEMPLATE = '''
|
|
| 2030 |
</html>
|
| 2031 |
'''
|
| 2032 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2033 |
ADMIN_TEMPLATE = '''
|
| 2034 |
<!DOCTYPE html>
|
| 2035 |
<html lang="ru">
|
|
@@ -2169,6 +2433,10 @@ ADMIN_TEMPLATE = '''
|
|
| 2169 |
<div style="display: flex; gap: 10px; flex-wrap: wrap;">
|
| 2170 |
<a href="{{ url_for('history_page', env_id=env_id) }}" class="button btn-history"><i class="fas fa-history"></i> История продаж</a>
|
| 2171 |
{% if settings.env_mode == '2in1' %}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2172 |
<a href="{{ url_for('reports_page', env_id=env_id) }}" class="button" style="background-color: #f39c12; color: white;"><i class="fas fa-chart-pie"></i> Отчеты</a>
|
| 2173 |
{% endif %}
|
| 2174 |
<a href="{{ url_for('catalog', env_id=env_id) }}" class="button" style="background-color: var(--bg-medium); color: white;"><i class="fas fa-store"></i> Каталог</a>
|
|
@@ -2768,7 +3036,7 @@ ADMIN_TEMPLATE = '''
|
|
| 2768 |
|
| 2769 |
const variants = prompt("Варианты через запятую (например: S, M, L). Оставьте пустым, если нет:");
|
| 2770 |
|
| 2771 |
-
let stock =
|
| 2772 |
if (envMode === '2in1') {
|
| 2773 |
const stockStr = prompt("Остаток на складе (в шт):", "0");
|
| 2774 |
stock = parseInt(stockStr) || 0;
|
|
@@ -2784,7 +3052,8 @@ ADMIN_TEMPLATE = '''
|
|
| 2784 |
box_qty: boxQty,
|
| 2785 |
box_price: boxPrice,
|
| 2786 |
variants: variants || "",
|
| 2787 |
-
stock: stock
|
|
|
|
| 2788 |
});
|
| 2789 |
|
| 2790 |
updateHiddenTags(scope);
|
|
@@ -2991,7 +3260,8 @@ def create_environment():
|
|
| 2991 |
"business_type": "retail", "env_mode": env_mode, "welcome_message_enabled": False, "welcome_message_text": "Добро пожаловать в наш магазин!",
|
| 2992 |
"inventory_tracking": False, "admin_password_enabled": False, "admin_password": "",
|
| 2993 |
"checkout_fields_enabled": False, "checkout_fields": {"name": False, "phone": False, "city": False, "address": False, "zip": False}
|
| 2994 |
-
}
|
|
|
|
| 2995 |
}
|
| 2996 |
save_data(all_data)
|
| 2997 |
flash(f'Новая среда с ID {new_id} успешно создана.', 'success')
|
|
@@ -3057,16 +3327,42 @@ def admin_logout(env_id):
|
|
| 3057 |
session.pop(f'admin_auth_{env_id}', None)
|
| 3058 |
return redirect(url_for('admin_login', env_id=env_id))
|
| 3059 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3060 |
@app.route('/<env_id>/catalog')
|
| 3061 |
def catalog(env_id):
|
| 3062 |
data = get_env_data(env_id)
|
| 3063 |
all_products_raw = data.get('products',[])
|
| 3064 |
settings = data.get('settings', {})
|
| 3065 |
blocks = data.get('blocks',[])
|
|
|
|
|
|
|
| 3066 |
product_categories = set(p.get('category', 'Без категории') for p in all_products_raw)
|
| 3067 |
admin_categories = set(data.get('categories',[]))
|
| 3068 |
all_cat_names = sorted(list(product_categories.union(admin_categories)))
|
| 3069 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3070 |
products_sorted_for_js = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
|
| 3071 |
|
| 3072 |
products_by_category = {cat:[] for cat in all_cat_names}
|
|
@@ -3088,8 +3384,149 @@ def pos_page(env_id):
|
|
| 3088 |
if settings.get('env_mode') != '2in1':
|
| 3089 |
return "POS доступен только в режиме '2 в 1'", 403
|
| 3090 |
emp_id = request.args.get('emp', '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3091 |
products = data.get('products',[])
|
| 3092 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3093 |
|
| 3094 |
@app.route('/<env_id>/reports')
|
| 3095 |
def reports_page(env_id):
|
|
@@ -3100,17 +3537,32 @@ def reports_page(env_id):
|
|
| 3100 |
if settings.get('admin_password_enabled') and not session.get(f'admin_auth_{env_id}'):
|
| 3101 |
return redirect(url_for('admin_login', env_id=env_id))
|
| 3102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3103 |
orders = data.get('orders', {}).values()
|
|
|
|
| 3104 |
|
| 3105 |
-
|
| 3106 |
-
|
| 3107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3108 |
online_orders = total_orders - pos_orders
|
| 3109 |
|
| 3110 |
emp_stats = {}
|
| 3111 |
product_sales = {}
|
| 3112 |
|
| 3113 |
-
for o in
|
| 3114 |
emp = o.get('employee_name') or 'Прямой заказ'
|
| 3115 |
if emp not in emp_stats:
|
| 3116 |
emp_stats[emp] = {'count': 0, 'revenue': 0}
|
|
@@ -3130,7 +3582,7 @@ def reports_page(env_id):
|
|
| 3130 |
return render_template_string(
|
| 3131 |
REPORTS_TEMPLATE, env_id=env_id, settings=settings, currency_code=settings.get('currency_code', 'KGS'),
|
| 3132 |
total_orders=total_orders, total_revenue=total_revenue, pos_orders=pos_orders, online_orders=online_orders,
|
| 3133 |
-
emp_stats=emp_stats, top_products=top_products[:20]
|
| 3134 |
)
|
| 3135 |
|
| 3136 |
@app.route('/<env_id>/track_view/<product_id>', methods=['POST'])
|
|
@@ -3148,7 +3600,22 @@ def product_detail(env_id, index):
|
|
| 3148 |
data = get_env_data(env_id)
|
| 3149 |
all_products_raw = data.get('products',[])
|
| 3150 |
settings = data.get('settings', {})
|
| 3151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3152 |
products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
|
| 3153 |
try:
|
| 3154 |
product = products_sorted[index]
|
|
@@ -3187,6 +3654,7 @@ def create_order(env_id):
|
|
| 3187 |
|
| 3188 |
total_price = 0
|
| 3189 |
processed_cart =[]
|
|
|
|
| 3190 |
|
| 3191 |
for item in cart_items:
|
| 3192 |
if not all(k in item for k in ('name', 'quantity')):
|
|
@@ -3210,6 +3678,9 @@ def create_order(env_id):
|
|
| 3210 |
if 'TAG_' in c_color:
|
| 3211 |
tag_id = c_color.split('_VAR_')[0].replace('TAG_', '')
|
| 3212 |
tag_ref = next((t for t in product_ref.get('tags',[]) if t.get('id') == tag_id), None)
|
|
|
|
|
|
|
|
|
|
| 3213 |
|
| 3214 |
price = float(item.get('price', 0))
|
| 3215 |
discount_applied = False
|
|
@@ -3231,8 +3702,38 @@ def create_order(env_id):
|
|
| 3231 |
deduction = quantity
|
| 3232 |
if u_type == 'box':
|
| 3233 |
deduction = quantity * box_qty
|
| 3234 |
-
|
| 3235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3236 |
|
| 3237 |
processed_cart.append({
|
| 3238 |
"product_id": p_id, "name": item['name'], "price": price, "quantity": quantity,
|
|
@@ -3245,7 +3746,6 @@ def create_order(env_id):
|
|
| 3245 |
return jsonify({"error": "Неверная цена или количество в товаре."}), 400
|
| 3246 |
|
| 3247 |
order_id = f"{datetime.now(ALMATY_TZ).strftime('%Y%m%d%H%M%S')}-{uuid4().hex[:6]}"
|
| 3248 |
-
order_timestamp = datetime.now(ALMATY_TZ).strftime('%Y-%m-%d %H:%M:%S')
|
| 3249 |
|
| 3250 |
new_order = {
|
| 3251 |
"id": order_id, "created_at": order_timestamp, "cart": processed_cart,
|
|
@@ -3581,9 +4081,13 @@ def admin(env_id):
|
|
| 3581 |
|
| 3582 |
tags_raw = request.form.get('tags_json', '[]')
|
| 3583 |
try:
|
| 3584 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3585 |
except:
|
| 3586 |
-
product_data['tags'] =
|
| 3587 |
|
| 3588 |
product_data['in_stock'] = 'in_stock' in request.form
|
| 3589 |
product_data['is_top'] = 'is_top' in request.form
|
|
@@ -3606,7 +4110,7 @@ def admin(env_id):
|
|
| 3606 |
if photo and photo.filename:
|
| 3607 |
try:
|
| 3608 |
ext = os.path.splitext(photo.filename)[1].lower()
|
| 3609 |
-
if ext not in
|
| 3610 |
safe_name = secure_filename(product_data['name'].replace(' ', '_'))[:50]
|
| 3611 |
photo_filename = f"{safe_name}_{uuid4().hex[:8]}{ext}"
|
| 3612 |
temp_path = os.path.join(uploads_dir, photo_filename)
|
|
@@ -3686,11 +4190,18 @@ def admin(env_id):
|
|
| 3686 |
chat_status = { "active": False, "expires_soon": False, "expires_date": "N/A" }
|
| 3687 |
chat_avatar_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/avatars/{display_settings['chat_avatar']}" if display_settings.get('chat_avatar') else "https://huggingface.co/spaces/gippo312/admin/resolve/main/Picsart_25-11-04_12-02-21-390.png"
|
| 3688 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3689 |
return render_template_string(
|
| 3690 |
ADMIN_TEMPLATE, paginated_products=paginated_products, total_pages=total_pages, page=page, search_q=search_q, categories=display_categories,
|
| 3691 |
organization_info=display_organization_info, chats={}, settings=display_settings, employees=employees,
|
| 3692 |
blocks=blocks, repo_id=REPO_ID, currency_code=display_settings.get('currency_code', 'KGS'), chat_avatar_url=chat_avatar_url,
|
| 3693 |
-
currencies=CURRENCIES, color_schemes=COLOR_SCHEMES, env_id=env_id, chat_status=chat_status
|
| 3694 |
)
|
| 3695 |
|
| 3696 |
@app.route('/generate_description_ai', methods=['POST'])
|
|
|
|
| 25 |
app = Flask(__name__)
|
| 26 |
app.secret_key = 'your_unique_secret_key_gippo_312_shop_54321_no_login'
|
| 27 |
DATA_FILE = 'data.json'
|
| 28 |
+
SYNC_FILES =[DATA_FILE]
|
| 29 |
REPO_ID = "Kgshop/metas"
|
| 30 |
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
|
| 31 |
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
|
|
|
|
| 209 |
env_data = {
|
| 210 |
'products': [], 'categories':[], 'orders': {}, 'employees':[], 'blocks':[],
|
| 211 |
'organization_info': default_organization_info,
|
| 212 |
+
'settings': default_settings,
|
| 213 |
+
'inventory_history':[]
|
| 214 |
}
|
| 215 |
|
| 216 |
if 'products' not in env_data: env_data['products'] =[]
|
|
|
|
| 220 |
if 'settings' not in env_data: env_data['settings'] = default_settings
|
| 221 |
if 'employees' not in env_data: env_data['employees'] =[]
|
| 222 |
if 'blocks' not in env_data: env_data['blocks'] =[]
|
| 223 |
+
if 'inventory_history' not in env_data: env_data['inventory_history'] =[]
|
| 224 |
|
| 225 |
settings_changed = False
|
| 226 |
for key, value in default_settings.items():
|
|
|
|
| 236 |
if 'views' not in product:
|
| 237 |
product['views'] = 0
|
| 238 |
products_changed = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
if 'tags' not in product:
|
| 240 |
product['tags'] =[]
|
| 241 |
products_changed = True
|
| 242 |
+
else:
|
| 243 |
+
for tag in product['tags']:
|
| 244 |
+
if 'stock' not in tag:
|
| 245 |
+
tag['stock'] = 0
|
| 246 |
+
products_changed = True
|
| 247 |
+
if 'stock_batches' not in tag:
|
| 248 |
+
tag['stock_batches'] = [{"qty": tag['stock'], "price": tag.get('price', 0), "box_price": tag.get('box_price', 0)}]
|
| 249 |
+
products_changed = True
|
| 250 |
|
| 251 |
if products_changed or settings_changed:
|
| 252 |
save_env_data(env_id, env_data)
|
|
|
|
| 1981 |
th, td { padding: 12px; border-bottom: 1px solid #eee; text-align: left; }
|
| 1982 |
th { background: #f8f9fa; color: #135D66; }
|
| 1983 |
.btn-back { display: inline-flex; align-items: center; gap: 8px; margin-bottom: 20px; color: #135D66; text-decoration: none; font-weight: 600; }
|
| 1984 |
+
.button { padding: 10px 20px; border: none; border-radius: 8px; background-color: #48D1CC; color: #003C43; font-weight: 600; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 5px; min-height: 44px; }
|
| 1985 |
+
.button:hover { background-color: #77E4D8; }
|
| 1986 |
+
input[type="date"] { padding: 10px; border: 1px solid #ddd; border-radius: 8px; font-family: inherit; font-size: 1rem; outline: none; }
|
| 1987 |
+
.filter-form { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; background: #fdfdff; padding: 15px; border-radius: 8px; border: 1px solid #e0e0e0; margin-bottom: 20px; }
|
| 1988 |
</style>
|
| 1989 |
</head>
|
| 1990 |
<body>
|
|
|
|
| 1992 |
<a href="{{ url_for('admin', env_id=env_id) }}" class="btn-back"><i class="fas fa-arrow-left"></i> Назад в админ-панель</a>
|
| 1993 |
<h1><i class="fas fa-chart-pie"></i> Отчеты (Режим 2 в 1)</h1>
|
| 1994 |
|
| 1995 |
+
<form class="filter-form" method="GET" action="{{ url_for('reports_page', env_id=env_id) }}">
|
| 1996 |
+
<label style="font-weight: 600;">Период с:</label>
|
| 1997 |
+
<input type="date" name="start_date" value="{{ start_date }}" required>
|
| 1998 |
+
<label style="font-weight: 600;">По:</label>
|
| 1999 |
+
<input type="date" name="end_date" value="{{ end_date }}" required>
|
| 2000 |
+
<button type="submit" class="button"><i class="fas fa-filter"></i> Применить</button>
|
| 2001 |
+
</form>
|
| 2002 |
+
|
| 2003 |
<div class="summary-cards">
|
| 2004 |
<div class="card">
|
| 2005 |
<h3>Всего заказов</h3>
|
|
|
|
| 2046 |
</html>
|
| 2047 |
'''
|
| 2048 |
|
| 2049 |
+
INVENTORY_TEMPLATE = '''
|
| 2050 |
+
<!DOCTYPE html>
|
| 2051 |
+
<html lang="ru">
|
| 2052 |
+
<head>
|
| 2053 |
+
<meta charset="UTF-8">
|
| 2054 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 2055 |
+
<title>Остатки - {{ settings.organization_name }}</title>
|
| 2056 |
+
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600&display=swap" rel="stylesheet">
|
| 2057 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
| 2058 |
+
<style>
|
| 2059 |
+
:root { --bg-light: #f4f6f9; --bg-medium: #135D66; --accent: #48D1CC; --accent-hover: #77E4D8; --text-dark: #333; --danger: #E57373; --success: #28a745; }
|
| 2060 |
+
* { box-sizing: border-box; }
|
| 2061 |
+
body { font-family: 'Montserrat', sans-serif; background-color: var(--bg-light); color: var(--text-dark); padding: 20px; line-height: 1.6; margin: 0; }
|
| 2062 |
+
.container { max-width: 1200px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); }
|
| 2063 |
+
h1 { color: var(--bg-medium); margin-bottom: 20px; }
|
| 2064 |
+
.btn-back { display: inline-flex; align-items: center; gap: 8px; margin-bottom: 20px; color: var(--bg-medium); text-decoration: none; font-weight: 600; min-height: 44px; }
|
| 2065 |
+
.tabs { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
|
| 2066 |
+
.tab { padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; background: #eee; border: none; transition: 0.2s; }
|
| 2067 |
+
.tab.active { background: var(--bg-medium); color: white; }
|
| 2068 |
+
.search-box { margin-bottom: 20px; width: 100%; }
|
| 2069 |
+
.search-box input { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 1rem; outline: none; }
|
| 2070 |
+
table { width: 100%; border-collapse: collapse; min-width: 800px; }
|
| 2071 |
+
.table-container { overflow-x: auto; }
|
| 2072 |
+
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
|
| 2073 |
+
th { background-color: #f8f9fa; color: var(--bg-medium); font-weight: 600; }
|
| 2074 |
+
.action-btn { padding: 8px 12px; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-right: 5px; color: white; font-size: 0.85rem; }
|
| 2075 |
+
.btn-add { background: var(--success); }
|
| 2076 |
+
.btn-writeoff { background: var(--danger); }
|
| 2077 |
+
.btn-history { background: #6c757d; }
|
| 2078 |
+
.low-stock { color: var(--danger); font-weight: bold; }
|
| 2079 |
+
.modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); align-items: center; justify-content: center; }
|
| 2080 |
+
.modal-content { background: #fff; padding: 25px; border-radius: 12px; width: 90%; max-width: 500px; display: flex; flex-direction: column; gap: 15px; }
|
| 2081 |
+
.modal-header { display: flex; justify-content: space-between; font-weight: bold; font-size: 1.2rem; color: var(--bg-medium); }
|
| 2082 |
+
.close-modal { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #666; }
|
| 2083 |
+
.form-group { display: flex; flex-direction: column; gap: 5px; }
|
| 2084 |
+
.form-group input[type="number"], .form-group input[type="text"] { padding: 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 1rem; }
|
| 2085 |
+
.form-group label { font-size: 0.9rem; font-weight: 600; color: #555; }
|
| 2086 |
+
.submit-btn { padding: 12px; background: var(--accent); color: #003C43; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 1rem; }
|
| 2087 |
+
.history-list { max-height: 300px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; }
|
| 2088 |
+
.history-item { background: #f9f9f9; padding: 10px; border-radius: 6px; border: 1px solid #eee; font-size: 0.9rem; }
|
| 2089 |
+
.history-date { color: #888; font-size: 0.8rem; margin-bottom: 5px; }
|
| 2090 |
+
.badge { background: red; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.8rem; margin-left: 5px; }
|
| 2091 |
+
</style>
|
| 2092 |
+
</head>
|
| 2093 |
+
<body>
|
| 2094 |
+
<div class="container">
|
| 2095 |
+
<a href="{{ url_for('admin', env_id=env_id) }}" class="btn-back"><i class="fas fa-arrow-left"></i> Назад в админ-панель</a>
|
| 2096 |
+
<h1><i class="fas fa-boxes"></i> Управление остатками</h1>
|
| 2097 |
+
|
| 2098 |
+
<div class="tabs">
|
| 2099 |
+
<button class="tab active" onclick="filterTab('all')">Все товары</button>
|
| 2100 |
+
<button class="tab" onclick="filterTab('low')">Заканчивающиеся {% if low_stock_count > 0 %}<span class="badge">{{ low_stock_count }}</span>{% endif %}</button>
|
| 2101 |
+
</div>
|
| 2102 |
+
|
| 2103 |
+
<div class="search-box">
|
| 2104 |
+
<input type="text" id="searchInput" placeholder="Поиск по названию..." oninput="filterTable()">
|
| 2105 |
+
</div>
|
| 2106 |
+
|
| 2107 |
+
<div class="table-container">
|
| 2108 |
+
<table id="invTable">
|
| 2109 |
+
<thead>
|
| 2110 |
+
<tr>
|
| 2111 |
+
<th>Товар</th>
|
| 2112 |
+
<th>Вариант</th>
|
| 2113 |
+
<th>Остаток</th>
|
| 2114 |
+
<th>Цена шт.</th>
|
| 2115 |
+
<th>Действия</th>
|
| 2116 |
+
</tr>
|
| 2117 |
+
</thead>
|
| 2118 |
+
<tbody>
|
| 2119 |
+
{% for item in items %}
|
| 2120 |
+
<tr class="inv-row" data-name="{{ item.product_name | lower }} {{ item.tag_name | lower }}" data-is-low="{{ 'true' if item.is_low else 'false' }}">
|
| 2121 |
+
<td>{{ item.product_name }}</td>
|
| 2122 |
+
<td>{{ item.tag_name }}</td>
|
| 2123 |
+
<td class="{{ 'low-stock' if item.is_low else '' }}">{{ item.stock }}</td>
|
| 2124 |
+
<td>{{ item.price }} {{ currency_code }}</td>
|
| 2125 |
+
<td>
|
| 2126 |
+
<button class="action-btn btn-add" onclick="openAddModal('{{ item.product_id }}', '{{ item.tag_id }}', '{{ item.product_name }} - {{ item.tag_name }}')"><i class="fas fa-plus"></i></button>
|
| 2127 |
+
<button class="action-btn btn-writeoff" onclick="openWriteOffModal('{{ item.product_id }}', '{{ item.tag_id }}', '{{ item.product_name }} - {{ item.tag_name }}')"><i class="fas fa-minus"></i></button>
|
| 2128 |
+
<button class="action-btn btn-history" onclick="openHistoryModal('{{ item.product_id }}', '{{ item.tag_id }}')"><i class="fas fa-history"></i></button>
|
| 2129 |
+
</td>
|
| 2130 |
+
</tr>
|
| 2131 |
+
{% endfor %}
|
| 2132 |
+
</tbody>
|
| 2133 |
+
</table>
|
| 2134 |
+
</div>
|
| 2135 |
+
</div>
|
| 2136 |
+
|
| 2137 |
+
<div id="addModal" class="modal" onclick="closeModal('addModal')">
|
| 2138 |
+
<div class="modal-content" onclick="event.stopPropagation()">
|
| 2139 |
+
<div class="modal-header">
|
| 2140 |
+
<span>Оприходовать</span>
|
| 2141 |
+
<button class="close-modal" onclick="closeModal('addModal')">×</button>
|
| 2142 |
+
</div>
|
| 2143 |
+
<div style="font-weight: 600; color: var(--bg-medium);" id="addTitle"></div>
|
| 2144 |
+
<div class="form-group">
|
| 2145 |
+
<label>Количество (шт):</label>
|
| 2146 |
+
<input type="number" id="addQty" min="1" value="1">
|
| 2147 |
+
</div>
|
| 2148 |
+
<div class="form-group" style="flex-direction: row; align-items: center;">
|
| 2149 |
+
<input type="checkbox" id="addCheckNewPrice" onchange="document.getElementById('newPriceFields').style.display = this.checked ? 'flex' : 'none';" style="width:auto;">
|
| 2150 |
+
<label for="addCheckNewPrice" style="margin:0; cursor:pointer;">Оприходовать по новой цене</label>
|
| 2151 |
+
</div>
|
| 2152 |
+
<div id="newPriceFields" style="display: none; flex-direction: column; gap: 15px;">
|
| 2153 |
+
<div class="form-group">
|
| 2154 |
+
<label>Новая цена за шт:</label>
|
| 2155 |
+
<input type="number" id="addPrice" step="0.01">
|
| 2156 |
+
</div>
|
| 2157 |
+
{% if settings.business_type != 'retail' %}
|
| 2158 |
+
<div class="form-group">
|
| 2159 |
+
<label>Новая цена за упаковку:</label>
|
| 2160 |
+
<input type="number" id="addBoxPrice" step="0.01">
|
| 2161 |
+
</div>
|
| 2162 |
+
{% endif %}
|
| 2163 |
+
</div>
|
| 2164 |
+
<button class="submit-btn" onclick="submitAction('add')">Применить</button>
|
| 2165 |
+
</div>
|
| 2166 |
+
</div>
|
| 2167 |
+
|
| 2168 |
+
<div id="writeoffModal" class="modal" onclick="closeModal('writeoffModal')">
|
| 2169 |
+
<div class="modal-content" onclick="event.stopPropagation()">
|
| 2170 |
+
<div class="modal-header">
|
| 2171 |
+
<span>Списать</span>
|
| 2172 |
+
<button class="close-modal" onclick="closeModal('writeoffModal')">×</button>
|
| 2173 |
+
</div>
|
| 2174 |
+
<div style="font-weight: 600; color: var(--danger);" id="woTitle"></div>
|
| 2175 |
+
<div class="form-group">
|
| 2176 |
+
<label>Количество (шт):</label>
|
| 2177 |
+
<input type="number" id="woQty" min="1" value="1">
|
| 2178 |
+
</div>
|
| 2179 |
+
<button class="submit-btn" style="background: var(--danger); color: white;" onclick="submitAction('write_off')">Списать</button>
|
| 2180 |
+
</div>
|
| 2181 |
+
</div>
|
| 2182 |
+
|
| 2183 |
+
<div id="historyModal" class="modal" onclick="closeModal('historyModal')">
|
| 2184 |
+
<div class="modal-content" onclick="event.stopPropagation()">
|
| 2185 |
+
<div class="modal-header">
|
| 2186 |
+
<span>История движений</span>
|
| 2187 |
+
<button class="close-modal" onclick="closeModal('historyModal')">×</button>
|
| 2188 |
+
</div>
|
| 2189 |
+
<div class="history-list" id="historyList">Загрузка...</div>
|
| 2190 |
+
</div>
|
| 2191 |
+
</div>
|
| 2192 |
+
|
| 2193 |
+
<script>
|
| 2194 |
+
let currentFilter = 'all';
|
| 2195 |
+
let actionData = {};
|
| 2196 |
+
const envId = '{{ env_id }}';
|
| 2197 |
+
|
| 2198 |
+
function filterTab(type) {
|
| 2199 |
+
currentFilter = type;
|
| 2200 |
+
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
| 2201 |
+
event.target.classList.add('active');
|
| 2202 |
+
filterTable();
|
| 2203 |
+
}
|
| 2204 |
+
|
| 2205 |
+
function filterTable() {
|
| 2206 |
+
const search = document.getElementById('searchInput').value.toLowerCase();
|
| 2207 |
+
document.querySelectorAll('.inv-row').forEach(row => {
|
| 2208 |
+
const name = row.getAttribute('data-name');
|
| 2209 |
+
const isLow = row.getAttribute('data-is-low') === 'true';
|
| 2210 |
+
const matchSearch = name.includes(search);
|
| 2211 |
+
const matchTab = currentFilter === 'all' || (currentFilter === 'low' && isLow);
|
| 2212 |
+
row.style.display = (matchSearch && matchTab) ? '' : 'none';
|
| 2213 |
+
});
|
| 2214 |
+
}
|
| 2215 |
+
|
| 2216 |
+
function openAddModal(pId, tId, title) {
|
| 2217 |
+
actionData = { pId, tId };
|
| 2218 |
+
document.getElementById('addTitle').textContent = title;
|
| 2219 |
+
document.getElementById('addQty').value = 1;
|
| 2220 |
+
document.getElementById('addCheckNewPrice').checked = false;
|
| 2221 |
+
document.getElementById('newPriceFields').style.display = 'none';
|
| 2222 |
+
document.getElementById('addPrice').value = '';
|
| 2223 |
+
const bp = document.getElementById('addBoxPrice');
|
| 2224 |
+
if(bp) bp.value = '';
|
| 2225 |
+
document.getElementById('addModal').style.display = 'flex';
|
| 2226 |
+
}
|
| 2227 |
+
|
| 2228 |
+
function openWriteOffModal(pId, tId, title) {
|
| 2229 |
+
actionData = { pId, tId };
|
| 2230 |
+
document.getElementById('woTitle').textContent = title;
|
| 2231 |
+
document.getElementById('woQty').value = 1;
|
| 2232 |
+
document.getElementById('writeoffModal').style.display = 'flex';
|
| 2233 |
+
}
|
| 2234 |
+
|
| 2235 |
+
function closeModal(id) {
|
| 2236 |
+
document.getElementById(id).style.display = 'none';
|
| 2237 |
+
}
|
| 2238 |
+
|
| 2239 |
+
function submitAction(action) {
|
| 2240 |
+
const qty = parseInt(document.getElementById(action === 'add' ? 'addQty' : 'woQty').value);
|
| 2241 |
+
if(isNaN(qty) || qty <= 0) return alert('Неверное количество');
|
| 2242 |
+
|
| 2243 |
+
const payload = {
|
| 2244 |
+
product_id: actionData.pId,
|
| 2245 |
+
tag_id: actionData.tId,
|
| 2246 |
+
action: action,
|
| 2247 |
+
qty: qty
|
| 2248 |
+
};
|
| 2249 |
+
|
| 2250 |
+
if(action === 'add' && document.getElementById('addCheckNewPrice').checked) {
|
| 2251 |
+
const price = document.getElementById('addPrice').value;
|
| 2252 |
+
if(!price) return alert('Укажите новую цену');
|
| 2253 |
+
payload.new_price = price;
|
| 2254 |
+
const bp = document.getElementById('addBoxPrice');
|
| 2255 |
+
if(bp && bp.value) payload.new_box_price = bp.value;
|
| 2256 |
+
}
|
| 2257 |
+
|
| 2258 |
+
fetch(`/${envId}/inventory_action`, {
|
| 2259 |
+
method: 'POST', headers: {'Content-Type': 'application/json'},
|
| 2260 |
+
body: JSON.stringify(payload)
|
| 2261 |
+
}).then(r => r.json()).then(data => {
|
| 2262 |
+
if(data.success) {
|
| 2263 |
+
location.reload();
|
| 2264 |
+
} else {
|
| 2265 |
+
alert(data.error || 'Ошибка');
|
| 2266 |
+
}
|
| 2267 |
+
}).catch(e => alert('Сетевая ошибка'));
|
| 2268 |
+
}
|
| 2269 |
+
|
| 2270 |
+
function openHistoryModal(pId, tId) {
|
| 2271 |
+
document.getElementById('historyModal').style.display = 'flex';
|
| 2272 |
+
const list = document.getElementById('historyList');
|
| 2273 |
+
list.innerHTML = 'Загрузка...';
|
| 2274 |
+
|
| 2275 |
+
fetch(`/${envId}/inventory_history/${pId}/${tId}`)
|
| 2276 |
+
.then(r => r.json())
|
| 2277 |
+
.then(data => {
|
| 2278 |
+
if(data.length === 0) {
|
| 2279 |
+
list.innerHTML = 'История пуста';
|
| 2280 |
+
return;
|
| 2281 |
+
}
|
| 2282 |
+
list.innerHTML = data.map(h => {
|
| 2283 |
+
let typeColor = h.type === 'add' ? 'green' : (h.type === 'sale' ? 'blue' : 'red');
|
| 2284 |
+
let sign = h.type === 'add' ? '+' : '-';
|
| 2285 |
+
return `<div class="history-item">
|
| 2286 |
+
<div class="history-date">${h.timestamp}</div>
|
| 2287 |
+
<div><strong style="color:${typeColor}">${sign}${h.qty} шт</strong> - ${h.details}</div>
|
| 2288 |
+
</div>`;
|
| 2289 |
+
}).join('');
|
| 2290 |
+
}).catch(e => list.innerHTML = 'Ошибка загрузки');
|
| 2291 |
+
}
|
| 2292 |
+
</script>
|
| 2293 |
+
</body>
|
| 2294 |
+
</html>
|
| 2295 |
+
'''
|
| 2296 |
+
|
| 2297 |
ADMIN_TEMPLATE = '''
|
| 2298 |
<!DOCTYPE html>
|
| 2299 |
<html lang="ru">
|
|
|
|
| 2433 |
<div style="display: flex; gap: 10px; flex-wrap: wrap;">
|
| 2434 |
<a href="{{ url_for('history_page', env_id=env_id) }}" class="button btn-history"><i class="fas fa-history"></i> История продаж</a>
|
| 2435 |
{% if settings.env_mode == '2in1' %}
|
| 2436 |
+
<a href="{{ url_for('inventory_page', env_id=env_id) }}" class="button" style="background-color: #17a2b8; color: white;">
|
| 2437 |
+
<i class="fas fa-boxes"></i> Остатки
|
| 2438 |
+
{% if low_stock_count > 0 %}<span style="background:red;color:white;border-radius:50%;padding:2px 6px;font-size:0.8rem;margin-left:5px;">{{ low_stock_count }}</span>{% endif %}
|
| 2439 |
+
</a>
|
| 2440 |
<a href="{{ url_for('reports_page', env_id=env_id) }}" class="button" style="background-color: #f39c12; color: white;"><i class="fas fa-chart-pie"></i> Отчеты</a>
|
| 2441 |
{% endif %}
|
| 2442 |
<a href="{{ url_for('catalog', env_id=env_id) }}" class="button" style="background-color: var(--bg-medium); color: white;"><i class="fas fa-store"></i> Каталог</a>
|
|
|
|
| 3036 |
|
| 3037 |
const variants = prompt("Варианты через запятую (например: S, M, L). Оставьте пустым, если нет:");
|
| 3038 |
|
| 3039 |
+
let stock = 0;
|
| 3040 |
if (envMode === '2in1') {
|
| 3041 |
const stockStr = prompt("Остаток на складе (в шт):", "0");
|
| 3042 |
stock = parseInt(stockStr) || 0;
|
|
|
|
| 3052 |
box_qty: boxQty,
|
| 3053 |
box_price: boxPrice,
|
| 3054 |
variants: variants || "",
|
| 3055 |
+
stock: stock,
|
| 3056 |
+
stock_batches: [{"qty": stock, "price": price, "box_price": boxPrice}]
|
| 3057 |
});
|
| 3058 |
|
| 3059 |
updateHiddenTags(scope);
|
|
|
|
| 3260 |
"business_type": "retail", "env_mode": env_mode, "welcome_message_enabled": False, "welcome_message_text": "Добро пожаловать в наш магазин!",
|
| 3261 |
"inventory_tracking": False, "admin_password_enabled": False, "admin_password": "",
|
| 3262 |
"checkout_fields_enabled": False, "checkout_fields": {"name": False, "phone": False, "city": False, "address": False, "zip": False}
|
| 3263 |
+
},
|
| 3264 |
+
'inventory_history':[]
|
| 3265 |
}
|
| 3266 |
save_data(all_data)
|
| 3267 |
flash(f'Новая среда с ID {new_id} успешно создана.', 'success')
|
|
|
|
| 3327 |
session.pop(f'admin_auth_{env_id}', None)
|
| 3328 |
return redirect(url_for('admin_login', env_id=env_id))
|
| 3329 |
|
| 3330 |
+
def update_tag_price_from_batches(tag):
|
| 3331 |
+
if 'stock_batches' in tag:
|
| 3332 |
+
for batch in tag['stock_batches']:
|
| 3333 |
+
if batch.get('qty', 0) > 0:
|
| 3334 |
+
tag['price'] = batch.get('price', tag.get('price'))
|
| 3335 |
+
tag['box_price'] = batch.get('box_price', tag.get('box_price'))
|
| 3336 |
+
break
|
| 3337 |
+
|
| 3338 |
@app.route('/<env_id>/catalog')
|
| 3339 |
def catalog(env_id):
|
| 3340 |
data = get_env_data(env_id)
|
| 3341 |
all_products_raw = data.get('products',[])
|
| 3342 |
settings = data.get('settings', {})
|
| 3343 |
blocks = data.get('blocks',[])
|
| 3344 |
+
env_mode = settings.get('env_mode', 'external')
|
| 3345 |
+
|
| 3346 |
product_categories = set(p.get('category', 'Без категории') for p in all_products_raw)
|
| 3347 |
admin_categories = set(data.get('categories',[]))
|
| 3348 |
all_cat_names = sorted(list(product_categories.union(admin_categories)))
|
| 3349 |
+
|
| 3350 |
+
products_in_stock =[]
|
| 3351 |
+
for p in all_products_raw:
|
| 3352 |
+
if not p.get('in_stock', True):
|
| 3353 |
+
continue
|
| 3354 |
+
|
| 3355 |
+
if env_mode == '2in1':
|
| 3356 |
+
valid_tags =[t for t in p.get('tags', []) if t.get('stock', 0) > 0]
|
| 3357 |
+
if not valid_tags and p.get('tags',[]):
|
| 3358 |
+
continue
|
| 3359 |
+
|
| 3360 |
+
p_copy = p.copy()
|
| 3361 |
+
p_copy['tags'] = valid_tags
|
| 3362 |
+
products_in_stock.append(p_copy)
|
| 3363 |
+
else:
|
| 3364 |
+
products_in_stock.append(p)
|
| 3365 |
+
|
| 3366 |
products_sorted_for_js = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
|
| 3367 |
|
| 3368 |
products_by_category = {cat:[] for cat in all_cat_names}
|
|
|
|
| 3384 |
if settings.get('env_mode') != '2in1':
|
| 3385 |
return "POS доступен только в режиме '2 в 1'", 403
|
| 3386 |
emp_id = request.args.get('emp', '')
|
| 3387 |
+
all_products_raw = data.get('products',[])
|
| 3388 |
+
|
| 3389 |
+
products_in_stock =[]
|
| 3390 |
+
for p in all_products_raw:
|
| 3391 |
+
if not p.get('in_stock', True):
|
| 3392 |
+
continue
|
| 3393 |
+
valid_tags =[t for t in p.get('tags', []) if t.get('stock', 0) > 0]
|
| 3394 |
+
if not valid_tags and p.get('tags',[]):
|
| 3395 |
+
continue
|
| 3396 |
+
p_copy = p.copy()
|
| 3397 |
+
p_copy['tags'] = valid_tags
|
| 3398 |
+
products_in_stock.append(p_copy)
|
| 3399 |
+
|
| 3400 |
+
return render_template_string(POS_TEMPLATE, products_json=json.dumps(products_in_stock), settings=settings, currency_code=settings.get('currency_code', 'KGS'), env_id=env_id, emp_id=emp_id, repo_id=REPO_ID)
|
| 3401 |
+
|
| 3402 |
+
@app.route('/<env_id>/inventory')
|
| 3403 |
+
def inventory_page(env_id):
|
| 3404 |
+
data = get_env_data(env_id)
|
| 3405 |
+
settings = data.get('settings', {})
|
| 3406 |
+
if settings.get('env_mode') != '2in1':
|
| 3407 |
+
return "Остатки доступны только в режиме '2 в 1'", 403
|
| 3408 |
+
if settings.get('admin_password_enabled') and not session.get(f'admin_auth_{env_id}'):
|
| 3409 |
+
return redirect(url_for('admin_login', env_id=env_id))
|
| 3410 |
+
|
| 3411 |
+
products = data.get('products', [])
|
| 3412 |
+
items =[]
|
| 3413 |
+
low_stock_count = 0
|
| 3414 |
+
|
| 3415 |
+
for p in products:
|
| 3416 |
+
for t in p.get('tags',[]):
|
| 3417 |
+
stock = t.get('stock', 0)
|
| 3418 |
+
is_low = stock <= 50
|
| 3419 |
+
if is_low: low_stock_count += 1
|
| 3420 |
+
|
| 3421 |
+
items.append({
|
| 3422 |
+
'product_id': p.get('product_id'),
|
| 3423 |
+
'product_name': p.get('name'),
|
| 3424 |
+
'tag_id': t.get('id'),
|
| 3425 |
+
'tag_name': t.get('name'),
|
| 3426 |
+
'stock': stock,
|
| 3427 |
+
'price': t.get('price', 0),
|
| 3428 |
+
'is_low': is_low
|
| 3429 |
+
})
|
| 3430 |
+
|
| 3431 |
+
items.sort(key=lambda x: x['product_name'])
|
| 3432 |
+
|
| 3433 |
+
return render_template_string(
|
| 3434 |
+
INVENTORY_TEMPLATE,
|
| 3435 |
+
env_id=env_id, settings=settings, currency_code=settings.get('currency_code', 'KGS'),
|
| 3436 |
+
items=items, low_stock_count=low_stock_count
|
| 3437 |
+
)
|
| 3438 |
+
|
| 3439 |
+
@app.route('/<env_id>/inventory_action', methods=['POST'])
|
| 3440 |
+
def inventory_action(env_id):
|
| 3441 |
+
data = get_env_data(env_id)
|
| 3442 |
+
settings = data.get('settings', {})
|
| 3443 |
+
if settings.get('env_mode') != '2in1':
|
| 3444 |
+
return jsonify({"error": "Только для режима 2 в 1"}), 403
|
| 3445 |
+
|
| 3446 |
+
req = request.get_json()
|
| 3447 |
+
p_id = req.get('product_id')
|
| 3448 |
+
t_id = req.get('tag_id')
|
| 3449 |
+
action = req.get('action')
|
| 3450 |
+
qty = int(req.get('qty', 0))
|
| 3451 |
+
|
| 3452 |
+
if qty <= 0:
|
| 3453 |
+
return jsonify({"error": "Количество должно быть больше 0"}), 400
|
| 3454 |
+
|
| 3455 |
products = data.get('products',[])
|
| 3456 |
+
product = next((p for p in products if p.get('product_id') == p_id), None)
|
| 3457 |
+
if not product: return jsonify({"error": "Товар не найден"}), 404
|
| 3458 |
+
|
| 3459 |
+
tag = next((t for t in product.get('tags',[]) if t.get('id') == t_id), None)
|
| 3460 |
+
if not tag: return jsonify({"error": "Вариант не найден"}), 404
|
| 3461 |
+
|
| 3462 |
+
if 'stock_batches' not in tag:
|
| 3463 |
+
tag['stock_batches'] =[{"qty": tag.get('stock', 0), "price": tag.get('price', 0), "box_price": tag.get('box_price', 0)}]
|
| 3464 |
+
|
| 3465 |
+
history_entry = {
|
| 3466 |
+
'id': uuid4().hex,
|
| 3467 |
+
'product_id': p_id,
|
| 3468 |
+
'tag_id': t_id,
|
| 3469 |
+
'type': action,
|
| 3470 |
+
'qty': qty,
|
| 3471 |
+
'timestamp': datetime.now(ALMATY_TZ).strftime('%Y-%m-%d %H:%M:%S'),
|
| 3472 |
+
'details': ''
|
| 3473 |
+
}
|
| 3474 |
+
|
| 3475 |
+
if action == 'add':
|
| 3476 |
+
new_price = req.get('new_price')
|
| 3477 |
+
new_box_price = req.get('new_box_price')
|
| 3478 |
+
|
| 3479 |
+
if new_price is not None:
|
| 3480 |
+
new_price = float(new_price)
|
| 3481 |
+
new_box_price = float(new_box_price) if new_box_price else new_price * tag.get('box_qty', 1)
|
| 3482 |
+
tag['stock_batches'].append({'qty': qty, 'price': new_price, 'box_price': new_box_price})
|
| 3483 |
+
history_entry['details'] = f'Оприходование (новая цена: {new_price})'
|
| 3484 |
+
else:
|
| 3485 |
+
if tag['stock_batches']:
|
| 3486 |
+
tag['stock_batches'][-1]['qty'] += qty
|
| 3487 |
+
else:
|
| 3488 |
+
tag['stock_batches'].append({'qty': qty, 'price': tag.get('price', 0), 'box_price': tag.get('box_price', 0)})
|
| 3489 |
+
history_entry['details'] = 'Оприходование (старая цена)'
|
| 3490 |
+
|
| 3491 |
+
tag['stock'] = tag.get('stock', 0) + qty
|
| 3492 |
+
update_tag_price_from_batches(tag)
|
| 3493 |
+
|
| 3494 |
+
elif action == 'write_off':
|
| 3495 |
+
if tag.get('stock', 0) < qty:
|
| 3496 |
+
return jsonify({"error": "Недостаточно остатков для списания"}), 400
|
| 3497 |
+
|
| 3498 |
+
remaining_to_deduct = qty
|
| 3499 |
+
for batch in tag['stock_batches']:
|
| 3500 |
+
if batch['qty'] > 0:
|
| 3501 |
+
if batch['qty'] >= remaining_to_deduct:
|
| 3502 |
+
batch['qty'] -= remaining_to_deduct
|
| 3503 |
+
remaining_to_deduct = 0
|
| 3504 |
+
break
|
| 3505 |
+
else:
|
| 3506 |
+
remaining_to_deduct -= batch['qty']
|
| 3507 |
+
batch['qty'] = 0
|
| 3508 |
+
|
| 3509 |
+
tag['stock'] -= qty
|
| 3510 |
+
history_entry['details'] = 'Ручное списание'
|
| 3511 |
+
update_tag_price_from_batches(tag)
|
| 3512 |
+
|
| 3513 |
+
else:
|
| 3514 |
+
return jsonify({"error": "Неизвестное действие"}), 400
|
| 3515 |
+
|
| 3516 |
+
if 'inventory_history' not in data:
|
| 3517 |
+
data['inventory_history'] = []
|
| 3518 |
+
data['inventory_history'].append(history_entry)
|
| 3519 |
+
|
| 3520 |
+
save_env_data(env_id, data)
|
| 3521 |
+
return jsonify({"success": True})
|
| 3522 |
+
|
| 3523 |
+
@app.route('/<env_id>/inventory_history/<p_id>/<t_id>')
|
| 3524 |
+
def inventory_history(env_id, p_id, t_id):
|
| 3525 |
+
data = get_env_data(env_id)
|
| 3526 |
+
history = data.get('inventory_history',[])
|
| 3527 |
+
item_history =[h for h in history if h.get('product_id') == p_id and h.get('tag_id') == t_id]
|
| 3528 |
+
item_history.sort(key=lambda x: x['timestamp'], reverse=True)
|
| 3529 |
+
return jsonify(item_history)
|
| 3530 |
|
| 3531 |
@app.route('/<env_id>/reports')
|
| 3532 |
def reports_page(env_id):
|
|
|
|
| 3537 |
if settings.get('admin_password_enabled') and not session.get(f'admin_auth_{env_id}'):
|
| 3538 |
return redirect(url_for('admin_login', env_id=env_id))
|
| 3539 |
|
| 3540 |
+
now = datetime.now(ALMATY_TZ)
|
| 3541 |
+
default_start = now.replace(day=1).strftime('%Y-%m-%d')
|
| 3542 |
+
default_end = now.strftime('%Y-%m-%d')
|
| 3543 |
+
|
| 3544 |
+
start_date = request.args.get('start_date', default_start)
|
| 3545 |
+
end_date = request.args.get('end_date', default_end)
|
| 3546 |
+
|
| 3547 |
orders = data.get('orders', {}).values()
|
| 3548 |
+
filtered_orders =[]
|
| 3549 |
|
| 3550 |
+
for o in orders:
|
| 3551 |
+
created_at = o.get('created_at', '')
|
| 3552 |
+
if created_at:
|
| 3553 |
+
date_part = created_at.split(' ')[0]
|
| 3554 |
+
if start_date <= date_part <= end_date:
|
| 3555 |
+
filtered_orders.append(o)
|
| 3556 |
+
|
| 3557 |
+
total_orders = len(filtered_orders)
|
| 3558 |
+
total_revenue = sum(o.get('total_price', 0) for o in filtered_orders)
|
| 3559 |
+
pos_orders = sum(1 for o in filtered_orders if o.get('source') == 'pos')
|
| 3560 |
online_orders = total_orders - pos_orders
|
| 3561 |
|
| 3562 |
emp_stats = {}
|
| 3563 |
product_sales = {}
|
| 3564 |
|
| 3565 |
+
for o in filtered_orders:
|
| 3566 |
emp = o.get('employee_name') or 'Прямой заказ'
|
| 3567 |
if emp not in emp_stats:
|
| 3568 |
emp_stats[emp] = {'count': 0, 'revenue': 0}
|
|
|
|
| 3582 |
return render_template_string(
|
| 3583 |
REPORTS_TEMPLATE, env_id=env_id, settings=settings, currency_code=settings.get('currency_code', 'KGS'),
|
| 3584 |
total_orders=total_orders, total_revenue=total_revenue, pos_orders=pos_orders, online_orders=online_orders,
|
| 3585 |
+
emp_stats=emp_stats, top_products=top_products[:20], start_date=start_date, end_date=end_date
|
| 3586 |
)
|
| 3587 |
|
| 3588 |
@app.route('/<env_id>/track_view/<product_id>', methods=['POST'])
|
|
|
|
| 3600 |
data = get_env_data(env_id)
|
| 3601 |
all_products_raw = data.get('products',[])
|
| 3602 |
settings = data.get('settings', {})
|
| 3603 |
+
env_mode = settings.get('env_mode', 'external')
|
| 3604 |
+
|
| 3605 |
+
products_in_stock =[]
|
| 3606 |
+
for p in all_products_raw:
|
| 3607 |
+
if not p.get('in_stock', True):
|
| 3608 |
+
continue
|
| 3609 |
+
if env_mode == '2in1':
|
| 3610 |
+
valid_tags =[t for t in p.get('tags', []) if t.get('stock', 0) > 0]
|
| 3611 |
+
if not valid_tags and p.get('tags',[]):
|
| 3612 |
+
continue
|
| 3613 |
+
p_copy = p.copy()
|
| 3614 |
+
p_copy['tags'] = valid_tags
|
| 3615 |
+
products_in_stock.append(p_copy)
|
| 3616 |
+
else:
|
| 3617 |
+
products_in_stock.append(p)
|
| 3618 |
+
|
| 3619 |
products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
|
| 3620 |
try:
|
| 3621 |
product = products_sorted[index]
|
|
|
|
| 3654 |
|
| 3655 |
total_price = 0
|
| 3656 |
processed_cart =[]
|
| 3657 |
+
order_timestamp = datetime.now(ALMATY_TZ).strftime('%Y-%m-%d %H:%M:%S')
|
| 3658 |
|
| 3659 |
for item in cart_items:
|
| 3660 |
if not all(k in item for k in ('name', 'quantity')):
|
|
|
|
| 3678 |
if 'TAG_' in c_color:
|
| 3679 |
tag_id = c_color.split('_VAR_')[0].replace('TAG_', '')
|
| 3680 |
tag_ref = next((t for t in product_ref.get('tags',[]) if t.get('id') == tag_id), None)
|
| 3681 |
+
elif item.get('id') and len(item['id'].split('-')) >= 2:
|
| 3682 |
+
tag_id = item['id'].split('-')[1]
|
| 3683 |
+
tag_ref = next((t for t in product_ref.get('tags',[]) if t.get('id') == tag_id), None)
|
| 3684 |
|
| 3685 |
price = float(item.get('price', 0))
|
| 3686 |
discount_applied = False
|
|
|
|
| 3702 |
deduction = quantity
|
| 3703 |
if u_type == 'box':
|
| 3704 |
deduction = quantity * box_qty
|
| 3705 |
+
|
| 3706 |
+
if tag_ref.get('stock', 0) < deduction:
|
| 3707 |
+
return jsonify({"error": f"Недостаточно остатков для товара {item['name']}."}), 400
|
| 3708 |
+
|
| 3709 |
+
if 'stock_batches' not in tag_ref:
|
| 3710 |
+
tag_ref['stock_batches'] =[{"qty": tag_ref.get('stock', 0), "price": tag_ref.get('price', 0), "box_price": tag_ref.get('box_price', 0)}]
|
| 3711 |
+
|
| 3712 |
+
remaining_to_deduct = deduction
|
| 3713 |
+
for batch in tag_ref['stock_batches']:
|
| 3714 |
+
if batch['qty'] > 0:
|
| 3715 |
+
if batch['qty'] >= remaining_to_deduct:
|
| 3716 |
+
batch['qty'] -= remaining_to_deduct
|
| 3717 |
+
remaining_to_deduct = 0
|
| 3718 |
+
break
|
| 3719 |
+
else:
|
| 3720 |
+
remaining_to_deduct -= batch['qty']
|
| 3721 |
+
batch['qty'] = 0
|
| 3722 |
+
|
| 3723 |
+
tag_ref['stock'] -= deduction
|
| 3724 |
+
update_tag_price_from_batches(tag_ref)
|
| 3725 |
+
|
| 3726 |
+
if 'inventory_history' not in data:
|
| 3727 |
+
data['inventory_history'] = []
|
| 3728 |
+
data['inventory_history'].append({
|
| 3729 |
+
'id': uuid4().hex,
|
| 3730 |
+
'product_id': p_id,
|
| 3731 |
+
'tag_id': tag_ref['id'],
|
| 3732 |
+
'type': 'sale',
|
| 3733 |
+
'qty': deduction,
|
| 3734 |
+
'timestamp': order_timestamp,
|
| 3735 |
+
'details': f"Продажа ({source})"
|
| 3736 |
+
})
|
| 3737 |
|
| 3738 |
processed_cart.append({
|
| 3739 |
"product_id": p_id, "name": item['name'], "price": price, "quantity": quantity,
|
|
|
|
| 3746 |
return jsonify({"error": "Неверная цена или количество в товаре."}), 400
|
| 3747 |
|
| 3748 |
order_id = f"{datetime.now(ALMATY_TZ).strftime('%Y%m%d%H%M%S')}-{uuid4().hex[:6]}"
|
|
|
|
| 3749 |
|
| 3750 |
new_order = {
|
| 3751 |
"id": order_id, "created_at": order_timestamp, "cart": processed_cart,
|
|
|
|
| 4081 |
|
| 4082 |
tags_raw = request.form.get('tags_json', '[]')
|
| 4083 |
try:
|
| 4084 |
+
parsed_tags = json.loads(tags_raw)
|
| 4085 |
+
for t in parsed_tags:
|
| 4086 |
+
if 'stock_batches' not in t:
|
| 4087 |
+
t['stock_batches'] =[{"qty": t.get('stock', 0), "price": t.get('price', 0), "box_price": t.get('box_price', 0)}]
|
| 4088 |
+
product_data['tags'] = parsed_tags
|
| 4089 |
except:
|
| 4090 |
+
product_data['tags'] =[]
|
| 4091 |
|
| 4092 |
product_data['in_stock'] = 'in_stock' in request.form
|
| 4093 |
product_data['is_top'] = 'is_top' in request.form
|
|
|
|
| 4110 |
if photo and photo.filename:
|
| 4111 |
try:
|
| 4112 |
ext = os.path.splitext(photo.filename)[1].lower()
|
| 4113 |
+
if ext not in['.jpg', '.jpeg', '.png', '.gif', '.webp']: continue
|
| 4114 |
safe_name = secure_filename(product_data['name'].replace(' ', '_'))[:50]
|
| 4115 |
photo_filename = f"{safe_name}_{uuid4().hex[:8]}{ext}"
|
| 4116 |
temp_path = os.path.join(uploads_dir, photo_filename)
|
|
|
|
| 4190 |
chat_status = { "active": False, "expires_soon": False, "expires_date": "N/A" }
|
| 4191 |
chat_avatar_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/avatars/{display_settings['chat_avatar']}" if display_settings.get('chat_avatar') else "https://huggingface.co/spaces/gippo312/admin/resolve/main/Picsart_25-11-04_12-02-21-390.png"
|
| 4192 |
|
| 4193 |
+
low_stock_count = 0
|
| 4194 |
+
if settings.get('env_mode') == '2in1':
|
| 4195 |
+
for p in products:
|
| 4196 |
+
for t in p.get('tags',[]):
|
| 4197 |
+
if t.get('stock', 0) <= 50:
|
| 4198 |
+
low_stock_count += 1
|
| 4199 |
+
|
| 4200 |
return render_template_string(
|
| 4201 |
ADMIN_TEMPLATE, paginated_products=paginated_products, total_pages=total_pages, page=page, search_q=search_q, categories=display_categories,
|
| 4202 |
organization_info=display_organization_info, chats={}, settings=display_settings, employees=employees,
|
| 4203 |
blocks=blocks, repo_id=REPO_ID, currency_code=display_settings.get('currency_code', 'KGS'), chat_avatar_url=chat_avatar_url,
|
| 4204 |
+
currencies=CURRENCIES, color_schemes=COLOR_SCHEMES, env_id=env_id, chat_status=chat_status, low_stock_count=low_stock_count
|
| 4205 |
)
|
| 4206 |
|
| 4207 |
@app.route('/generate_description_ai', methods=['POST'])
|