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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import logging
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import pytz
|
| 9 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 10 |
+
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
|
| 11 |
+
import uuid
|
| 12 |
+
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
| 13 |
+
import functools
|
| 14 |
+
|
| 15 |
+
app = Flask(__name__)
|
| 16 |
+
app.secret_key = os.urandom(24)
|
| 17 |
+
|
| 18 |
+
DATA_DIR = 'pos_data'
|
| 19 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
INVENTORY_FILE = os.path.join(DATA_DIR, 'inventory.json')
|
| 22 |
+
TRANSACTIONS_FILE = os.path.join(DATA_DIR, 'transactions.json')
|
| 23 |
+
USERS_FILE = os.path.join(DATA_DIR, 'users.json')
|
| 24 |
+
KASSAS_FILE = os.path.join(DATA_DIR, 'kassas.json')
|
| 25 |
+
|
| 26 |
+
DATA_FILES = {
|
| 27 |
+
'inventory': (INVENTORY_FILE, threading.Lock()),
|
| 28 |
+
'transactions': (TRANSACTIONS_FILE, threading.Lock()),
|
| 29 |
+
'users': (USERS_FILE, threading.Lock()),
|
| 30 |
+
'kassas': (KASSAS_FILE, threading.Lock()),
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE")
|
| 34 |
+
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", "YOUR_READ_TOKEN_HERE")
|
| 35 |
+
REPO_ID = "Kgshop/postest"
|
| 36 |
+
|
| 37 |
+
BISHKEK_TZ = pytz.timezone('Asia/Bishkek')
|
| 38 |
+
|
| 39 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 40 |
+
|
| 41 |
+
def get_current_time():
|
| 42 |
+
return datetime.now(BISHKEK_TZ)
|
| 43 |
+
|
| 44 |
+
class DecimalEncoder(json.JSONEncoder):
|
| 45 |
+
def default(self, obj):
|
| 46 |
+
if isinstance(obj, Decimal):
|
| 47 |
+
return str(obj)
|
| 48 |
+
return json.JSONEncoder.default(self, obj)
|
| 49 |
+
|
| 50 |
+
def to_decimal(value_str, default='0.00'):
|
| 51 |
+
if value_str is None or value_str == '':
|
| 52 |
+
return Decimal(default)
|
| 53 |
+
try:
|
| 54 |
+
return Decimal(str(value_str).replace(',', '.'))
|
| 55 |
+
except InvalidOperation:
|
| 56 |
+
logging.warning(f"Could not convert '{value_str}' to Decimal. Returned {default}.")
|
| 57 |
+
return Decimal(default)
|
| 58 |
+
|
| 59 |
+
def load_json_data(file_key):
|
| 60 |
+
filepath, lock = DATA_FILES[file_key]
|
| 61 |
+
filename = os.path.basename(filepath)
|
| 62 |
+
with lock:
|
| 63 |
+
try:
|
| 64 |
+
hf_hub_download(
|
| 65 |
+
repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN_READ,
|
| 66 |
+
local_dir=DATA_DIR, local_dir_use_symlinks=False, force_download=True,
|
| 67 |
+
)
|
| 68 |
+
except HfHubHTTPError as e:
|
| 69 |
+
if e.response.status_code != 404:
|
| 70 |
+
logging.error(f"HTTP error downloading {filename}: {e}")
|
| 71 |
+
except Exception as e:
|
| 72 |
+
logging.error(f"Unknown error downloading {filename}: {e}")
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 76 |
+
return json.load(f)
|
| 77 |
+
except (FileNotFoundError, json.JSONDecodeError):
|
| 78 |
+
return []
|
| 79 |
+
|
| 80 |
+
def save_json_data(file_key, data):
|
| 81 |
+
filepath, lock = DATA_FILES[file_key]
|
| 82 |
+
with lock:
|
| 83 |
+
try:
|
| 84 |
+
temp_file = filepath + ".tmp"
|
| 85 |
+
with open(temp_file, 'w', encoding='utf-8') as f:
|
| 86 |
+
json.dump(data, f, ensure_ascii=False, indent=4, cls=DecimalEncoder)
|
| 87 |
+
os.replace(temp_file, filepath)
|
| 88 |
+
except Exception as e:
|
| 89 |
+
logging.error(f"Critical error saving {filepath}: {e}", exc_info=True)
|
| 90 |
+
|
| 91 |
+
@functools.lru_cache(maxsize=1)
|
| 92 |
+
def get_hf_api():
|
| 93 |
+
if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE":
|
| 94 |
+
return None
|
| 95 |
+
try:
|
| 96 |
+
return HfApi()
|
| 97 |
+
except Exception as e:
|
| 98 |
+
logging.error(f"Error initializing HfApi: {e}")
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
def upload_db_to_hf(file_key):
|
| 102 |
+
api = get_hf_api()
|
| 103 |
+
if not api:
|
| 104 |
+
return
|
| 105 |
+
filepath, _ = DATA_FILES[file_key]
|
| 106 |
+
if not os.path.exists(filepath):
|
| 107 |
+
return
|
| 108 |
+
try:
|
| 109 |
+
filename = os.path.basename(filepath)
|
| 110 |
+
commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z')
|
| 111 |
+
api.upload_file(
|
| 112 |
+
path_or_fileobj=filepath, path_in_repo=filename, repo_id=REPO_ID, repo_type="dataset",
|
| 113 |
+
token=HF_TOKEN_WRITE, commit_message=f"Automated backup {filename} {commit_time}",
|
| 114 |
+
run_as_future=True
|
| 115 |
+
)
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logging.error(f"Error initiating upload of {filepath}: {e}")
|
| 118 |
+
|
| 119 |
+
def periodic_backup():
|
| 120 |
+
while True:
|
| 121 |
+
time.sleep(1800)
|
| 122 |
+
try:
|
| 123 |
+
for key in DATA_FILES.keys():
|
| 124 |
+
upload_db_to_hf(key)
|
| 125 |
+
except Exception as e:
|
| 126 |
+
logging.error(f"Error during scheduled backup: {e}", exc_info=True)
|
| 127 |
+
|
| 128 |
+
def find_item_by_field(file_key, field, value):
|
| 129 |
+
data = load_json_data(file_key)
|
| 130 |
+
for item in data:
|
| 131 |
+
if isinstance(item, dict) and item.get(field) == value:
|
| 132 |
+
return item
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
def format_currency_py(value):
|
| 136 |
+
try:
|
| 137 |
+
number = to_decimal(value)
|
| 138 |
+
return f"{number:,.2f}".replace(",", " ").replace(".", ",")
|
| 139 |
+
except (InvalidOperation, TypeError, ValueError):
|
| 140 |
+
return "0,00"
|
| 141 |
+
|
| 142 |
+
@app.context_processor
|
| 143 |
+
def inject_utils():
|
| 144 |
+
return {'format_currency_py': format_currency_py, 'get_current_time': get_current_time}
|
| 145 |
+
|
| 146 |
+
@app.route('/')
|
| 147 |
+
def sales_screen():
|
| 148 |
+
inventory = load_json_data('inventory')
|
| 149 |
+
users = load_json_data('users')
|
| 150 |
+
kassas = load_json_data('kassas')
|
| 151 |
+
active_inventory = [p for p in inventory if isinstance(p, dict) and p.get('stock', 0) > 0]
|
| 152 |
+
active_inventory.sort(key=lambda x: x.get('name', '').lower())
|
| 153 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALES_SCREEN_CONTENT).replace('__SCRIPTS__', SALES_SCREEN_SCRIPTS)
|
| 154 |
+
return render_template_string(html, inventory=active_inventory, users=users, kassas=kassas)
|
| 155 |
+
|
| 156 |
+
@app.route('/inventory', methods=['GET', 'POST'])
|
| 157 |
+
def inventory_management():
|
| 158 |
+
if request.method == 'POST':
|
| 159 |
+
try:
|
| 160 |
+
name = request.form.get('name', '').strip()
|
| 161 |
+
barcode = request.form.get('barcode', '').strip()
|
| 162 |
+
price = to_decimal(request.form.get('price', '0'))
|
| 163 |
+
cost_price = to_decimal(request.form.get('cost_price', '0'))
|
| 164 |
+
stock = int(to_decimal(request.form.get('stock', '0')))
|
| 165 |
+
|
| 166 |
+
if not name or not barcode or price <= 0:
|
| 167 |
+
flash("Название, штрих-код и цена - обязательные поля.", "danger")
|
| 168 |
+
return redirect(url_for('inventory_management'))
|
| 169 |
+
|
| 170 |
+
inventory = load_json_data('inventory')
|
| 171 |
+
if find_item_by_field('inventory', 'barcode', barcode):
|
| 172 |
+
flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
|
| 173 |
+
return redirect(url_for('inventory_management'))
|
| 174 |
+
|
| 175 |
+
new_product = {
|
| 176 |
+
'id': uuid.uuid4().hex,
|
| 177 |
+
'name': name,
|
| 178 |
+
'barcode': barcode,
|
| 179 |
+
'price': str(price),
|
| 180 |
+
'cost_price': str(cost_price),
|
| 181 |
+
'stock': stock,
|
| 182 |
+
'timestamp_added': get_current_time().isoformat(),
|
| 183 |
+
'timestamp_updated': get_current_time().isoformat()
|
| 184 |
+
}
|
| 185 |
+
inventory.append(new_product)
|
| 186 |
+
save_json_data('inventory', inventory)
|
| 187 |
+
upload_db_to_hf('inventory')
|
| 188 |
+
flash(f"Товар '{name}' успешно добавлен.", "success")
|
| 189 |
+
except Exception as e:
|
| 190 |
+
flash(f"Ошибка при добавлении товара: {e}", "danger")
|
| 191 |
+
return redirect(url_for('inventory_management'))
|
| 192 |
+
|
| 193 |
+
inventory_list = load_json_data('inventory')
|
| 194 |
+
inventory_list.sort(key=lambda x: x.get('name', '').lower())
|
| 195 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
|
| 196 |
+
return render_template_string(html, inventory=inventory_list)
|
| 197 |
+
|
| 198 |
+
@app.route('/inventory/edit/<product_id>', methods=['POST'])
|
| 199 |
+
def edit_product(product_id):
|
| 200 |
+
inventory = load_json_data('inventory')
|
| 201 |
+
product_found = False
|
| 202 |
+
for i, product in enumerate(inventory):
|
| 203 |
+
if isinstance(product, dict) and product.get('id') == product_id:
|
| 204 |
+
try:
|
| 205 |
+
name = request.form.get('name', '').strip()
|
| 206 |
+
barcode = request.form.get('barcode', '').strip()
|
| 207 |
+
price = to_decimal(request.form.get('price'))
|
| 208 |
+
cost_price = to_decimal(request.form.get('cost_price'))
|
| 209 |
+
stock = int(to_decimal(request.form.get('stock')))
|
| 210 |
+
|
| 211 |
+
if not name or not barcode or price <= 0:
|
| 212 |
+
flash("Название, штрих-код и цена обязательны.", "danger")
|
| 213 |
+
return redirect(url_for('inventory_management'))
|
| 214 |
+
|
| 215 |
+
existing_barcode = find_item_by_field('inventory', 'barcode', barcode)
|
| 216 |
+
if existing_barcode and existing_barcode.get('id') != product_id:
|
| 217 |
+
flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning")
|
| 218 |
+
return redirect(url_for('inventory_management'))
|
| 219 |
+
|
| 220 |
+
inventory[i].update({
|
| 221 |
+
'name': name,
|
| 222 |
+
'barcode': barcode,
|
| 223 |
+
'price': str(price),
|
| 224 |
+
'cost_price': str(cost_price),
|
| 225 |
+
'stock': stock,
|
| 226 |
+
'timestamp_updated': get_current_time().isoformat()
|
| 227 |
+
})
|
| 228 |
+
product_found = True
|
| 229 |
+
break
|
| 230 |
+
except Exception as e:
|
| 231 |
+
flash(f"Ошибка при обновлении товара: {e}", "danger")
|
| 232 |
+
return redirect(url_for('inventory_management'))
|
| 233 |
+
|
| 234 |
+
if product_found:
|
| 235 |
+
save_json_data('inventory', inventory)
|
| 236 |
+
upload_db_to_hf('inventory')
|
| 237 |
+
flash("Товар успешно обновлен.", "success")
|
| 238 |
+
else:
|
| 239 |
+
flash("Товар не найден.", "danger")
|
| 240 |
+
return redirect(url_for('inventory_management'))
|
| 241 |
+
|
| 242 |
+
@app.route('/inventory/delete/<product_id>', methods=['POST'])
|
| 243 |
+
def delete_product(product_id):
|
| 244 |
+
inventory = load_json_data('inventory')
|
| 245 |
+
initial_len = len(inventory)
|
| 246 |
+
inventory = [p for p in inventory if not (isinstance(p, dict) and p.get('id') == product_id)]
|
| 247 |
+
if len(inventory) < initial_len:
|
| 248 |
+
save_json_data('inventory', inventory)
|
| 249 |
+
upload_db_to_hf('inventory')
|
| 250 |
+
flash("Товар удален.", "success")
|
| 251 |
+
else:
|
| 252 |
+
flash("Товар не найден.", "warning")
|
| 253 |
+
return redirect(url_for('inventory_management'))
|
| 254 |
+
|
| 255 |
+
@app.route('/api/product_by_barcode/<barcode>')
|
| 256 |
+
def get_product_by_barcode(barcode):
|
| 257 |
+
product = find_item_by_field('inventory', 'barcode', barcode)
|
| 258 |
+
if product:
|
| 259 |
+
if product.get('stock', 0) > 0:
|
| 260 |
+
return jsonify({'success': True, 'product': product})
|
| 261 |
+
else:
|
| 262 |
+
return jsonify({'success': False, 'message': 'Товар закончился на складе'}), 404
|
| 263 |
+
return jsonify({'success': False, 'message': 'Товар не найден'}), 404
|
| 264 |
+
|
| 265 |
+
@app.route('/api/complete_sale', methods=['POST'])
|
| 266 |
+
def complete_sale():
|
| 267 |
+
try:
|
| 268 |
+
data = request.get_json()
|
| 269 |
+
cart = data.get('cart', [])
|
| 270 |
+
user_id = data.get('userId')
|
| 271 |
+
kassa_id = data.get('kassaId')
|
| 272 |
+
payment_method = data.get('paymentMethod', 'cash')
|
| 273 |
+
|
| 274 |
+
if not cart or not user_id or not kassa_id:
|
| 275 |
+
return jsonify({'success': False, 'message': 'Неполные данные для продажи.'}), 400
|
| 276 |
+
|
| 277 |
+
inventory = load_json_data('inventory')
|
| 278 |
+
users = load_json_data('users')
|
| 279 |
+
kassas = load_json_data('kassas')
|
| 280 |
+
|
| 281 |
+
user = find_item_by_field('users', 'id', user_id)
|
| 282 |
+
kassa = find_item_by_field('kassas', 'id', kassa_id)
|
| 283 |
+
|
| 284 |
+
if not user or not kassa:
|
| 285 |
+
return jsonify({'success': False, 'message': 'Кассир или касса не найдены.'}), 404
|
| 286 |
+
|
| 287 |
+
sale_items = []
|
| 288 |
+
total_amount = Decimal('0.00')
|
| 289 |
+
inventory_updates = {}
|
| 290 |
+
|
| 291 |
+
for item_id, cart_item in cart.items():
|
| 292 |
+
product = find_item_by_field('inventory', 'id', item_id)
|
| 293 |
+
if not product:
|
| 294 |
+
return jsonify({'success': False, 'message': f"Товар с ID {item_id} не найден."}), 404
|
| 295 |
+
|
| 296 |
+
quantity_sold = cart_item['quantity']
|
| 297 |
+
current_stock = product.get('stock', 0)
|
| 298 |
+
|
| 299 |
+
if quantity_sold > current_stock:
|
| 300 |
+
return jsonify({'success': False, 'message': f"Недостаточно товара '{product['name']}'. В наличии: {current_stock}"}), 400
|
| 301 |
+
|
| 302 |
+
price_at_sale = to_decimal(product.get('price', '0'))
|
| 303 |
+
item_total = price_at_sale * Decimal(quantity_sold)
|
| 304 |
+
total_amount += item_total
|
| 305 |
+
|
| 306 |
+
sale_items.append({
|
| 307 |
+
'product_id': item_id,
|
| 308 |
+
'name': product['name'],
|
| 309 |
+
'barcode': product.get('barcode'),
|
| 310 |
+
'quantity': quantity_sold,
|
| 311 |
+
'price_at_sale': str(price_at_sale),
|
| 312 |
+
'total': str(item_total)
|
| 313 |
+
})
|
| 314 |
+
inventory_updates[item_id] = current_stock - quantity_sold
|
| 315 |
+
|
| 316 |
+
now_iso = get_current_time().isoformat()
|
| 317 |
+
|
| 318 |
+
new_transaction = {
|
| 319 |
+
'id': uuid.uuid4().hex,
|
| 320 |
+
'timestamp': now_iso,
|
| 321 |
+
'user_id': user_id,
|
| 322 |
+
'user_name': user.get('name', 'N/A'),
|
| 323 |
+
'kassa_id': kassa_id,
|
| 324 |
+
'kassa_name': kassa.get('name', 'N/A'),
|
| 325 |
+
'items': sale_items,
|
| 326 |
+
'total_amount': str(total_amount),
|
| 327 |
+
'payment_method': payment_method
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
transactions = load_json_data('transactions')
|
| 331 |
+
transactions.append(new_transaction)
|
| 332 |
+
|
| 333 |
+
for prod_id, new_stock in inventory_updates.items():
|
| 334 |
+
for i, p in enumerate(inventory):
|
| 335 |
+
if p.get('id') == prod_id:
|
| 336 |
+
inventory[i]['stock'] = new_stock
|
| 337 |
+
inventory[i]['timestamp_updated'] = now_iso
|
| 338 |
+
break
|
| 339 |
+
|
| 340 |
+
if payment_method == 'cash':
|
| 341 |
+
for i, k in enumerate(kassas):
|
| 342 |
+
if k.get('id') == kassa_id:
|
| 343 |
+
current_balance = to_decimal(k.get('balance', '0'))
|
| 344 |
+
kassas[i]['balance'] = str(current_balance + total_amount)
|
| 345 |
+
if 'history' not in kassas[i] or not isinstance(kassas[i]['history'], list):
|
| 346 |
+
kassas[i]['history'] = []
|
| 347 |
+
kassas[i]['history'].append({
|
| 348 |
+
'type': 'sale',
|
| 349 |
+
'amount': str(total_amount),
|
| 350 |
+
'timestamp': now_iso,
|
| 351 |
+
'transaction_id': new_transaction['id']
|
| 352 |
+
})
|
| 353 |
+
break
|
| 354 |
+
|
| 355 |
+
save_json_data('transactions', transactions)
|
| 356 |
+
save_json_data('inventory', inventory)
|
| 357 |
+
save_json_data('kassas', kassas)
|
| 358 |
+
|
| 359 |
+
upload_db_to_hf('transactions')
|
| 360 |
+
upload_db_to_hf('inventory')
|
| 361 |
+
upload_db_to_hf('kassas')
|
| 362 |
+
|
| 363 |
+
return jsonify({'success': True, 'message': 'Продажа успешно зарегистрирована.', 'transactionId': new_transaction['id']})
|
| 364 |
+
|
| 365 |
+
except Exception as e:
|
| 366 |
+
logging.error(f"Error completing sale: {e}", exc_info=True)
|
| 367 |
+
return jsonify({'success': False, 'message': f'Внутренняя ошибка сервера: {e}'}), 500
|
| 368 |
+
|
| 369 |
+
@app.route('/transactions')
|
| 370 |
+
def transaction_history():
|
| 371 |
+
transactions = load_json_data('transactions')
|
| 372 |
+
transactions.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
|
| 373 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "История продаж").replace('__CONTENT__', TRANSACTIONS_CONTENT).replace('__SCRIPTS__', TRANSACTIONS_SCRIPTS)
|
| 374 |
+
return render_template_string(html, transactions=transactions)
|
| 375 |
+
|
| 376 |
+
@app.route('/admin', methods=['GET'])
|
| 377 |
+
def admin_panel():
|
| 378 |
+
users = load_json_data('users')
|
| 379 |
+
kassas = load_json_data('kassas')
|
| 380 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_CONTENT).replace('__SCRIPTS__', ADMIN_SCRIPTS)
|
| 381 |
+
return render_template_string(html, users=users, kassas=kassas)
|
| 382 |
+
|
| 383 |
+
@app.route('/admin/user', methods=['POST'])
|
| 384 |
+
def manage_user():
|
| 385 |
+
action = request.form.get('action')
|
| 386 |
+
users = load_json_data('users')
|
| 387 |
+
|
| 388 |
+
if action == 'add':
|
| 389 |
+
name = request.form.get('name', '').strip()
|
| 390 |
+
pin = request.form.get('pin', '').strip()
|
| 391 |
+
if name and pin and pin.isdigit():
|
| 392 |
+
new_user = {'id': uuid.uuid4().hex, 'name': name, 'pin': pin}
|
| 393 |
+
users.append(new_user)
|
| 394 |
+
flash(f"Кассир '{name}' добавлен.", "success")
|
| 395 |
+
else:
|
| 396 |
+
flash("Имя и цифровой ПИН-код обязательны.", "danger")
|
| 397 |
+
|
| 398 |
+
elif action == 'delete':
|
| 399 |
+
user_id = request.form.get('id')
|
| 400 |
+
initial_len = len(users)
|
| 401 |
+
users = [u for u in users if u.get('id') != user_id]
|
| 402 |
+
if len(users) < initial_len:
|
| 403 |
+
flash("Кассир удален.", "success")
|
| 404 |
+
else:
|
| 405 |
+
flash("Кассир не найден.", "warning")
|
| 406 |
+
|
| 407 |
+
save_json_data('users', users)
|
| 408 |
+
upload_db_to_hf('users')
|
| 409 |
+
return redirect(url_for('admin_panel'))
|
| 410 |
+
|
| 411 |
+
@app.route('/admin/kassa', methods=['POST'])
|
| 412 |
+
def manage_kassa():
|
| 413 |
+
action = request.form.get('action')
|
| 414 |
+
kassas = load_json_data('kassas')
|
| 415 |
+
|
| 416 |
+
if action == 'add':
|
| 417 |
+
name = request.form.get('name', '').strip()
|
| 418 |
+
balance = to_decimal(request.form.get('balance', '0'))
|
| 419 |
+
if name:
|
| 420 |
+
new_kassa = {
|
| 421 |
+
'id': uuid.uuid4().hex,
|
| 422 |
+
'name': name,
|
| 423 |
+
'balance': str(balance),
|
| 424 |
+
'history': []
|
| 425 |
+
}
|
| 426 |
+
if balance > 0:
|
| 427 |
+
new_kassa['history'].append({
|
| 428 |
+
'type': 'deposit',
|
| 429 |
+
'amount': str(balance),
|
| 430 |
+
'timestamp': get_current_time().isoformat(),
|
| 431 |
+
'description': 'Начальный баланс'
|
| 432 |
+
})
|
| 433 |
+
kassas.append(new_kassa)
|
| 434 |
+
flash(f"Касса '{name}' добавлена.", "success")
|
| 435 |
+
else:
|
| 436 |
+
flash("Название кассы обязательно.", "danger")
|
| 437 |
+
|
| 438 |
+
elif action == 'delete':
|
| 439 |
+
kassa_id = request.form.get('id')
|
| 440 |
+
initial_len = len(kassas)
|
| 441 |
+
kassas = [k for k in kassas if k.get('id') != kassa_id]
|
| 442 |
+
if len(kassas) < initial_len:
|
| 443 |
+
flash("Касса удалена.", "success")
|
| 444 |
+
else:
|
| 445 |
+
flash("Касса не найдена.", "warning")
|
| 446 |
+
|
| 447 |
+
save_json_data('kassas', kassas)
|
| 448 |
+
upload_db_to_hf('kassas')
|
| 449 |
+
return redirect(url_for('admin_panel'))
|
| 450 |
+
|
| 451 |
+
@app.route('/admin/kassa_op', methods=['POST'])
|
| 452 |
+
def kassa_operation():
|
| 453 |
+
kassa_id = request.form.get('kassa_id')
|
| 454 |
+
op_type = request.form.get('op_type')
|
| 455 |
+
amount = to_decimal(request.form.get('amount', '0'))
|
| 456 |
+
description = request.form.get('description', '').strip()
|
| 457 |
+
|
| 458 |
+
if not kassa_id or not op_type or amount <= 0:
|
| 459 |
+
flash("Выберите кассу, тип операции и укажите положительную сумму.", "danger")
|
| 460 |
+
return redirect(url_for('admin_panel'))
|
| 461 |
+
|
| 462 |
+
kassas = load_json_data('kassas')
|
| 463 |
+
kassa_found = False
|
| 464 |
+
for i, kassa in enumerate(kassas):
|
| 465 |
+
if kassa.get('id') == kassa_id:
|
| 466 |
+
current_balance = to_decimal(kassa.get('balance', '0'))
|
| 467 |
+
new_balance = current_balance
|
| 468 |
+
|
| 469 |
+
if op_type == 'deposit':
|
| 470 |
+
new_balance += amount
|
| 471 |
+
elif op_type == 'withdrawal':
|
| 472 |
+
if amount > current_balance:
|
| 473 |
+
flash("Сумма изъятия превышает баланс кассы.", "danger")
|
| 474 |
+
return redirect(url_for('admin_panel'))
|
| 475 |
+
new_balance -= amount
|
| 476 |
+
|
| 477 |
+
kassas[i]['balance'] = str(new_balance)
|
| 478 |
+
if 'history' not in kassas[i]: kassas[i]['history'] = []
|
| 479 |
+
kassas[i]['history'].append({
|
| 480 |
+
'type': op_type,
|
| 481 |
+
'amount': str(amount),
|
| 482 |
+
'timestamp': get_current_time().isoformat(),
|
| 483 |
+
'description': description or f"{'Внесение' if op_type == 'deposit' else 'Изъятие'} средств"
|
| 484 |
+
})
|
| 485 |
+
kassa_found = True
|
| 486 |
+
break
|
| 487 |
+
|
| 488 |
+
if kassa_found:
|
| 489 |
+
save_json_data('kassas', kassas)
|
| 490 |
+
upload_db_to_hf('kassas')
|
| 491 |
+
flash("Операция по кассе успешно проведена.", "success")
|
| 492 |
+
else:
|
| 493 |
+
flash("Касса не найдена.", "danger")
|
| 494 |
+
|
| 495 |
+
return redirect(url_for('admin_panel'))
|
| 496 |
+
|
| 497 |
+
@app.route('/backup', methods=['POST'])
|
| 498 |
+
def backup_hf():
|
| 499 |
+
try:
|
| 500 |
+
for key in DATA_FILES.keys():
|
| 501 |
+
upload_db_to_hf(key)
|
| 502 |
+
flash(f"Резервное копирование {len(DATA_FILES)} файлов инициировано.", "success")
|
| 503 |
+
except Exception as e:
|
| 504 |
+
flash(f"Ошибка при резервном копировании: {e}", "danger")
|
| 505 |
+
return redirect(url_for('admin_panel'))
|
| 506 |
+
|
| 507 |
+
@app.route('/download', methods=['GET'])
|
| 508 |
+
def download_hf():
|
| 509 |
+
errors = []
|
| 510 |
+
success_count = 0
|
| 511 |
+
for key in DATA_FILES.keys():
|
| 512 |
+
filepath, _ = DATA_FILES[key]
|
| 513 |
+
filename = os.path.basename(filepath)
|
| 514 |
+
try:
|
| 515 |
+
hf_hub_download(
|
| 516 |
+
repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN_READ,
|
| 517 |
+
local_dir=DATA_DIR, local_dir_use_symlinks=False, force_download=True,
|
| 518 |
+
)
|
| 519 |
+
success_count += 1
|
| 520 |
+
except Exception as e:
|
| 521 |
+
errors.append(f"Ошибка загрузки {filename}: {e}")
|
| 522 |
+
if success_count > 0:
|
| 523 |
+
flash(f"Успешно загружено {success_count} файлов. Данные перезаписаны.", "success")
|
| 524 |
+
if errors:
|
| 525 |
+
flash("Произошли ошибки: " + "; ".join(errors), "danger")
|
| 526 |
+
return redirect(url_for('admin_panel'))
|
| 527 |
+
|
| 528 |
+
BASE_TEMPLATE = """
|
| 529 |
+
<!DOCTYPE html>
|
| 530 |
+
<html lang="ru" data-bs-theme="light">
|
| 531 |
+
<head>
|
| 532 |
+
<meta charset="UTF-8">
|
| 533 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 534 |
+
<title>__TITLE__ - POS</title>
|
| 535 |
+
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
| 536 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
| 537 |
+
<style>
|
| 538 |
+
:root { --sidebar-width: 250px; }
|
| 539 |
+
body { background-color: #f8f9fa; }
|
| 540 |
+
.sidebar { position: fixed; top: 0; left: 0; width: var(--sidebar-width); height: 100vh; background-color: #343a40; padding-top: 1rem; }
|
| 541 |
+
.sidebar .nav-link { color: rgba(255,255,255,.75); }
|
| 542 |
+
.sidebar .nav-link:hover, .sidebar .nav-link.active { color: #fff; }
|
| 543 |
+
.main-content { margin-left: var(--sidebar-width); padding: 1.5rem; }
|
| 544 |
+
@media (max-width: 992px) {
|
| 545 |
+
.sidebar { transform: translateX(calc(-1 * var(--sidebar-width))); transition: transform 0.3s ease-in-out; z-index: 1040; }
|
| 546 |
+
.sidebar.active { transform: translateX(0); }
|
| 547 |
+
.main-content { margin-left: 0; }
|
| 548 |
+
}
|
| 549 |
+
[data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; }
|
| 550 |
+
[data-bs-theme="dark"] .card { background-color: #343a40; }
|
| 551 |
+
</style>
|
| 552 |
+
</head>
|
| 553 |
+
<body>
|
| 554 |
+
<nav class="sidebar">
|
| 555 |
+
<div class="p-3 text-white">
|
| 556 |
+
<a href="/" class="text-white text-decoration-none"><h4 class="fw-bold"><i class="fas fa-cash-register me-2"></i>POS System</h4></a>
|
| 557 |
+
</div>
|
| 558 |
+
<ul class="nav flex-column">
|
| 559 |
+
<li class="nav-item"><a class="nav-link {% if request.endpoint == 'sales_screen' %}active{% endif %}" href="{{ url_for('sales_screen') }}"><i class="fas fa-fw fa-dollar-sign me-2"></i>Касса</a></li>
|
| 560 |
+
<li class="nav-item"><a class="nav-link {% if request.endpoint == 'inventory_management' %}active{% endif %}" href="{{ url_for('inventory_management') }}"><i class="fas fa-fw fa-boxes me-2"></i>Склад</a></li>
|
| 561 |
+
<li class="nav-item"><a class="nav-link {% if request.endpoint == 'transaction_history' %}active{% endif %}" href="{{ url_for('transaction_history') }}"><i class="fas fa-fw fa-history me-2"></i>Продажи</a></li>
|
| 562 |
+
<li class="nav-item"><a class="nav-link {% if request.endpoint == 'admin_panel' %}active{% endif %}" href="{{ url_for('admin_panel') }}"><i class="fas fa-fw fa-cogs me-2"></i>Админка</a></li>
|
| 563 |
+
</ul>
|
| 564 |
+
<div class="mt-auto p-3 text-secondary small">
|
| 565 |
+
© {{ get_current_time().year }}<br>{{ get_current_time().strftime('%Y-%m-%d %H:%M') }}
|
| 566 |
+
</div>
|
| 567 |
+
</nav>
|
| 568 |
+
|
| 569 |
+
<div class="main-content">
|
| 570 |
+
<header class="d-flex justify-content-between align-items-center mb-4">
|
| 571 |
+
<button class="btn btn-dark d-lg-none" id="sidebar-toggle"><i class="fas fa-bars"></i></button>
|
| 572 |
+
<h2 class="h3 mb-0">__TITLE__</h2>
|
| 573 |
+
<div id="theme-toggle" style="cursor: pointer;"><i class="fas fa-sun fa-lg"></i></div>
|
| 574 |
+
</header>
|
| 575 |
+
<main>
|
| 576 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 577 |
+
{% if messages %}
|
| 578 |
+
{% for category, message in messages %}
|
| 579 |
+
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
| 580 |
+
{{ message }}
|
| 581 |
+
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
| 582 |
+
</div>
|
| 583 |
+
{% endfor %}
|
| 584 |
+
{% endif %}
|
| 585 |
+
{% endwith %}
|
| 586 |
+
__CONTENT__
|
| 587 |
+
</main>
|
| 588 |
+
</div>
|
| 589 |
+
|
| 590 |
+
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
| 591 |
+
<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
|
| 592 |
+
<script>
|
| 593 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 594 |
+
document.getElementById('sidebar-toggle')?.addEventListener('click', () => document.querySelector('.sidebar').classList.toggle('active'));
|
| 595 |
+
const themeToggle = document.getElementById('theme-toggle');
|
| 596 |
+
const getStoredTheme = () => localStorage.getItem('theme');
|
| 597 |
+
const setStoredTheme = theme => localStorage.setItem('theme', theme);
|
| 598 |
+
const getPreferredTheme = () => getStoredTheme() || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
| 599 |
+
const setTheme = theme => {
|
| 600 |
+
document.documentElement.setAttribute('data-bs-theme', theme);
|
| 601 |
+
themeToggle.innerHTML = theme === 'dark' ? '<i class="fas fa-moon fa-lg"></i>' : '<i class="fas fa-sun fa-lg"></i>';
|
| 602 |
+
};
|
| 603 |
+
setTheme(getPreferredTheme());
|
| 604 |
+
themeToggle.addEventListener('click', () => {
|
| 605 |
+
const newTheme = getPreferredTheme() === 'light' ? 'dark' : 'light';
|
| 606 |
+
setStoredTheme(newTheme);
|
| 607 |
+
setTheme(newTheme);
|
| 608 |
+
});
|
| 609 |
+
});
|
| 610 |
+
</script>
|
| 611 |
+
__SCRIPTS__
|
| 612 |
+
</body>
|
| 613 |
+
</html>
|
| 614 |
+
"""
|
| 615 |
+
|
| 616 |
+
SALES_SCREEN_CONTENT = """
|
| 617 |
+
<div class="row">
|
| 618 |
+
<div class="col-lg-7 mb-4">
|
| 619 |
+
<div class="card">
|
| 620 |
+
<div class="card-header d-flex justify-content-between align-items-center">
|
| 621 |
+
<h5 class="mb-0">Товары</h5>
|
| 622 |
+
<button id="scan-btn" class="btn btn-primary btn-sm"><i class="fas fa-barcode me-2"></i>Сканировать</button>
|
| 623 |
+
</div>
|
| 624 |
+
<div class="card-body">
|
| 625 |
+
<div id="scanner-container" class="mb-3" style="display: none;">
|
| 626 |
+
<div id="reader" style="width: 100%;"></div>
|
| 627 |
+
<button id="stop-scan-btn" class="btn btn-danger btn-sm mt-2">Остановить</button>
|
| 628 |
+
</div>
|
| 629 |
+
<input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду...">
|
| 630 |
+
<div id="product-grid" class="d-grid gap-2" style="grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));">
|
| 631 |
+
{% for p in inventory %}
|
| 632 |
+
<div class="card text-center product-card" data-id="{{ p.id }}" data-name="{{ p.name|lower }}" data-barcode="{{ p.barcode }}">
|
| 633 |
+
<div class="card-body p-2">
|
| 634 |
+
<h6 class="card-title small mb-1">{{ p.name }}</h6>
|
| 635 |
+
<p class="card-text fw-bold mb-0">{{ format_currency_py(p.price) }} с</p>
|
| 636 |
+
</div>
|
| 637 |
+
</div>
|
| 638 |
+
{% endfor %}
|
| 639 |
+
</div>
|
| 640 |
+
</div>
|
| 641 |
+
</div>
|
| 642 |
+
</div>
|
| 643 |
+
<div class="col-lg-5">
|
| 644 |
+
<div class="card">
|
| 645 |
+
<div class="card-header"><h5 class="mb-0">Чек</h5></div>
|
| 646 |
+
<div class="card-body">
|
| 647 |
+
<div class="row g-2 mb-3">
|
| 648 |
+
<div class="col-6"><select id="user-select" class="form-select"><option value="">-- Кассир --</option>{% for u in users %}<option value="{{ u.id }}">{{ u.name }}</option>{% endfor %}</select></div>
|
| 649 |
+
<div class="col-6"><select id="kassa-select" class="form-select"><option value="">-- Касса --</option>{% for k in kassas %}<option value="{{ k.id }}">{{ k.name }}</option>{% endfor %}</select></div>
|
| 650 |
+
</div>
|
| 651 |
+
<div id="cart-items" class="list-group mb-3"></div>
|
| 652 |
+
<div class="d-flex justify-content-between align-items-center mb-3">
|
| 653 |
+
<h4 class="mb-0">Итого:</h4>
|
| 654 |
+
<h4 class="mb-0" id="cart-total">0,00 с</h4>
|
| 655 |
+
</div>
|
| 656 |
+
<div class="d-grid gap-2">
|
| 657 |
+
<div class="btn-group"><button class="btn btn-success flex-grow-1" id="pay-cash-btn"><i class="fas fa-money-bill-wave me-2"></i>Наличные</button><button class="btn btn-info flex-grow-1" id="pay-card-btn"><i class="far fa-credit-card me-2"></i>Карта</button></div>
|
| 658 |
+
<button class="btn btn-danger" id="clear-cart-btn">Очистить</button>
|
| 659 |
+
</div>
|
| 660 |
+
</div>
|
| 661 |
+
</div>
|
| 662 |
+
</div>
|
| 663 |
+
</div>
|
| 664 |
+
"""
|
| 665 |
+
|
| 666 |
+
SALES_SCREEN_SCRIPTS = """
|
| 667 |
+
<script>
|
| 668 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 669 |
+
const cart = {};
|
| 670 |
+
const productGrid = document.getElementById('product-grid');
|
| 671 |
+
const cartItemsEl = document.getElementById('cart-items');
|
| 672 |
+
const cartTotalEl = document.getElementById('cart-total');
|
| 673 |
+
let audioCtx;
|
| 674 |
+
|
| 675 |
+
function playBeep() {
|
| 676 |
+
if (!audioCtx) {
|
| 677 |
+
try {
|
| 678 |
+
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
| 679 |
+
} catch (e) {
|
| 680 |
+
console.error("Web Audio API is not supported in this browser");
|
| 681 |
+
return;
|
| 682 |
+
}
|
| 683 |
+
}
|
| 684 |
+
const oscillator = audioCtx.createOscillator();
|
| 685 |
+
const gainNode = audioCtx.createGain();
|
| 686 |
+
oscillator.connect(gainNode);
|
| 687 |
+
gainNode.connect(audioCtx.destination);
|
| 688 |
+
oscillator.type = 'sine';
|
| 689 |
+
oscillator.frequency.setValueAtTime(880, audioCtx.currentTime);
|
| 690 |
+
gainNode.gain.setValueAtTime(0.5, audioCtx.currentTime);
|
| 691 |
+
gainNode.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + 0.15);
|
| 692 |
+
oscillator.start(audioCtx.currentTime);
|
| 693 |
+
oscillator.stop(audioCtx.currentTime + 0.15);
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
const updateCartView = () => {
|
| 697 |
+
cartItemsEl.innerHTML = '';
|
| 698 |
+
let total = 0;
|
| 699 |
+
if (Object.keys(cart).length === 0) {
|
| 700 |
+
cartItemsEl.innerHTML = '<p class="text-center text-muted">Корзина пуста</p>';
|
| 701 |
+
}
|
| 702 |
+
for (const id in cart) {
|
| 703 |
+
const item = cart[id];
|
| 704 |
+
total += parseFloat(item.price.replace(',', '.')) * item.quantity;
|
| 705 |
+
cartItemsEl.innerHTML += `
|
| 706 |
+
<div class="list-group-item d-flex justify-content-between align-items-center">
|
| 707 |
+
<div>
|
| 708 |
+
<h6 class="mb-0 small">${item.name}</h6>
|
| 709 |
+
<small>${item.quantity} x ${item.price} с</small>
|
| 710 |
+
</div>
|
| 711 |
+
<div>
|
| 712 |
+
<button class="btn btn-sm btn-outline-secondary cart-qty-btn" data-id="${id}" data-op="-1">-</button>
|
| 713 |
+
<button class="btn btn-sm btn-outline-secondary cart-qty-btn" data-id="${id}" data-op="1">+</button>
|
| 714 |
+
</div>
|
| 715 |
+
</div>`;
|
| 716 |
+
}
|
| 717 |
+
cartTotalEl.textContent = total.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' с';
|
| 718 |
+
};
|
| 719 |
+
|
| 720 |
+
const addToCart = (product) => {
|
| 721 |
+
if (cart[product.id]) {
|
| 722 |
+
cart[product.id].quantity++;
|
| 723 |
+
} else {
|
| 724 |
+
cart[product.id] = {
|
| 725 |
+
name: product.name,
|
| 726 |
+
price: product.price.replace('.',','),
|
| 727 |
+
quantity: 1
|
| 728 |
+
};
|
| 729 |
+
}
|
| 730 |
+
playBeep();
|
| 731 |
+
updateCartView();
|
| 732 |
+
};
|
| 733 |
+
|
| 734 |
+
productGrid.addEventListener('click', e => {
|
| 735 |
+
const card = e.target.closest('.product-card');
|
| 736 |
+
if (card) {
|
| 737 |
+
fetch(`/api/product_by_barcode/${card.dataset.barcode}`)
|
| 738 |
+
.then(res => res.json())
|
| 739 |
+
.then(data => {
|
| 740 |
+
if (data.success) addToCart(data.product);
|
| 741 |
+
else alert(data.message);
|
| 742 |
+
});
|
| 743 |
+
}
|
| 744 |
+
});
|
| 745 |
+
|
| 746 |
+
cartItemsEl.addEventListener('click', e => {
|
| 747 |
+
if (e.target.classList.contains('cart-qty-btn')) {
|
| 748 |
+
const id = e.target.dataset.id;
|
| 749 |
+
const op = parseInt(e.target.dataset.op);
|
| 750 |
+
if (cart[id]) {
|
| 751 |
+
cart[id].quantity += op;
|
| 752 |
+
if (cart[id].quantity <= 0) delete cart[id];
|
| 753 |
+
updateCartView();
|
| 754 |
+
}
|
| 755 |
+
}
|
| 756 |
+
});
|
| 757 |
+
|
| 758 |
+
document.getElementById('clear-cart-btn').addEventListener('click', () => {
|
| 759 |
+
for(const id in cart) delete cart[id];
|
| 760 |
+
updateCartView();
|
| 761 |
+
});
|
| 762 |
+
|
| 763 |
+
document.getElementById('product-search').addEventListener('input', e => {
|
| 764 |
+
const term = e.target.value.toLowerCase();
|
| 765 |
+
document.querySelectorAll('.product-card').forEach(card => {
|
| 766 |
+
const show = card.dataset.name.includes(term) || card.dataset.barcode.includes(term);
|
| 767 |
+
card.style.display = show ? '' : 'none';
|
| 768 |
+
});
|
| 769 |
+
});
|
| 770 |
+
|
| 771 |
+
const completeSale = (paymentMethod) => {
|
| 772 |
+
const userId = document.getElementById('user-select').value;
|
| 773 |
+
const kassaId = document.getElementById('kassa-select').value;
|
| 774 |
+
if (!userId || !kassaId) {
|
| 775 |
+
alert('Выберите кассира и кассу!');
|
| 776 |
+
return;
|
| 777 |
+
}
|
| 778 |
+
if (Object.keys(cart).length === 0) {
|
| 779 |
+
alert('Корзина пуста!');
|
| 780 |
+
return;
|
| 781 |
+
}
|
| 782 |
+
fetch('/api/complete_sale', {
|
| 783 |
+
method: 'POST',
|
| 784 |
+
headers: {'Content-Type': 'application/json'},
|
| 785 |
+
body: JSON.stringify({ cart, userId, kassaId, paymentMethod })
|
| 786 |
+
})
|
| 787 |
+
.then(res => res.json())
|
| 788 |
+
.then(data => {
|
| 789 |
+
if (data.success) {
|
| 790 |
+
alert('Продажа завершена!');
|
| 791 |
+
for(const id in cart) delete cart[id];
|
| 792 |
+
updateCartView();
|
| 793 |
+
} else {
|
| 794 |
+
alert(`Ошибка: ${data.message}`);
|
| 795 |
+
}
|
| 796 |
+
})
|
| 797 |
+
.catch(err => alert(`Сетевая ошибка: ${err}`));
|
| 798 |
+
};
|
| 799 |
+
|
| 800 |
+
document.getElementById('pay-cash-btn').addEventListener('click', () => completeSale('cash'));
|
| 801 |
+
document.getElementById('pay-card-btn').addEventListener('click', () => completeSale('card'));
|
| 802 |
+
|
| 803 |
+
const html5QrCode = new Html5Qrcode("reader");
|
| 804 |
+
const onScanSuccess = (decodedText, decodedResult) => {
|
| 805 |
+
fetch(`/api/product_by_barcode/${decodedText}`)
|
| 806 |
+
.then(res => res.json())
|
| 807 |
+
.then(data => {
|
| 808 |
+
if (data.success) addToCart(data.product);
|
| 809 |
+
else alert(data.message);
|
| 810 |
+
});
|
| 811 |
+
};
|
| 812 |
+
const startScanner = () => {
|
| 813 |
+
document.getElementById('scanner-container').style.display = 'block';
|
| 814 |
+
const config = { fps: 10, qrbox: { width: 250, height: 250 } };
|
| 815 |
+
html5QrCode.start({ facingMode: "environment" }, config, onScanSuccess);
|
| 816 |
+
};
|
| 817 |
+
const stopScanner = () => {
|
| 818 |
+
html5QrCode.stop().then(() => {
|
| 819 |
+
document.getElementById('scanner-container').style.display = 'none';
|
| 820 |
+
}).catch(err => console.error("Failed to stop scanner", err));
|
| 821 |
+
};
|
| 822 |
+
|
| 823 |
+
document.getElementById('scan-btn').addEventListener('click', startScanner);
|
| 824 |
+
document.getElementById('stop-scan-btn').addEventListener('click', stopScanner);
|
| 825 |
+
|
| 826 |
+
updateCartView();
|
| 827 |
+
});
|
| 828 |
+
</script>
|
| 829 |
+
"""
|
| 830 |
+
|
| 831 |
+
INVENTORY_CONTENT = """
|
| 832 |
+
<button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus me-2"></i>Добавить товар</button>
|
| 833 |
+
<div class="card">
|
| 834 |
+
<div class="card-body">
|
| 835 |
+
<div class="table-responsive">
|
| 836 |
+
<table class="table table-hover">
|
| 837 |
+
<thead><tr><th>Название</th><th>Штрих-код</th><th>Цена</th><th>Себест.</th><th>Остаток</th><th>Действия</th></tr></thead>
|
| 838 |
+
<tbody>
|
| 839 |
+
{% for p in inventory %}
|
| 840 |
+
<tr>
|
| 841 |
+
<td>{{ p.name }}</td><td>{{ p.barcode }}</td><td>{{ format_currency_py(p.price) }} с</td><td>{{ format_currency_py(p.cost_price) }} с</td><td>{{ p.stock }}</td>
|
| 842 |
+
<td>
|
| 843 |
+
<button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editProductModal-{{ p.id }}"><i class="fas fa-edit"></i></button>
|
| 844 |
+
<form action="{{ url_for('delete_product', product_id=p.id) }}" method="POST" class="d-inline" onsubmit="return confirm('Удалить товар?');">
|
| 845 |
+
<button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
|
| 846 |
+
</form>
|
| 847 |
+
</td>
|
| 848 |
+
</tr>
|
| 849 |
+
{% endfor %}
|
| 850 |
+
</tbody>
|
| 851 |
+
</table>
|
| 852 |
+
</div>
|
| 853 |
+
</div>
|
| 854 |
+
</div>
|
| 855 |
+
|
| 856 |
+
<div class="modal fade" id="addProductModal" tabindex="-1">
|
| 857 |
+
<div class="modal-dialog">
|
| 858 |
+
<div class="modal-content">
|
| 859 |
+
<div class="modal-header"><h5 class="modal-title">Новый товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
|
| 860 |
+
<form action="{{ url_for('inventory_management') }}" method="POST">
|
| 861 |
+
<div class="modal-body">
|
| 862 |
+
<div class="mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" required></div>
|
| 863 |
+
<div class="mb-3"><label class="form-label">Штрих-код</label>
|
| 864 |
+
<div class="input-group"><input type="text" name="barcode" class="form-control barcode-input" required><button type="button" class="btn btn-outline-secondary scan-modal-btn"><i class="fas fa-barcode"></i></button></div>
|
| 865 |
+
</div>
|
| 866 |
+
<div id="modal-scanner-add" class="mb-2" style="display:none;"></div>
|
| 867 |
+
<div class="row">
|
| 868 |
+
<div class="col-6 mb-3"><label class="form-label">Цена</label><input type="text" name="price" class="form-control" inputmode="decimal" required></div>
|
| 869 |
+
<div class="col-6 mb-3"><label class="form-label">Себестоимость</label><input type="text" name="cost_price" class="form-control" inputmode="decimal"></div>
|
| 870 |
+
</div>
|
| 871 |
+
<div class="mb-3"><label class="form-label">Начальный остаток</label><input type="number" name="stock" class="form-control" value="0" step="1"></div>
|
| 872 |
+
</div>
|
| 873 |
+
<div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
|
| 874 |
+
</form>
|
| 875 |
+
</div>
|
| 876 |
+
</div>
|
| 877 |
+
</div>
|
| 878 |
+
|
| 879 |
+
{% for p in inventory %}
|
| 880 |
+
<div class="modal fade" id="editProductModal-{{ p.id }}" tabindex="-1">
|
| 881 |
+
<div class="modal-dialog">
|
| 882 |
+
<div class="modal-content">
|
| 883 |
+
<div class="modal-header"><h5 class="modal-title">Редактировать товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
|
| 884 |
+
<form action="{{ url_for('edit_product', product_id=p.id) }}" method="POST">
|
| 885 |
+
<div class="modal-body">
|
| 886 |
+
<div class="mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" value="{{ p.name }}" required></div>
|
| 887 |
+
<div class="mb-3"><label class="form-label">Штрих-код</label><input type="text" name="barcode" class="form-control" value="{{ p.barcode }}" required></div>
|
| 888 |
+
<div class="row">
|
| 889 |
+
<div class="col-6 mb-3"><label class="form-label">Цена</label><input type="text" name="price" class="form-control" value="{{ p.price|string|replace('.', ',') }}" inputmode="decimal" required></div>
|
| 890 |
+
<div class="col-6 mb-3"><label class="form-label">Себестоимость</label><input type="text" name="cost_price" value="{{ p.cost_price|string|replace('.', ',') }}" class="form-control" inputmode="decimal"></div>
|
| 891 |
+
</div>
|
| 892 |
+
<div class="mb-3"><label class="form-label">Остаток</label><input type="number" name="stock" class="form-control" value="{{ p.stock }}" step="1"></div>
|
| 893 |
+
</div>
|
| 894 |
+
<div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
|
| 895 |
+
</form>
|
| 896 |
+
</div>
|
| 897 |
+
</div>
|
| 898 |
+
</div>
|
| 899 |
+
{% endfor %}
|
| 900 |
+
"""
|
| 901 |
+
|
| 902 |
+
INVENTORY_SCRIPTS = """
|
| 903 |
+
<script>
|
| 904 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 905 |
+
let currentScanner = null;
|
| 906 |
+
document.querySelectorAll('.scan-modal-btn').forEach(btn => {
|
| 907 |
+
btn.addEventListener('click', e => {
|
| 908 |
+
const form = e.target.closest('form');
|
| 909 |
+
const scannerContainer = form.querySelector('[id^="modal-scanner-"]');
|
| 910 |
+
const barcodeInput = form.querySelector('.barcode-input');
|
| 911 |
+
if (currentScanner) {
|
| 912 |
+
currentScanner.stop();
|
| 913 |
+
currentScanner = null;
|
| 914 |
+
scannerContainer.style.display = 'none';
|
| 915 |
+
return;
|
| 916 |
+
}
|
| 917 |
+
scannerContainer.style.display = 'block';
|
| 918 |
+
const scannerId = scannerContainer.id + '-reader';
|
| 919 |
+
if(!document.getElementById(scannerId)) scannerContainer.innerHTML = `<div id="${scannerId}"></div>`;
|
| 920 |
+
|
| 921 |
+
const html5QrCode = new Html5Qrcode(scannerId);
|
| 922 |
+
currentScanner = html5QrCode;
|
| 923 |
+
const onScanSuccess = (decodedText, decodedResult) => {
|
| 924 |
+
barcodeInput.value = decodedText;
|
| 925 |
+
html5QrCode.stop();
|
| 926 |
+
currentScanner = null;
|
| 927 |
+
scannerContainer.style.display = 'none';
|
| 928 |
+
};
|
| 929 |
+
html5QrCode.start({ facingMode: "environment" }, { fps: 10, qrbox: 250 }, onScanSuccess);
|
| 930 |
+
});
|
| 931 |
+
});
|
| 932 |
+
|
| 933 |
+
document.querySelectorAll('.modal').forEach(modal => {
|
| 934 |
+
modal.addEventListener('hidden.bs.modal', () => {
|
| 935 |
+
if (currentScanner) {
|
| 936 |
+
currentScanner.stop();
|
| 937 |
+
currentScanner = null;
|
| 938 |
+
}
|
| 939 |
+
modal.querySelectorAll('[id^="modal-scanner-"]').forEach(c => c.style.display = 'none');
|
| 940 |
+
});
|
| 941 |
+
});
|
| 942 |
+
});
|
| 943 |
+
</script>
|
| 944 |
+
"""
|
| 945 |
+
|
| 946 |
+
TRANSACTIONS_CONTENT = """
|
| 947 |
+
<div class="card">
|
| 948 |
+
<div class="card-body">
|
| 949 |
+
<div class="table-responsive">
|
| 950 |
+
<table class="table table-sm table-hover">
|
| 951 |
+
<thead><tr><th>ID</th><th>Дата</th><th>Кассир</th><th>Касса</th><th>Сумма</th><th>Тип опл.</th><th>Позиции</th></tr></thead>
|
| 952 |
+
<tbody>
|
| 953 |
+
{% for t in transactions %}
|
| 954 |
+
<tr>
|
| 955 |
+
<td><small class="text-muted">{{ t.id[:8] }}</small></td>
|
| 956 |
+
<td>{{ t.timestamp[:16]|replace('T', ' ') }}</td>
|
| 957 |
+
<td>{{ t.user_name }}</td><td>{{ t.kassa_name }}</td>
|
| 958 |
+
<td class="fw-bold">{{ format_currency_py(t.total_amount) }} с</td>
|
| 959 |
+
<td><span class="badge bg-{{'success' if t.payment_method == 'cash' else 'info'}}">{{'Нал.' if t.payment_method == 'cash' else 'Карта'}}</span></td>
|
| 960 |
+
<td>
|
| 961 |
+
<ul class="list-unstyled mb-0 small">
|
| 962 |
+
{% for item in t['items'] %}<li>{{ item.name }} ({{ item.quantity }}x{{ format_currency_py(item.price_at_sale) }})</li>{% endfor %}
|
| 963 |
+
</ul>
|
| 964 |
+
</td>
|
| 965 |
+
</tr>
|
| 966 |
+
{% endfor %}
|
| 967 |
+
</tbody>
|
| 968 |
+
</table>
|
| 969 |
+
</div>
|
| 970 |
+
</div>
|
| 971 |
+
</div>
|
| 972 |
+
"""
|
| 973 |
+
|
| 974 |
+
TRANSACTIONS_SCRIPTS = ""
|
| 975 |
+
|
| 976 |
+
ADMIN_CONTENT = """
|
| 977 |
+
<div class="row">
|
| 978 |
+
<div class="col-md-6 mb-4">
|
| 979 |
+
<div class="card h-100">
|
| 980 |
+
<div class="card-header"><h5 class="mb-0">Кассиры</h5></div>
|
| 981 |
+
<div class="card-body">
|
| 982 |
+
<form action="{{ url_for('manage_user') }}" method="POST" class="mb-3">
|
| 983 |
+
<input type="hidden" name="action" value="add">
|
| 984 |
+
<div class="input-group">
|
| 985 |
+
<input type="text" name="name" class="form-control" placeholder="Имя кассира" required>
|
| 986 |
+
<input type="password" name="pin" class="form-control" placeholder="ПИН-код" required>
|
| 987 |
+
<button type="submit" class="btn btn-primary">Добавить</button>
|
| 988 |
+
</div>
|
| 989 |
+
</form>
|
| 990 |
+
<ul class="list-group">
|
| 991 |
+
{% for u in users %}
|
| 992 |
+
<li class="list-group-item d-flex justify-content-between align-items-center">
|
| 993 |
+
{{ u.name }}
|
| 994 |
+
<form action="{{ url_for('manage_user') }}" method="POST" onsubmit="return confirm('Удалить кассира?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="{{ u.id }}"><button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button></form>
|
| 995 |
+
</li>
|
| 996 |
+
{% endfor %}
|
| 997 |
+
</ul>
|
| 998 |
+
</div>
|
| 999 |
+
</div>
|
| 1000 |
+
</div>
|
| 1001 |
+
<div class="col-md-6 mb-4">
|
| 1002 |
+
<div class="card h-100">
|
| 1003 |
+
<div class="card-header"><h5 class="mb-0">Кассы</h5></div>
|
| 1004 |
+
<div class="card-body">
|
| 1005 |
+
<form action="{{ url_for('manage_kassa') }}" method="POST" class="mb-3">
|
| 1006 |
+
<input type="hidden" name="action" value="add">
|
| 1007 |
+
<div class="input-group">
|
| 1008 |
+
<input type="text" name="name" class="form-control" placeholder="Название кассы" required>
|
| 1009 |
+
<input type="text" name="balance" class="form-control" placeholder="Начальный баланс" value="0" inputmode="decimal">
|
| 1010 |
+
<button type="submit" class="btn btn-primary">Добавить</button>
|
| 1011 |
+
</div>
|
| 1012 |
+
</form>
|
| 1013 |
+
<ul class="list-group">
|
| 1014 |
+
{% for k in kassas %}
|
| 1015 |
+
<li class="list-group-item d-flex justify-content-between align-items-center">
|
| 1016 |
+
<div>{{ k.name }} <br><small class="fw-bold">{{ format_currency_py(k.balance) }} с</small></div>
|
| 1017 |
+
<form action="{{ url_for('manage_kassa') }}" method="POST" onsubmit="return confirm('Удалить кассу?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="{{ k.id }}"><button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button></form>
|
| 1018 |
+
</li>
|
| 1019 |
+
{% endfor %}
|
| 1020 |
+
</ul>
|
| 1021 |
+
</div>
|
| 1022 |
+
</div>
|
| 1023 |
+
</div>
|
| 1024 |
+
<div class="col-12 mb-4">
|
| 1025 |
+
<div class="card">
|
| 1026 |
+
<div class="card-header"><h5 class="mb-0">Операции по кассе (Внесение/Изъятие)</h5></div>
|
| 1027 |
+
<div class="card-body">
|
| 1028 |
+
<form action="{{ url_for('kassa_operation') }}" method="POST">
|
| 1029 |
+
<div class="row g-2 align-items-end">
|
| 1030 |
+
<div class="col-md-3"><label class="form-label">Касса</label><select name="kassa_id" class="form-select" required><option value="">-- Выберите --</option>{% for k in kassas %}<option value="{{k.id}}">{{k.name}}</option>{% endfor %}</select></div>
|
| 1031 |
+
<div class="col-md-2"><label class="form-label">Операция</label><select name="op_type" class="form-select" required><option value="deposit">Внесение</option><option value="withdrawal">Изъятие</option></select></div>
|
| 1032 |
+
<div class="col-md-2"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal"></div>
|
| 1033 |
+
<div class="col-md-3"><label class="form-label">Описание</label><input type="text" name="description" class="form-control"></div>
|
| 1034 |
+
<div class="col-md-2"><button type="submit" class="btn btn-success w-100">Выполнить</button></div>
|
| 1035 |
+
</div>
|
| 1036 |
+
</form>
|
| 1037 |
+
</div>
|
| 1038 |
+
</div>
|
| 1039 |
+
</div>
|
| 1040 |
+
<div class="col-12">
|
| 1041 |
+
<div class="card">
|
| 1042 |
+
<div class="card-header"><h5 class="mb-0">Резервное копирование</h5></div>
|
| 1043 |
+
<div class="card-body">
|
| 1044 |
+
<p>Данные периодически сохраняются в облако. Можно сделать это вручную.</p>
|
| 1045 |
+
<form method="POST" action="{{ url_for('backup_hf') }}" class="d-inline-block me-2">
|
| 1046 |
+
<button type="submit" class="btn btn-outline-primary"><i class="fas fa-cloud-upload-alt me-2"></i>Сохранить в облако</button>
|
| 1047 |
+
</form>
|
| 1048 |
+
<form method="GET" action="{{ url_for('download_hf') }}" class="d-inline-block" onsubmit="return confirm('ВНИМАНИЕ! Это действие заменит все локальные данные данными из облака. Продолжить?');">
|
| 1049 |
+
<button type="submit" class="btn btn-outline-danger"><i class="fas fa-cloud-download-alt me-2"></i>Загрузить из облака</button>
|
| 1050 |
+
</form>
|
| 1051 |
+
</div>
|
| 1052 |
+
</div>
|
| 1053 |
+
</div>
|
| 1054 |
+
</div>
|
| 1055 |
+
"""
|
| 1056 |
+
|
| 1057 |
+
ADMIN_SCRIPTS = ""
|
| 1058 |
+
|
| 1059 |
+
if __name__ == '__main__':
|
| 1060 |
+
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 1061 |
+
backup_thread.start()
|
| 1062 |
+
for key in DATA_FILES.keys():
|
| 1063 |
+
load_json_data(key)
|
| 1064 |
+
app.run(debug=False, host='0.0.0.0', port=7860, use_reloader=False)
|