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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, send_from_directory
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import logging
|
| 7 |
+
import threading
|
| 8 |
+
import time
|
| 9 |
+
from datetime import datetime, timedelta, date
|
| 10 |
+
import pytz
|
| 11 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 12 |
+
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
|
| 13 |
+
from werkzeug.utils import secure_filename
|
| 14 |
+
import uuid
|
| 15 |
+
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
| 16 |
+
import functools
|
| 17 |
+
|
| 18 |
+
app = Flask(__name__)
|
| 19 |
+
app.secret_key = os.urandom(24)
|
| 20 |
+
DATA_FILE = 'pos_data.json'
|
| 21 |
+
UPLOAD_FOLDER = 'uploads'
|
| 22 |
+
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 23 |
+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
| 24 |
+
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
|
| 25 |
+
|
| 26 |
+
HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE")
|
| 27 |
+
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", "YOUR_READ_TOKEN_HERE")
|
| 28 |
+
REPO_ID = "Kgshop/postest"
|
| 29 |
+
|
| 30 |
+
BISHKEK_TZ = pytz.timezone('Asia/Bishkek')
|
| 31 |
+
|
| 32 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 33 |
+
|
| 34 |
+
data_lock = threading.Lock()
|
| 35 |
+
|
| 36 |
+
def get_current_time():
|
| 37 |
+
return datetime.now(BISHKEK_TZ)
|
| 38 |
+
|
| 39 |
+
def initialize_data_structure():
|
| 40 |
+
return {
|
| 41 |
+
'products': [],
|
| 42 |
+
'sales': [],
|
| 43 |
+
'cash_registers': [],
|
| 44 |
+
'cash_operations': [],
|
| 45 |
+
'config': {}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
class DecimalEncoder(json.JSONEncoder):
|
| 49 |
+
def default(self, obj):
|
| 50 |
+
if isinstance(obj, Decimal): return str(obj)
|
| 51 |
+
return json.JSONEncoder.default(self, obj)
|
| 52 |
+
|
| 53 |
+
def load_data():
|
| 54 |
+
with data_lock:
|
| 55 |
+
try:
|
| 56 |
+
logging.info(f"Attempting download of {DATA_FILE} from {REPO_ID}...")
|
| 57 |
+
hf_hub_download(
|
| 58 |
+
repo_id=REPO_ID, filename=DATA_FILE, repo_type="dataset", token=HF_TOKEN_READ,
|
| 59 |
+
local_dir=".", local_dir_use_symlinks=False, force_download=True,
|
| 60 |
+
)
|
| 61 |
+
logging.info(f"{DATA_FILE} downloaded successfully from Hugging Face.")
|
| 62 |
+
except RepositoryNotFoundError:
|
| 63 |
+
logging.warning(f"Repository {REPO_ID} not found. Checking local {DATA_FILE}.")
|
| 64 |
+
except HfHubHTTPError as e:
|
| 65 |
+
if e.response.status_code == 404:
|
| 66 |
+
logging.warning(f"File {DATA_FILE} not found in repository {REPO_ID}. Checking local file.")
|
| 67 |
+
else:
|
| 68 |
+
logging.error(f"HTTP error downloading {DATA_FILE} from Hugging Face: {e}")
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logging.error(f"Unknown error downloading {DATA_FILE} from Hugging Face: {e}")
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 74 |
+
data = json.load(file)
|
| 75 |
+
logging.info("Main data loaded successfully from local JSON.")
|
| 76 |
+
default_data = initialize_data_structure()
|
| 77 |
+
changed = False
|
| 78 |
+
for key, default_value in default_data.items():
|
| 79 |
+
if key not in data:
|
| 80 |
+
logging.warning(f"Key '{key}' missing in {DATA_FILE}. Initializing with default.")
|
| 81 |
+
data[key] = default_value
|
| 82 |
+
changed = True
|
| 83 |
+
if changed:
|
| 84 |
+
save_data(data)
|
| 85 |
+
return data
|
| 86 |
+
except FileNotFoundError:
|
| 87 |
+
logging.warning(f"Local file {DATA_FILE} not found. Initializing empty structure.")
|
| 88 |
+
new_data = initialize_data_structure()
|
| 89 |
+
save_data(new_data)
|
| 90 |
+
return new_data
|
| 91 |
+
except json.JSONDecodeError:
|
| 92 |
+
logging.error(f"JSON decode error in {DATA_FILE}. Initializing empty structure.")
|
| 93 |
+
bad_file_path = f"{DATA_FILE}.{get_current_time().strftime('%Y%m%d%H%M%S')}.bad"
|
| 94 |
+
try: os.rename(DATA_FILE, bad_file_path)
|
| 95 |
+
except Exception as backup_err: logging.error(f"Failed to backup corrupted file: {backup_err}")
|
| 96 |
+
new_data = initialize_data_structure()
|
| 97 |
+
save_data(new_data)
|
| 98 |
+
return new_data
|
| 99 |
+
except Exception as e:
|
| 100 |
+
logging.error(f"Unknown error loading local main data: {e}", exc_info=True)
|
| 101 |
+
return initialize_data_structure()
|
| 102 |
+
|
| 103 |
+
def save_data(data):
|
| 104 |
+
try:
|
| 105 |
+
temp_file = DATA_FILE + ".tmp"
|
| 106 |
+
with open(temp_file, 'w', encoding='utf-8') as file:
|
| 107 |
+
json.dump(data, file, ensure_ascii=False, indent=4, cls=DecimalEncoder)
|
| 108 |
+
os.replace(temp_file, DATA_FILE)
|
| 109 |
+
logging.info(f"Main data successfully saved to local file {DATA_FILE}.")
|
| 110 |
+
except Exception as e:
|
| 111 |
+
logging.error(f"Critical error saving main data: {e}", exc_info=True)
|
| 112 |
+
if os.path.exists(temp_file):
|
| 113 |
+
try: os.remove(temp_file)
|
| 114 |
+
except OSError as rm_err: logging.error(f"Failed to remove temporary file {temp_file}: {rm_err}")
|
| 115 |
+
|
| 116 |
+
@functools.lru_cache(maxsize=1)
|
| 117 |
+
def get_hf_api():
|
| 118 |
+
if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE":
|
| 119 |
+
logging.warning("HF_TOKEN_WRITE not set. Uploads to Hugging Face will be disabled.")
|
| 120 |
+
return None
|
| 121 |
+
try: return HfApi()
|
| 122 |
+
except Exception as e: logging.error(f"Error initializing HfApi: {e}"); return None
|
| 123 |
+
|
| 124 |
+
def upload_db_to_hf(filepath=DATA_FILE):
|
| 125 |
+
api = get_hf_api()
|
| 126 |
+
if not api: logging.warning(f"HfApi not initialized. Upload of {filepath} to Hugging Face skipped."); return
|
| 127 |
+
if not os.path.exists(filepath): logging.warning(f"Local file {filepath} not found. Upload to Hugging Face skipped."); return
|
| 128 |
+
try:
|
| 129 |
+
filename = os.path.basename(filepath)
|
| 130 |
+
commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z')
|
| 131 |
+
logging.info(f"Starting upload of {filename} to Hugging Face...")
|
| 132 |
+
api.upload_file(
|
| 133 |
+
path_or_fileobj=filepath, path_in_repo=filename, repo_id=REPO_ID, repo_type="dataset",
|
| 134 |
+
token=HF_TOKEN_WRITE, commit_message=f"Automated backup {filename} {commit_time}",
|
| 135 |
+
run_as_future=True
|
| 136 |
+
)
|
| 137 |
+
logging.info(f"Upload of {filename} to Hugging Face initiated.")
|
| 138 |
+
except RepositoryNotFoundError: logging.error(f"Upload error: Repository {REPO_ID} not found on Hugging Face.")
|
| 139 |
+
except Exception as e: logging.error(f"Error initiating upload of {filepath} to Hugging Face: {e}")
|
| 140 |
+
|
| 141 |
+
def periodic_backup():
|
| 142 |
+
logging.info("Starting periodic backup thread.")
|
| 143 |
+
while True:
|
| 144 |
+
time.sleep(1800)
|
| 145 |
+
logging.info("Starting scheduled backup...")
|
| 146 |
+
try:
|
| 147 |
+
if os.path.exists(DATA_FILE):
|
| 148 |
+
upload_db_to_hf(DATA_FILE)
|
| 149 |
+
else:
|
| 150 |
+
logging.warning(f"File {DATA_FILE} not found for scheduled backup.")
|
| 151 |
+
logging.info("Scheduled backup completed.")
|
| 152 |
+
except Exception as e:
|
| 153 |
+
logging.error(f"Error during scheduled backup: {e}", exc_info=True)
|
| 154 |
+
|
| 155 |
+
def to_decimal(value_str, default='0.00'):
|
| 156 |
+
if value_str is None: return Decimal(default)
|
| 157 |
+
try: return Decimal(str(value_str).replace(',', '.').strip())
|
| 158 |
+
except InvalidOperation: logging.warning(f"Could not convert '{value_str}' to Decimal. Returned {default}."); return Decimal(default)
|
| 159 |
+
|
| 160 |
+
def to_int(value_str, default=0):
|
| 161 |
+
if value_str is None: return default
|
| 162 |
+
try: return int(to_decimal(value_str).to_integral_value())
|
| 163 |
+
except (InvalidOperation, ValueError): return default
|
| 164 |
+
|
| 165 |
+
def parse_iso_datetime(timestamp_str):
|
| 166 |
+
if not timestamp_str: return None
|
| 167 |
+
try:
|
| 168 |
+
dt = datetime.fromisoformat(timestamp_str.replace('Z', '+00:00'))
|
| 169 |
+
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
|
| 170 |
+
return pytz.utc.localize(dt).astimezone(BISHKEK_TZ)
|
| 171 |
+
else:
|
| 172 |
+
return dt.astimezone(BISHKEK_TZ)
|
| 173 |
+
except (ValueError, TypeError) as e:
|
| 174 |
+
logging.warning(f"Failed to parse date: '{timestamp_str}'. Error: {e}")
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
def find_item_by_id(item_id, item_list):
|
| 178 |
+
return next((item for item in item_list if item.get('id') == item_id), None)
|
| 179 |
+
|
| 180 |
+
def find_product_by_sku(sku, products_list):
|
| 181 |
+
return next((p for p in products_list if p.get('sku') == sku), None)
|
| 182 |
+
|
| 183 |
+
def format_currency_py(value):
|
| 184 |
+
try:
|
| 185 |
+
number = to_decimal(value)
|
| 186 |
+
return f"{number:,.2f}".replace(",", "TEMP_SPACE").replace(".", ",").replace("TEMP_SPACE", " ")
|
| 187 |
+
except (InvalidOperation, TypeError, ValueError): return "0,00"
|
| 188 |
+
|
| 189 |
+
def format_integer_py(value):
|
| 190 |
+
try:
|
| 191 |
+
number = to_decimal(value).to_integral_value(rounding=ROUND_HALF_UP)
|
| 192 |
+
return f"{number:,}".replace(",", " ")
|
| 193 |
+
except (InvalidOperation, TypeError, ValueError): return "0"
|
| 194 |
+
|
| 195 |
+
@app.route('/')
|
| 196 |
+
def index():
|
| 197 |
+
return redirect(url_for('dashboard'))
|
| 198 |
+
|
| 199 |
+
@app.route('/dashboard')
|
| 200 |
+
def dashboard():
|
| 201 |
+
data = load_data()
|
| 202 |
+
now = get_current_time()
|
| 203 |
+
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
| 204 |
+
|
| 205 |
+
sales_today = [s for s in data.get('sales', []) if parse_iso_datetime(s.get('timestamp')) >= today_start]
|
| 206 |
+
|
| 207 |
+
total_revenue_today = sum(to_decimal(s.get('total_amount', '0')) for s in sales_today)
|
| 208 |
+
transactions_today = len(sales_today)
|
| 209 |
+
|
| 210 |
+
total_profit_today = Decimal('0')
|
| 211 |
+
for sale in sales_today:
|
| 212 |
+
for item in sale.get('items', []):
|
| 213 |
+
profit_per_item = to_decimal(item.get('selling_price', '0')) - to_decimal(item.get('purchase_price', '0'))
|
| 214 |
+
total_profit_today += profit_per_item * to_int(item.get('quantity', 0))
|
| 215 |
+
|
| 216 |
+
cash_registers = data.get('cash_registers', [])
|
| 217 |
+
total_cash_balance = sum(to_decimal(cr.get('balance', '0')) for cr in cash_registers)
|
| 218 |
+
|
| 219 |
+
products_low_stock = [p for p in data.get('products', []) if to_int(p.get('quantity', 0)) <= to_int(p.get('low_stock_threshold', 5))]
|
| 220 |
+
|
| 221 |
+
stats = {
|
| 222 |
+
'revenue_today': total_revenue_today,
|
| 223 |
+
'profit_today': total_profit_today,
|
| 224 |
+
'transactions_today': transactions_today,
|
| 225 |
+
'total_cash_balance': total_cash_balance,
|
| 226 |
+
'products_low_stock': len(products_low_stock),
|
| 227 |
+
'low_stock_items': products_low_stock
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "Панель управления").replace('__CONTENT__', DASHBOARD_CONTENT)
|
| 231 |
+
return render_template_string(html, stats=stats, cash_registers=cash_registers)
|
| 232 |
+
|
| 233 |
+
@app.route('/inventory', methods=['GET', 'POST'])
|
| 234 |
+
def inventory():
|
| 235 |
+
data = load_data()
|
| 236 |
+
if request.method == 'POST':
|
| 237 |
+
action = request.form.get('action', 'add')
|
| 238 |
+
products = data.get('products', [])
|
| 239 |
+
|
| 240 |
+
try:
|
| 241 |
+
if action == 'add':
|
| 242 |
+
name = request.form.get('name', '').strip()
|
| 243 |
+
sku = request.form.get('sku', '').strip() or uuid.uuid4().hex[:12].upper()
|
| 244 |
+
quantity = to_int(request.form.get('quantity', '0'))
|
| 245 |
+
purchase_price = to_decimal(request.form.get('purchase_price', '0'))
|
| 246 |
+
selling_price = to_decimal(request.form.get('selling_price', '0'))
|
| 247 |
+
low_stock_threshold = to_int(request.form.get('low_stock_threshold', '5'))
|
| 248 |
+
|
| 249 |
+
if not name or selling_price <= 0:
|
| 250 |
+
flash("Название и цена продажи - обязательные поля.", "danger")
|
| 251 |
+
return redirect(url_for('inventory'))
|
| 252 |
+
|
| 253 |
+
if find_product_by_sku(sku, products):
|
| 254 |
+
flash(f"Товар с артикулом/штрихкодом '{sku}' уже существует.", "warning")
|
| 255 |
+
return redirect(url_for('inventory'))
|
| 256 |
+
|
| 257 |
+
new_product = {
|
| 258 |
+
'id': uuid.uuid4().hex,
|
| 259 |
+
'name': name,
|
| 260 |
+
'sku': sku,
|
| 261 |
+
'quantity': quantity,
|
| 262 |
+
'purchase_price': str(purchase_price),
|
| 263 |
+
'selling_price': str(selling_price),
|
| 264 |
+
'low_stock_threshold': low_stock_threshold,
|
| 265 |
+
'timestamp_added': get_current_time().isoformat()
|
| 266 |
+
}
|
| 267 |
+
products.append(new_product)
|
| 268 |
+
flash(f"Товар '{name}' успешно добавлен.", "success")
|
| 269 |
+
|
| 270 |
+
elif action == 'edit':
|
| 271 |
+
product_id = request.form.get('id')
|
| 272 |
+
product = find_item_by_id(product_id, products)
|
| 273 |
+
if not product:
|
| 274 |
+
flash("Товар не найден.", "danger")
|
| 275 |
+
return redirect(url_for('inventory'))
|
| 276 |
+
|
| 277 |
+
new_sku = request.form.get('sku', '').strip()
|
| 278 |
+
if product.get('sku') != new_sku and find_product_by_sku(new_sku, products):
|
| 279 |
+
flash(f"Товар с артикулом/штрихкодом '{new_sku}' уже существует.", "warning")
|
| 280 |
+
return redirect(url_for('inventory'))
|
| 281 |
+
|
| 282 |
+
product.update({
|
| 283 |
+
'name': request.form.get('name', '').strip(),
|
| 284 |
+
'sku': new_sku,
|
| 285 |
+
'quantity': to_int(request.form.get('quantity', '0')),
|
| 286 |
+
'purchase_price': str(to_decimal(request.form.get('purchase_price', '0'))),
|
| 287 |
+
'selling_price': str(to_decimal(request.form.get('selling_price', '0'))),
|
| 288 |
+
'low_stock_threshold': to_int(request.form.get('low_stock_threshold', '5'))
|
| 289 |
+
})
|
| 290 |
+
flash(f"Товар '{product['name']}' обновлен.", "success")
|
| 291 |
+
|
| 292 |
+
save_data(data)
|
| 293 |
+
upload_db_to_hf()
|
| 294 |
+
except Exception as e:
|
| 295 |
+
logging.error(f"Error processing inventory form: {e}", exc_info=True)
|
| 296 |
+
flash(f"Произошла ошибка: {e}", "danger")
|
| 297 |
+
return redirect(url_for('inventory'))
|
| 298 |
+
|
| 299 |
+
products_list = data.get('products', [])
|
| 300 |
+
products_list.sort(key=lambda p: p.get('name', '').lower())
|
| 301 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
|
| 302 |
+
return render_template_string(html, products=products_list)
|
| 303 |
+
|
| 304 |
+
@app.route('/inventory/delete/<product_id>', methods=['POST'])
|
| 305 |
+
def delete_product(product_id):
|
| 306 |
+
data = load_data()
|
| 307 |
+
products = data.get('products', [])
|
| 308 |
+
initial_length = len(products)
|
| 309 |
+
data['products'] = [p for p in products if p.get('id') != product_id]
|
| 310 |
+
if len(data['products']) < initial_length:
|
| 311 |
+
save_data(data)
|
| 312 |
+
upload_db_to_hf()
|
| 313 |
+
flash("Товар успешно удален.", "success")
|
| 314 |
+
else:
|
| 315 |
+
flash("Товар для удаления не найден.", "warning")
|
| 316 |
+
return redirect(url_for('inventory'))
|
| 317 |
+
|
| 318 |
+
@app.route('/pos', methods=['GET'])
|
| 319 |
+
def pos():
|
| 320 |
+
data = load_data()
|
| 321 |
+
cash_registers = data.get('cash_registers', [])
|
| 322 |
+
if not cash_registers:
|
| 323 |
+
flash("Сначала создайте кассу в разделе 'Управление кассами'.", "warning")
|
| 324 |
+
return redirect(url_for('cash_management'))
|
| 325 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "Касса (POS)").replace('__CONTENT__', POS_CONTENT).replace('__SCRIPTS__', POS_SCRIPTS)
|
| 326 |
+
return render_template_string(html, cash_registers=cash_registers)
|
| 327 |
+
|
| 328 |
+
@app.route('/api/product/<sku>', methods=['GET'])
|
| 329 |
+
def get_product_by_sku(sku):
|
| 330 |
+
data = load_data()
|
| 331 |
+
product = find_product_by_sku(sku, data.get('products', []))
|
| 332 |
+
if product:
|
| 333 |
+
if to_int(product.get('quantity', 0)) > 0:
|
| 334 |
+
return jsonify(product)
|
| 335 |
+
else:
|
| 336 |
+
return jsonify({'error': 'Товар закончился'}), 404
|
| 337 |
+
return jsonify({'error': 'Товар не найден'}), 404
|
| 338 |
+
|
| 339 |
+
@app.route('/pos/checkout', methods=['POST'])
|
| 340 |
+
def checkout():
|
| 341 |
+
data = load_data()
|
| 342 |
+
products = data.get('products', [])
|
| 343 |
+
sales = data.get('sales', [])
|
| 344 |
+
cash_registers = data.get('cash_registers', [])
|
| 345 |
+
|
| 346 |
+
try:
|
| 347 |
+
cart_data = request.get_json()
|
| 348 |
+
cart = cart_data.get('cart', [])
|
| 349 |
+
cash_register_id = cart_data.get('cash_register_id')
|
| 350 |
+
|
| 351 |
+
if not cart or not cash_register_id:
|
| 352 |
+
return jsonify({'error': 'Корзина пуста или касса не выбрана'}), 400
|
| 353 |
+
|
| 354 |
+
cash_register = find_item_by_id(cash_register_id, cash_registers)
|
| 355 |
+
if not cash_register:
|
| 356 |
+
return jsonify({'error': 'Касса не найдена'}), 404
|
| 357 |
+
|
| 358 |
+
sale_items = []
|
| 359 |
+
total_amount = Decimal('0')
|
| 360 |
+
|
| 361 |
+
for item in cart:
|
| 362 |
+
product_id = item.get('id')
|
| 363 |
+
quantity_sold = to_int(item.get('quantity', 0))
|
| 364 |
+
|
| 365 |
+
product_in_db = find_item_by_id(product_id, products)
|
| 366 |
+
if not product_in_db:
|
| 367 |
+
return jsonify({'error': f"Товар '{item.get('name')}' не найден в базе."}), 404
|
| 368 |
+
|
| 369 |
+
if to_int(product_in_db.get('quantity', 0)) < quantity_sold:
|
| 370 |
+
return jsonify({'error': f"Недостаточно товара '{product_in_db.get('name')}'. В наличии: {product_in_db.get('quantity')}"}), 400
|
| 371 |
+
|
| 372 |
+
for item in cart:
|
| 373 |
+
product_id = item.get('id')
|
| 374 |
+
quantity_sold = to_int(item.get('quantity', 0))
|
| 375 |
+
product_in_db = find_item_by_id(product_id, products)
|
| 376 |
+
|
| 377 |
+
product_in_db['quantity'] = to_int(product_in_db.get('quantity', 0)) - quantity_sold
|
| 378 |
+
|
| 379 |
+
selling_price = to_decimal(product_in_db.get('selling_price', '0'))
|
| 380 |
+
purchase_price = to_decimal(product_in_db.get('purchase_price', '0'))
|
| 381 |
+
|
| 382 |
+
item_total = selling_price * Decimal(quantity_sold)
|
| 383 |
+
total_amount += item_total
|
| 384 |
+
|
| 385 |
+
sale_items.append({
|
| 386 |
+
'product_id': product_id,
|
| 387 |
+
'name': product_in_db.get('name'),
|
| 388 |
+
'sku': product_in_db.get('sku'),
|
| 389 |
+
'quantity': quantity_sold,
|
| 390 |
+
'selling_price': str(selling_price),
|
| 391 |
+
'purchase_price': str(purchase_price)
|
| 392 |
+
})
|
| 393 |
+
|
| 394 |
+
new_sale = {
|
| 395 |
+
'id': uuid.uuid4().hex,
|
| 396 |
+
'timestamp': get_current_time().isoformat(),
|
| 397 |
+
'items': sale_items,
|
| 398 |
+
'total_amount': str(total_amount),
|
| 399 |
+
'cash_register_id': cash_register_id,
|
| 400 |
+
'cash_register_name': cash_register.get('name')
|
| 401 |
+
}
|
| 402 |
+
sales.append(new_sale)
|
| 403 |
+
|
| 404 |
+
current_balance = to_decimal(cash_register.get('balance', '0'))
|
| 405 |
+
cash_register['balance'] = str(current_balance + total_amount)
|
| 406 |
+
|
| 407 |
+
save_data(data)
|
| 408 |
+
upload_db_to_hf()
|
| 409 |
+
|
| 410 |
+
return jsonify({'success': True, 'sale_id': new_sale['id']})
|
| 411 |
+
except Exception as e:
|
| 412 |
+
logging.error(f"Checkout error: {e}", exc_info=True)
|
| 413 |
+
return jsonify({'error': f"Внутренняя ошибка сервера: {e}"}), 500
|
| 414 |
+
|
| 415 |
+
@app.route('/cash', methods=['GET', 'POST'])
|
| 416 |
+
def cash_management():
|
| 417 |
+
data = load_data()
|
| 418 |
+
if request.method == 'POST':
|
| 419 |
+
action = request.form.get('action')
|
| 420 |
+
try:
|
| 421 |
+
if action == 'add_register':
|
| 422 |
+
name = request.form.get('name', '').strip()
|
| 423 |
+
initial_balance = to_decimal(request.form.get('initial_balance', '0'))
|
| 424 |
+
if not name:
|
| 425 |
+
flash("Название кассы обязательно.", "danger")
|
| 426 |
+
else:
|
| 427 |
+
new_register = {
|
| 428 |
+
'id': uuid.uuid4().hex,
|
| 429 |
+
'name': name,
|
| 430 |
+
'balance': str(initial_balance)
|
| 431 |
+
}
|
| 432 |
+
data['cash_registers'].append(new_register)
|
| 433 |
+
save_data(data)
|
| 434 |
+
upload_db_to_hf()
|
| 435 |
+
flash(f"Касса '{name}' успешно создана.", "success")
|
| 436 |
+
|
| 437 |
+
elif action == 'add_operation':
|
| 438 |
+
register_id = request.form.get('cash_register_id')
|
| 439 |
+
op_type = request.form.get('type')
|
| 440 |
+
amount = to_decimal(request.form.get('amount', '0'))
|
| 441 |
+
description = request.form.get('description', '').strip()
|
| 442 |
+
|
| 443 |
+
if not register_id or not op_type or amount <= 0:
|
| 444 |
+
flash("Заполните все поля операции: касса, тип, сумма (>0).", "danger")
|
| 445 |
+
else:
|
| 446 |
+
register = find_item_by_id(register_id, data.get('cash_registers', []))
|
| 447 |
+
if not register:
|
| 448 |
+
flash("Касса не ��айдена.", "danger")
|
| 449 |
+
else:
|
| 450 |
+
new_operation = {
|
| 451 |
+
'id': uuid.uuid4().hex,
|
| 452 |
+
'cash_register_id': register_id,
|
| 453 |
+
'cash_register_name': register.get('name'),
|
| 454 |
+
'type': op_type,
|
| 455 |
+
'amount': str(amount),
|
| 456 |
+
'description': description,
|
| 457 |
+
'timestamp': get_current_time().isoformat()
|
| 458 |
+
}
|
| 459 |
+
data['cash_operations'].append(new_operation)
|
| 460 |
+
|
| 461 |
+
current_balance = to_decimal(register.get('balance', '0'))
|
| 462 |
+
if op_type == 'deposit':
|
| 463 |
+
register['balance'] = str(current_balance + amount)
|
| 464 |
+
flash(f"Внесение {format_currency_py(amount)} сом в кассу '{register.get('name')}' зарегистрировано.", "success")
|
| 465 |
+
elif op_type == 'withdrawal':
|
| 466 |
+
register['balance'] = str(current_balance - amount)
|
| 467 |
+
flash(f"Изъятие {format_currency_py(amount)} сом из кассы '{register.get('name')}' зарегистрировано.", "success")
|
| 468 |
+
|
| 469 |
+
save_data(data)
|
| 470 |
+
upload_db_to_hf()
|
| 471 |
+
except Exception as e:
|
| 472 |
+
logging.error(f"Error in cash management: {e}", exc_info=True)
|
| 473 |
+
flash(f"Произошла ошибка: {e}", "danger")
|
| 474 |
+
|
| 475 |
+
return redirect(url_for('cash_management'))
|
| 476 |
+
|
| 477 |
+
cash_registers = data.get('cash_registers', [])
|
| 478 |
+
cash_operations = data.get('cash_operations', [])
|
| 479 |
+
cash_operations.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
|
| 480 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "Управление кассами").replace('__CONTENT__', CASH_MANAGEMENT_CONTENT)
|
| 481 |
+
return render_template_string(html, cash_registers=cash_registers, cash_operations=cash_operations)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
@app.route('/reports')
|
| 485 |
+
def reports():
|
| 486 |
+
data = load_data()
|
| 487 |
+
now = get_current_time()
|
| 488 |
+
|
| 489 |
+
filter_type = request.args.get('filter', 'month')
|
| 490 |
+
start_date_str = request.args.get('start_date')
|
| 491 |
+
end_date_str = request.args.get('end_date')
|
| 492 |
+
|
| 493 |
+
try:
|
| 494 |
+
if filter_type == 'custom' and start_date_str and end_date_str:
|
| 495 |
+
sd = datetime.strptime(start_date_str, '%Y-%m-%d')
|
| 496 |
+
ed = datetime.strptime(end_date_str, '%Y-%m-%d')
|
| 497 |
+
start_date_dt = BISHKEK_TZ.localize(sd.replace(hour=0, minute=0, second=0, microsecond=0))
|
| 498 |
+
end_date_dt = BISHKEK_TZ.localize(ed.replace(hour=23, minute=59, second=59, microsecond=999999))
|
| 499 |
+
elif filter_type == 'today':
|
| 500 |
+
start_date_dt = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
| 501 |
+
end_date_dt = now.replace(hour=23, minute=59, second=59, microsecond=999999)
|
| 502 |
+
elif filter_type == 'week':
|
| 503 |
+
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
| 504 |
+
start_date_dt = today_start - timedelta(days=today_start.weekday())
|
| 505 |
+
end_date_dt = start_date_dt + timedelta(days=6, hours=23, minutes=59, seconds=59, microseconds=999999)
|
| 506 |
+
else: # month
|
| 507 |
+
start_date_dt = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
| 508 |
+
next_month_start = (start_date_dt.replace(day=28) + timedelta(days=4)).replace(day=1)
|
| 509 |
+
end_date_dt = next_month_start - timedelta(microseconds=1)
|
| 510 |
+
except (ValueError, TypeError):
|
| 511 |
+
flash("Неверный формат даты. Показывается отчет за текущий месяц.", "warning")
|
| 512 |
+
start_date_dt = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
| 513 |
+
next_month_start = (start_date_dt.replace(day=28) + timedelta(days=4)).replace(day=1)
|
| 514 |
+
end_date_dt = next_month_start - timedelta(microseconds=1)
|
| 515 |
+
|
| 516 |
+
filtered_sales = [s for s in data.get('sales', []) if start_date_dt <= parse_iso_datetime(s.get('timestamp')) <= end_date_dt]
|
| 517 |
+
filtered_ops = [op for op in data.get('cash_operations', []) if start_date_dt <= parse_iso_datetime(op.get('timestamp')) <= end_date_dt]
|
| 518 |
+
|
| 519 |
+
total_revenue = sum(to_decimal(s.get('total_amount', '0')) for s in filtered_sales)
|
| 520 |
+
|
| 521 |
+
total_cost_of_goods = Decimal('0')
|
| 522 |
+
product_summary = {}
|
| 523 |
+
|
| 524 |
+
for sale in filtered_sales:
|
| 525 |
+
for item in sale.get('items', []):
|
| 526 |
+
purchase_price = to_decimal(item.get('purchase_price', '0'))
|
| 527 |
+
selling_price = to_decimal(item.get('selling_price', '0'))
|
| 528 |
+
quantity = to_int(item.get('quantity', 0))
|
| 529 |
+
cost_for_item = purchase_price * quantity
|
| 530 |
+
revenue_for_item = selling_price * quantity
|
| 531 |
+
total_cost_of_goods += cost_for_item
|
| 532 |
+
|
| 533 |
+
p_id = item.get('product_id')
|
| 534 |
+
if p_id not in product_summary:
|
| 535 |
+
product_summary[p_id] = {'name': item.get('name'), 'sku': item.get('sku'), 'quantity': 0, 'revenue': Decimal('0'), 'cogs': Decimal('0')}
|
| 536 |
+
|
| 537 |
+
product_summary[p_id]['quantity'] += quantity
|
| 538 |
+
product_summary[p_id]['revenue'] += revenue_for_item
|
| 539 |
+
product_summary[p_id]['cogs'] += cost_for_item
|
| 540 |
+
|
| 541 |
+
gross_profit = total_revenue - total_cost_of_goods
|
| 542 |
+
|
| 543 |
+
total_expenses = sum(to_decimal(op.get('amount', '0')) for op in filtered_ops if op.get('type') == 'withdrawal')
|
| 544 |
+
net_profit = gross_profit - total_expenses
|
| 545 |
+
|
| 546 |
+
report_data = {
|
| 547 |
+
'start_date': start_date_dt.strftime('%Y-%m-%d'),
|
| 548 |
+
'end_date': end_date_dt.strftime('%Y-%m-%d'),
|
| 549 |
+
'filter_type': filter_type,
|
| 550 |
+
'total_revenue': total_revenue,
|
| 551 |
+
'total_cost_of_goods': total_cost_of_goods,
|
| 552 |
+
'gross_profit': gross_profit,
|
| 553 |
+
'total_expenses': total_expenses,
|
| 554 |
+
'net_profit': net_profit,
|
| 555 |
+
'filtered_sales': sorted(filtered_sales, key=lambda s: s.get('timestamp', ''), reverse=True),
|
| 556 |
+
'product_summary': sorted(product_summary.values(), key=lambda p: p['quantity'], reverse=True)
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
|
| 560 |
+
return render_template_string(html, report=report_data)
|
| 561 |
+
|
| 562 |
+
@app.route('/backup', methods=['POST'])
|
| 563 |
+
def backup_hf():
|
| 564 |
+
try:
|
| 565 |
+
logging.info("Manual backup to Hugging Face initiated...")
|
| 566 |
+
if os.path.exists(DATA_FILE):
|
| 567 |
+
upload_db_to_hf(DATA_FILE)
|
| 568 |
+
flash(f"Backup of {DATA_FILE} to Hugging Face initiated.", "success")
|
| 569 |
+
else:
|
| 570 |
+
flash(f"Local file '{DATA_FILE}' not found for backup.", "warning")
|
| 571 |
+
except Exception as e:
|
| 572 |
+
logging.error(f"Error during manual backup: {e}", exc_info=True)
|
| 573 |
+
flash(f"An error occurred during backup: {e}", "danger")
|
| 574 |
+
return redirect(url_for('dashboard'))
|
| 575 |
+
|
| 576 |
+
@app.route('/download', methods=['GET'])
|
| 577 |
+
def download_hf():
|
| 578 |
+
downloaded = False
|
| 579 |
+
error_msg = None
|
| 580 |
+
logging.info("Starting data download from Hugging Face...")
|
| 581 |
+
try:
|
| 582 |
+
hf_hub_download(repo_id=REPO_ID, filename=DATA_FILE, repo_type="dataset", token=HF_TOKEN_READ, local_dir=".", local_dir_use_symlinks=False, force_download=True)
|
| 583 |
+
downloaded = True
|
| 584 |
+
except Exception as e:
|
| 585 |
+
logging.error(f"Error downloading from HF: {e}", exc_info=True)
|
| 586 |
+
error_msg = str(e)
|
| 587 |
+
|
| 588 |
+
if downloaded:
|
| 589 |
+
flash(f"File {DATA_FILE} downloaded successfully. Reloading data.", "success")
|
| 590 |
+
try:
|
| 591 |
+
load_data()
|
| 592 |
+
except Exception as e:
|
| 593 |
+
flash(f"Error reloading data after download: {e}", "warning")
|
| 594 |
+
else:
|
| 595 |
+
flash(f"Error during download: {error_msg}", "danger")
|
| 596 |
+
|
| 597 |
+
return redirect(url_for('dashboard'))
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
BASE_TEMPLATE = """
|
| 601 |
+
<!DOCTYPE html>
|
| 602 |
+
<html lang="ru" data-bs-theme="light">
|
| 603 |
+
<head>
|
| 604 |
+
<meta charset="UTF-8">
|
| 605 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 606 |
+
<title>__TITLE__ - POS</title>
|
| 607 |
+
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
| 608 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
| 609 |
+
<style>
|
| 610 |
+
:root { --sidebar-width: 250px; --topbar-height: 60px; }
|
| 611 |
+
body { background-color: #f8f9fa; }
|
| 612 |
+
.sidebar { position: fixed; top: 0; left: 0; width: var(--sidebar-width); height: 100vh; background-color: #212529; color: white; padding-top: 1rem; }
|
| 613 |
+
.sidebar-brand { font-size: 1.5rem; font-weight: 700; color: white; text-decoration: none; }
|
| 614 |
+
.sidebar .nav-link { color: rgba(255,255,255,.75); }
|
| 615 |
+
.sidebar .nav-link:hover { color: white; }
|
| 616 |
+
.sidebar .nav-link.active { color: white; font-weight: bold; }
|
| 617 |
+
.main-content { margin-left: var(--sidebar-width); padding-top: calc(var(--topbar-height) + 1rem); }
|
| 618 |
+
.topbar { position: fixed; top: 0; right: 0; left: var(--sidebar-width); height: var(--topbar-height); background: #fff; border-bottom: 1px solid #dee2e6; z-index: 1020; }
|
| 619 |
+
@media (max-width: 992px) {
|
| 620 |
+
.sidebar { transform: translateX(calc(-1 * var(--sidebar-width))); transition: transform 0.3s ease; }
|
| 621 |
+
.sidebar.active { transform: translateX(0); }
|
| 622 |
+
.main-content, .topbar { margin-left: 0; left: 0; }
|
| 623 |
+
}
|
| 624 |
+
[data-bs-theme="dark"] body { background-color: #212529; color: #fff; }
|
| 625 |
+
[data-bs-theme="dark"] .card, [data-bs-theme="dark"] .modal-content, [data-bs-theme="dark"] .topbar { background-color: #343a40; border-color: #495057; }
|
| 626 |
+
[data-bs-theme="dark"] .table { --bs-table-color: #fff; --bs-table-bg: #343a40; --bs-table-border-color: #495057; --bs-table-striped-bg: #3e444a; --bs-table-hover-bg: #454b51; }
|
| 627 |
+
[data-bs-theme="dark"] .form-control, [data-bs-theme="dark"] .form-select { background-color: #495057; border-color: #6c757d; color: #fff; }
|
| 628 |
+
</style>
|
| 629 |
+
</head>
|
| 630 |
+
<body>
|
| 631 |
+
<div class="sidebar p-3">
|
| 632 |
+
<a href="{{ url_for('dashboard') }}" class="sidebar-brand d-flex align-items-center mb-3">
|
| 633 |
+
<i class="fas fa-cash-register me-2"></i> POS
|
| 634 |
+
</a>
|
| 635 |
+
<nav class="nav flex-column nav-pills">
|
| 636 |
+
<a class="nav-link {% if request.endpoint == 'dashboard' %}active{% endif %}" href="{{ url_for('dashboard') }}"><i class="fas fa-fw fa-tachometer-alt me-2"></i>Панель</a>
|
| 637 |
+
<a class="nav-link {% if request.endpoint == 'pos' %}active{% endif %}" href="{{ url_for('pos') }}"><i class="fas fa-fw fa-shopping-cart me-2"></i>Касса (POS)</a>
|
| 638 |
+
<a class="nav-link {% if request.endpoint == 'inventory' %}active{% endif %}" href="{{ url_for('inventory') }}"><i class="fas fa-fw fa-boxes me-2"></i>Склад</a>
|
| 639 |
+
<a class="nav-link {% if request.endpoint == 'cash_management' %}active{% endif %}" href="{{ url_for('cash_management') }}"><i class="fas fa-fw fa-wallet me-2"></i>Кассы</a>
|
| 640 |
+
<a class="nav-link {% if request.endpoint == 'reports' %}active{% endif %}" href="{{ url_for('reports') }}"><i class="fas fa-fw fa-chart-line me-2"></i>Отчеты</a>
|
| 641 |
+
</nav>
|
| 642 |
+
<div class="mt-auto">
|
| 643 |
+
<small class="text-muted">{{ get_current_time().strftime('%Y-%m-%d %H:%M') }}</small>
|
| 644 |
+
</div>
|
| 645 |
+
</div>
|
| 646 |
+
<div class="main-content p-4">
|
| 647 |
+
<header class="topbar d-flex justify-content-between align-items-center px-4">
|
| 648 |
+
<button class="btn btn-outline-secondary d-lg-none" id="sidebar-toggle"><i class="fas fa-bars"></i></button>
|
| 649 |
+
<h4 class="h5 mb-0 d-none d-lg-block">__TITLE__</h4>
|
| 650 |
+
<div class="d-flex align-items-center">
|
| 651 |
+
<form method="POST" action="{{ url_for('backup_hf') }}" class="me-2 mb-0">
|
| 652 |
+
<button type="submit" class="btn btn-sm btn-outline-secondary" title="Backup to Hugging Face"><i class="fas fa-cloud-upload-alt me-1"></i> Backup</button>
|
| 653 |
+
</form>
|
| 654 |
+
<form method="GET" action="{{ url_for('download_hf') }}" onsubmit="return confirm('Перезапишет локальные данные. Уверены?');" class="mb-0 me-3">
|
| 655 |
+
<button type="submit" class="btn btn-sm btn-outline-secondary" title="Download DB from Hugging Face"><i class="fas fa-cloud-download-alt me-1"></i> Download</button>
|
| 656 |
+
</form>
|
| 657 |
+
<button class="btn btn-sm btn-outline-secondary" id="theme-toggle"><i class="fas fa-sun"></i></button>
|
| 658 |
+
</div>
|
| 659 |
+
</header>
|
| 660 |
+
<main>
|
| 661 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 662 |
+
{% if messages %}
|
| 663 |
+
{% for category, message in messages %}
|
| 664 |
+
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
| 665 |
+
{{ message }}
|
| 666 |
+
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
| 667 |
+
</div>
|
| 668 |
+
{% endfor %}
|
| 669 |
+
{% endif %}
|
| 670 |
+
{% endwith %}
|
| 671 |
+
__CONTENT__
|
| 672 |
+
</main>
|
| 673 |
+
</div>
|
| 674 |
+
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
| 675 |
+
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
|
| 676 |
+
<script>
|
| 677 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 678 |
+
const sidebarToggle = document.getElementById('sidebar-toggle');
|
| 679 |
+
const sidebar = document.querySelector('.sidebar');
|
| 680 |
+
if (sidebarToggle && sidebar) {
|
| 681 |
+
sidebarToggle.addEventListener('click', () => sidebar.classList.toggle('active'));
|
| 682 |
+
}
|
| 683 |
+
const themeToggle = document.getElementById('theme-toggle');
|
| 684 |
+
const getStoredTheme = () => localStorage.getItem('theme');
|
| 685 |
+
const setStoredTheme = theme => localStorage.setItem('theme', theme);
|
| 686 |
+
const getPreferredTheme = () => getStoredTheme() || 'light';
|
| 687 |
+
const setTheme = theme => {
|
| 688 |
+
document.documentElement.setAttribute('data-bs-theme', theme);
|
| 689 |
+
themeToggle.querySelector('i').className = theme === 'dark' ? 'fas fa-moon' : 'fas fa-sun';
|
| 690 |
+
};
|
| 691 |
+
setTheme(getPreferredTheme());
|
| 692 |
+
themeToggle.addEventListener('click', () => {
|
| 693 |
+
const newTheme = getPreferredTheme() === 'light' ? 'dark' : 'light';
|
| 694 |
+
setStoredTheme(newTheme);
|
| 695 |
+
setTheme(newTheme);
|
| 696 |
+
});
|
| 697 |
+
});
|
| 698 |
+
function formatCurrencyJS(value) { try { const number = parseFloat(String(value).replace(/\\s/g, '').replace(',', '.')); if (isNaN(number)) { return '0,00'; } return number.toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } catch (e) { return '0,00'; } }
|
| 699 |
+
function formatIntegerJS(value) { try { const number = parseInt(String(value).replace(/\\s/g, '').replace(',', '.').split('.')[0]); if (isNaN(number)) { return '0'; } return number.toLocaleString('ru-RU'); } catch (e) { return '0'; } }
|
| 700 |
+
</script>
|
| 701 |
+
__SCRIPTS__
|
| 702 |
+
</body>
|
| 703 |
+
</html>
|
| 704 |
+
"""
|
| 705 |
+
|
| 706 |
+
DASHBOARD_CONTENT = """
|
| 707 |
+
<div class="row">
|
| 708 |
+
<div class="col-lg-8">
|
| 709 |
+
<div class="row">
|
| 710 |
+
<div class="col-md-6 mb-4">
|
| 711 |
+
<div class="card text-bg-primary h-100">
|
| 712 |
+
<div class="card-body">
|
| 713 |
+
<h6 class="card-subtitle mb-2">Выручка сегодня</h6>
|
| 714 |
+
<p class="card-text display-5 fw-bold">{{ format_currency_py(stats.revenue_today) }} <small>сом</small></p>
|
| 715 |
+
</div>
|
| 716 |
+
</div>
|
| 717 |
+
</div>
|
| 718 |
+
<div class="col-md-6 mb-4">
|
| 719 |
+
<div class="card text-bg-success h-100">
|
| 720 |
+
<div class="card-body">
|
| 721 |
+
<h6 class="card-subtitle mb-2">Прибыль сегодня</h6>
|
| 722 |
+
<p class="card-text display-5 fw-bold">{{ format_currency_py(stats.profit_today) }} <small>сом</small></p>
|
| 723 |
+
</div>
|
| 724 |
+
</div>
|
| 725 |
+
</div>
|
| 726 |
+
<div class="col-md-6 mb-4">
|
| 727 |
+
<div class="card h-100">
|
| 728 |
+
<div class="card-body">
|
| 729 |
+
<h6 class="card-subtitle mb-2 text-muted">Транзакций сегодня</h6>
|
| 730 |
+
<p class="card-text display-5 fw-bold">{{ stats.transactions_today }}</p>
|
| 731 |
+
</div>
|
| 732 |
+
</div>
|
| 733 |
+
</div>
|
| 734 |
+
<div class="col-md-6 mb-4">
|
| 735 |
+
<div class="card h-100">
|
| 736 |
+
<div class="card-body">
|
| 737 |
+
<h6 class="card-subtitle mb-2 text-muted">Остатки в кассах</h6>
|
| 738 |
+
<p class="card-text display-5 fw-bold">{{ format_currency_py(stats.total_cash_balance) }} <small>сом</small></p>
|
| 739 |
+
</div>
|
| 740 |
+
</div>
|
| 741 |
+
</div>
|
| 742 |
+
</div>
|
| 743 |
+
</div>
|
| 744 |
+
<div class="col-lg-4 mb-4">
|
| 745 |
+
<div class="card h-100">
|
| 746 |
+
<div class="card-header">Заканчивающиеся товары ({{ stats.products_low_stock }})</div>
|
| 747 |
+
<div class="card-body">
|
| 748 |
+
{% if stats.low_stock_items %}
|
| 749 |
+
<ul class="list-group list-group-flush">
|
| 750 |
+
{% for item in stats.low_stock_items %}
|
| 751 |
+
<li class="list-group-item d-flex justify-content-between align-items-center">
|
| 752 |
+
{{ item.name }}
|
| 753 |
+
<span class="badge bg-danger rounded-pill">{{ item.quantity }} шт.</span>
|
| 754 |
+
</li>
|
| 755 |
+
{% endfor %}
|
| 756 |
+
</ul>
|
| 757 |
+
{% else %}
|
| 758 |
+
<p class="text-muted text-center">Всех товаров достаточно.</p>
|
| 759 |
+
{% endif %}
|
| 760 |
+
</div>
|
| 761 |
+
</div>
|
| 762 |
+
</div>
|
| 763 |
+
</div>
|
| 764 |
+
<div class="card">
|
| 765 |
+
<div class="card-header">Баланс касс</div>
|
| 766 |
+
<div class="card-body">
|
| 767 |
+
<div class="table-responsive">
|
| 768 |
+
<table class="table">
|
| 769 |
+
<thead><tr><th>Касса</th><th class="text-end">Баланс</th></tr></thead>
|
| 770 |
+
<tbody>
|
| 771 |
+
{% for cr in cash_registers %}
|
| 772 |
+
<tr><td>{{ cr.name }}</td><td class="text-end">{{ format_currency_py(cr.balance) }} сом</td></tr>
|
| 773 |
+
{% else %}
|
| 774 |
+
<tr><td colspan="2" class="text-center text-muted">Нет созданных касс.</td></tr>
|
| 775 |
+
{% endfor %}
|
| 776 |
+
</tbody>
|
| 777 |
+
</table>
|
| 778 |
+
</div>
|
| 779 |
+
</div>
|
| 780 |
+
</div>
|
| 781 |
+
"""
|
| 782 |
+
|
| 783 |
+
INVENTORY_CONTENT = """
|
| 784 |
+
<div class="card mb-4">
|
| 785 |
+
<div class="card-header">Добавить новый товар</div>
|
| 786 |
+
<div class="card-body">
|
| 787 |
+
<form method="POST">
|
| 788 |
+
<div class="row g-3">
|
| 789 |
+
<div class="col-md-4"><label class="form-label">Название</label><input type="text" name="name" class="form-control" required></div>
|
| 790 |
+
<div class="col-md-4"><label class="form-label">Артикул / Штрихкод</label><input type="text" name="sku" class="form-control" placeholder="Оставить пустым для автогенерации"></div>
|
| 791 |
+
<div class="col-md-4"><label class="form-label">Количество</label><input type="number" name="quantity" class="form-control" value="0" min="0" step="1"></div>
|
| 792 |
+
<div class="col-md-4"><label class="form-label">Цена закупки</label><input type="text" name="purchase_price" class="form-control" value="0" inputmode="decimal"></div>
|
| 793 |
+
<div class="col-md-4"><label class="form-label">Цена продажи</label><input type="text" name="selling_price" class="form-control" required inputmode="decimal"></div>
|
| 794 |
+
<div class="col-md-3"><label class="form-label">Мин. остаток</label><input type="number" name="low_stock_threshold" class="form-control" value="5" min="0" step="1"></div>
|
| 795 |
+
<div class="col-md-1 d-flex align-items-end"><button type="submit" name="action" value="add" class="btn btn-primary w-100">Добавить</button></div>
|
| 796 |
+
</div>
|
| 797 |
+
</form>
|
| 798 |
+
</div>
|
| 799 |
+
</div>
|
| 800 |
+
<div class="card">
|
| 801 |
+
<div class="card-header">Список товаров</div>
|
| 802 |
+
<div class="card-body">
|
| 803 |
+
<input type="text" id="inventory-search" class="form-control mb-3" placeholder="Поиск по названию или артикулу...">
|
| 804 |
+
<div class="table-responsive">
|
| 805 |
+
<table class="table table-hover" id="inventory-table">
|
| 806 |
+
<thead><tr><th>Название</th><th>Артикул/ШК</th><th>Кол-во</th><th>Цена закупки</th><th>Цена продажи</th><th>Действия</th></tr></thead>
|
| 807 |
+
<tbody>
|
| 808 |
+
{% for p in products %}
|
| 809 |
+
<tr data-search="{{ p.name|lower }} {{ p.sku|lower }}">
|
| 810 |
+
<td>{{ p.name }}</td>
|
| 811 |
+
<td>{{ p.sku }}</td>
|
| 812 |
+
<td><span class="badge rounded-pill text-bg-{{ 'danger' if to_int(p.quantity) <= to_int(p.low_stock_threshold) else 'secondary' }}">{{ p.quantity }}</span></td>
|
| 813 |
+
<td>{{ format_currency_py(p.purchase_price) }}</td>
|
| 814 |
+
<td>{{ format_currency_py(p.selling_price) }}</td>
|
| 815 |
+
<td>
|
| 816 |
+
<button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModal" data-product='{{ p|tojson }}'><i class="fas fa-edit"></i></button>
|
| 817 |
+
<form method="POST" action="{{ url_for('delete_product', product_id=p.id) }}" onsubmit="return confirm('Удалить товар?')" class="d-inline">
|
| 818 |
+
<button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
|
| 819 |
+
</form>
|
| 820 |
+
</td>
|
| 821 |
+
</tr>
|
| 822 |
+
{% endfor %}
|
| 823 |
+
</tbody>
|
| 824 |
+
</table>
|
| 825 |
+
</div>
|
| 826 |
+
</div>
|
| 827 |
+
</div>
|
| 828 |
+
|
| 829 |
+
<div class="modal fade" id="editModal" tabindex="-1">
|
| 830 |
+
<div class="modal-dialog modal-lg">
|
| 831 |
+
<div class="modal-content">
|
| 832 |
+
<div class="modal-header">
|
| 833 |
+
<h5 class="modal-title">Редактировать товар</h5>
|
| 834 |
+
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
| 835 |
+
</div>
|
| 836 |
+
<form method="POST">
|
| 837 |
+
<div class="modal-body">
|
| 838 |
+
<input type="hidden" name="action" value="edit">
|
| 839 |
+
<input type="hidden" name="id" id="edit-id">
|
| 840 |
+
<div class="row g-3">
|
| 841 |
+
<div class="col-md-6"><label class="form-label">Название</label><input type="text" id="edit-name" name="name" class="form-control" required></div>
|
| 842 |
+
<div class="col-md-6"><label class="form-label">Артикул / Штрихкод</label><input type="text" id="edit-sku" name="sku" class="form-control"></div>
|
| 843 |
+
<div class="col-md-4"><label class="form-label">Количество</label><input type="number" id="edit-quantity" name="quantity" class="form-control" min="0" step="1"></div>
|
| 844 |
+
<div class="col-md-4"><label class="form-label">Цена закупки</label><input type="text" id="edit-purchase_price" name="purchase_price" class="form-control" inputmode="decimal"></div>
|
| 845 |
+
<div class="col-md-4"><label class="form-label">Цена продажи</label><input type="text" id="edit-selling_price" name="selling_price" class="form-control" required inputmode="decimal"></div>
|
| 846 |
+
<div class="col-md-4"><label class="form-label">Мин. остаток</label><input type="number" id="edit-low_stock_threshold" name="low_stock_threshold" class="form-control" min="0" step="1"></div>
|
| 847 |
+
</div>
|
| 848 |
+
</div>
|
| 849 |
+
<div class="modal-footer">
|
| 850 |
+
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
| 851 |
+
<button type="submit" class="btn btn-primary">Сохранить</button>
|
| 852 |
+
</div>
|
| 853 |
+
</form>
|
| 854 |
+
</div>
|
| 855 |
+
</div>
|
| 856 |
+
</div>
|
| 857 |
+
"""
|
| 858 |
+
|
| 859 |
+
INVENTORY_SCRIPTS = """
|
| 860 |
+
<script>
|
| 861 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 862 |
+
const editModal = document.getElementById('editModal');
|
| 863 |
+
editModal.addEventListener('show.bs.modal', event => {
|
| 864 |
+
const button = event.relatedTarget;
|
| 865 |
+
const product = JSON.parse(button.getAttribute('data-product'));
|
| 866 |
+
|
| 867 |
+
editModal.querySelector('#edit-id').value = product.id;
|
| 868 |
+
editModal.querySelector('#edit-name').value = product.name;
|
| 869 |
+
editModal.querySelector('#edit-sku').value = product.sku;
|
| 870 |
+
editModal.querySelector('#edit-quantity').value = product.quantity;
|
| 871 |
+
editModal.querySelector('#edit-purchase_price').value = String(product.purchase_price).replace('.', ',');
|
| 872 |
+
editModal.querySelector('#edit-selling_price').value = String(product.selling_price).replace('.', ',');
|
| 873 |
+
editModal.querySelector('#edit-low_stock_threshold').value = product.low_stock_threshold;
|
| 874 |
+
});
|
| 875 |
+
|
| 876 |
+
const searchInput = document.getElementById('inventory-search');
|
| 877 |
+
const tableBody = document.getElementById('inventory-table').querySelector('tbody');
|
| 878 |
+
searchInput.addEventListener('input', () => {
|
| 879 |
+
const searchTerm = searchInput.value.toLowerCase();
|
| 880 |
+
tableBody.querySelectorAll('tr').forEach(row => {
|
| 881 |
+
row.style.display = row.dataset.search.includes(searchTerm) ? '' : 'none';
|
| 882 |
+
});
|
| 883 |
+
});
|
| 884 |
+
});
|
| 885 |
+
</script>
|
| 886 |
+
"""
|
| 887 |
+
|
| 888 |
+
POS_CONTENT = """
|
| 889 |
+
<div class="row">
|
| 890 |
+
<div class="col-lg-7">
|
| 891 |
+
<div class="card">
|
| 892 |
+
<div class="card-header d-flex justify-content-between align-items-center">
|
| 893 |
+
Товары
|
| 894 |
+
<button id="scan-btn" class="btn btn-sm btn-outline-primary"><i class="fas fa-qrcode me-1"></i> Сканировать</button>
|
| 895 |
+
</div>
|
| 896 |
+
<div class="card-body">
|
| 897 |
+
<div id="qr-reader" style="width:100%;"></div>
|
| 898 |
+
<div id="qr-reader-results" class="alert alert-info mt-2" style="display: none;"></div>
|
| 899 |
+
<div class="input-group my-3">
|
| 900 |
+
<input type="text" id="sku-input" class="form-control" placeholder="Введите артикул/штрихкод и нажмите Enter">
|
| 901 |
+
<button class="btn btn-outline-secondary" id="add-by-sku-btn" type="button"><i class="fas fa-plus"></i></button>
|
| 902 |
+
</div>
|
| 903 |
+
</div>
|
| 904 |
+
</div>
|
| 905 |
+
</div>
|
| 906 |
+
<div class="col-lg-5">
|
| 907 |
+
<div class="card">
|
| 908 |
+
<div class="card-header">
|
| 909 |
+
<div class="d-flex justify-content-between align-items-center">
|
| 910 |
+
<span>Корзина</span>
|
| 911 |
+
<select id="cash-register-select" class="form-select form-select-sm w-50">
|
| 912 |
+
{% for cr in cash_registers %}
|
| 913 |
+
<option value="{{ cr.id }}">{{ cr.name }}</option>
|
| 914 |
+
{% endfor %}
|
| 915 |
+
</select>
|
| 916 |
+
</div>
|
| 917 |
+
</div>
|
| 918 |
+
<div class="card-body">
|
| 919 |
+
<div id="cart-items" style="min-height: 200px;">
|
| 920 |
+
<p class="text-muted text-center" id="cart-placeholder">Корзина пуста</p>
|
| 921 |
+
</div>
|
| 922 |
+
</div>
|
| 923 |
+
<div class="card-footer">
|
| 924 |
+
<h4 class="d-flex justify-content-between">
|
| 925 |
+
<span>Итого:</span>
|
| 926 |
+
<strong id="cart-total">0,00 сом</strong>
|
| 927 |
+
</h4>
|
| 928 |
+
<div class="d-grid gap-2">
|
| 929 |
+
<button id="checkout-btn" class="btn btn-success btn-lg" disabled><i class="fas fa-check me-2"></i>Оплатить</button>
|
| 930 |
+
</div>
|
| 931 |
+
</div>
|
| 932 |
+
</div>
|
| 933 |
+
</div>
|
| 934 |
+
</div>
|
| 935 |
+
"""
|
| 936 |
+
|
| 937 |
+
POS_SCRIPTS = """
|
| 938 |
+
<script>
|
| 939 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 940 |
+
let cart = [];
|
| 941 |
+
const skuInput = document.getElementById('sku-input');
|
| 942 |
+
const addBySkuBtn = document.getElementById('add-by-sku-btn');
|
| 943 |
+
const cartItemsContainer = document.getElementById('cart-items');
|
| 944 |
+
const cartTotalEl = document.getElementById('cart-total');
|
| 945 |
+
const checkoutBtn = document.getElementById('checkout-btn');
|
| 946 |
+
const cartPlaceholder = document.getElementById('cart-placeholder');
|
| 947 |
+
const cashRegisterSelect = document.getElementById('cash-register-select');
|
| 948 |
+
let html5QrCode = null;
|
| 949 |
+
|
| 950 |
+
function renderCart() {
|
| 951 |
+
cartItemsContainer.innerHTML = '';
|
| 952 |
+
if (cart.length === 0) {
|
| 953 |
+
cartItemsContainer.appendChild(cartPlaceholder);
|
| 954 |
+
cartPlaceholder.style.display = 'block';
|
| 955 |
+
checkoutBtn.disabled = true;
|
| 956 |
+
} else {
|
| 957 |
+
cartPlaceholder.style.display = 'none';
|
| 958 |
+
checkoutBtn.disabled = false;
|
| 959 |
+
const table = document.createElement('table');
|
| 960 |
+
table.className = 'table table-sm';
|
| 961 |
+
table.innerHTML = '<thead><tr><th>Товар</th><th>Цена</th><th class="text-center">Кол-во</th><th class="text-end">Сумма</th><th></th></tr></thead>';
|
| 962 |
+
const tbody = document.createElement('tbody');
|
| 963 |
+
cart.forEach((item, index) => {
|
| 964 |
+
const row = document.createElement('tr');
|
| 965 |
+
row.innerHTML = `
|
| 966 |
+
<td>${item.name}</td>
|
| 967 |
+
<td>${formatCurrencyJS(item.selling_price)}</td>
|
| 968 |
+
<td class="text-center">
|
| 969 |
+
<div class="input-group input-group-sm">
|
| 970 |
+
<button class="btn btn-outline-secondary" type="button" onclick="updateCartQuantity(${index}, -1)">-</button>
|
| 971 |
+
<input type="text" class="form-control text-center" value="${item.quantity}" readonly>
|
| 972 |
+
<button class="btn btn-outline-secondary" type="button" onclick="updateCartQuantity(${index}, 1)">+</button>
|
| 973 |
+
</div>
|
| 974 |
+
</td>
|
| 975 |
+
<td class="text-end">${formatCurrencyJS(item.selling_price * item.quantity)}</td>
|
| 976 |
+
<td><button class="btn btn-sm btn-outline-danger" onclick="removeFromCart(${index})"><i class="fas fa-times"></i></button></td>
|
| 977 |
+
`;
|
| 978 |
+
tbody.appendChild(row);
|
| 979 |
+
});
|
| 980 |
+
table.appendChild(tbody);
|
| 981 |
+
cartItemsContainer.appendChild(table);
|
| 982 |
+
}
|
| 983 |
+
updateTotal();
|
| 984 |
+
}
|
| 985 |
+
|
| 986 |
+
function updateTotal() {
|
| 987 |
+
const total = cart.reduce((sum, item) => sum + (item.selling_price * item.quantity), 0);
|
| 988 |
+
cartTotalEl.textContent = formatCurrencyJS(total) + ' сом';
|
| 989 |
+
}
|
| 990 |
+
|
| 991 |
+
async function addProductToCart(sku) {
|
| 992 |
+
try {
|
| 993 |
+
const response = await fetch(`/api/product/${sku}`);
|
| 994 |
+
const product = await response.json();
|
| 995 |
+
if (response.ok) {
|
| 996 |
+
const existingItem = cart.find(item => item.id === product.id);
|
| 997 |
+
if (existingItem) {
|
| 998 |
+
if (existingItem.quantity < product.quantity) {
|
| 999 |
+
existingItem.quantity++;
|
| 1000 |
+
} else {
|
| 1001 |
+
alert('Больше нет в наличии');
|
| 1002 |
+
}
|
| 1003 |
+
} else {
|
| 1004 |
+
cart.push({ ...product, quantity: 1 });
|
| 1005 |
+
}
|
| 1006 |
+
skuInput.value = '';
|
| 1007 |
+
renderCart();
|
| 1008 |
+
} else {
|
| 1009 |
+
alert(`Ошибка: ${product.error}`);
|
| 1010 |
+
}
|
| 1011 |
+
} catch (error) {
|
| 1012 |
+
console.error('Fetch error:', error);
|
| 1013 |
+
alert('Не удалось связаться с сервером.');
|
| 1014 |
+
}
|
| 1015 |
+
}
|
| 1016 |
+
|
| 1017 |
+
window.updateCartQuantity = (index, change) => {
|
| 1018 |
+
const item = cart[index];
|
| 1019 |
+
if (item) {
|
| 1020 |
+
const newQuantity = item.quantity + change;
|
| 1021 |
+
if (newQuantity > 0) {
|
| 1022 |
+
if(newQuantity <= parseInt(item.max_quantity || item.quantity)) { // A bit of a hack, server validates final
|
| 1023 |
+
item.quantity = newQuantity;
|
| 1024 |
+
} else {
|
| 1025 |
+
alert('Больше нет в наличии');
|
| 1026 |
+
}
|
| 1027 |
+
} else {
|
| 1028 |
+
removeFromCart(index);
|
| 1029 |
+
}
|
| 1030 |
+
renderCart();
|
| 1031 |
+
}
|
| 1032 |
+
};
|
| 1033 |
+
|
| 1034 |
+
window.removeFromCart = (index) => {
|
| 1035 |
+
cart.splice(index, 1);
|
| 1036 |
+
renderCart();
|
| 1037 |
+
};
|
| 1038 |
+
|
| 1039 |
+
addBySkuBtn.addEventListener('click', () => {
|
| 1040 |
+
const sku = skuInput.value.trim();
|
| 1041 |
+
if (sku) addProductToCart(sku);
|
| 1042 |
+
});
|
| 1043 |
+
|
| 1044 |
+
skuInput.addEventListener('keypress', e => {
|
| 1045 |
+
if (e.key === 'Enter') {
|
| 1046 |
+
addBySkuBtn.click();
|
| 1047 |
+
}
|
| 1048 |
+
});
|
| 1049 |
+
|
| 1050 |
+
checkoutBtn.addEventListener('click', async () => {
|
| 1051 |
+
if (cart.length === 0) return;
|
| 1052 |
+
|
| 1053 |
+
const saleData = {
|
| 1054 |
+
cart: cart.map(item => ({ id: item.id, quantity: item.quantity })),
|
| 1055 |
+
cash_register_id: cashRegisterSelect.value
|
| 1056 |
+
};
|
| 1057 |
+
|
| 1058 |
+
checkoutBtn.disabled = true;
|
| 1059 |
+
checkoutBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Обработка...';
|
| 1060 |
+
|
| 1061 |
+
try {
|
| 1062 |
+
const response = await fetch('/pos/checkout', {
|
| 1063 |
+
method: 'POST',
|
| 1064 |
+
headers: { 'Content-Type': 'application/json' },
|
| 1065 |
+
body: JSON.stringify(saleData)
|
| 1066 |
+
});
|
| 1067 |
+
const result = await response.json();
|
| 1068 |
+
if (response.ok) {
|
| 1069 |
+
alert('Продажа успешно завершена!');
|
| 1070 |
+
cart = [];
|
| 1071 |
+
renderCart();
|
| 1072 |
+
} else {
|
| 1073 |
+
alert(`Ошибка при продаже: ${result.error}`);
|
| 1074 |
+
}
|
| 1075 |
+
} catch(error) {
|
| 1076 |
+
console.error('Checkout error:', error);
|
| 1077 |
+
alert('Ошибка сети при завершении продажи.');
|
| 1078 |
+
} finally {
|
| 1079 |
+
checkoutBtn.disabled = false;
|
| 1080 |
+
checkoutBtn.innerHTML = '<i class="fas fa-check me-2"></i>Оплатить';
|
| 1081 |
+
}
|
| 1082 |
+
});
|
| 1083 |
+
|
| 1084 |
+
// QR Scanner
|
| 1085 |
+
const qrResultEl = document.getElementById('qr-reader-results');
|
| 1086 |
+
const onScanSuccess = (decodedText, decodedResult) => {
|
| 1087 |
+
qrResultEl.textContent = `Найден код: ${decodedText}`;
|
| 1088 |
+
qrResultEl.style.display = 'block';
|
| 1089 |
+
addProductToCart(decodedText);
|
| 1090 |
+
html5QrCode.pause();
|
| 1091 |
+
setTimeout(() => html5QrCode.resume(), 1000);
|
| 1092 |
+
};
|
| 1093 |
+
const onScanFailure = (error) => { /* console.warn(`QR error = ${error}`); */ };
|
| 1094 |
+
|
| 1095 |
+
document.getElementById('scan-btn').addEventListener('click', () => {
|
| 1096 |
+
const qrReaderDiv = document.getElementById('qr-reader');
|
| 1097 |
+
if (!html5QrCode) {
|
| 1098 |
+
html5QrCode = new Html5Qrcode("qr-reader");
|
| 1099 |
+
}
|
| 1100 |
+
if (qrReaderDiv.style.display === 'none' || qrReaderDiv.style.display === '') {
|
| 1101 |
+
qrReaderDiv.style.display = 'block';
|
| 1102 |
+
html5QrCode.start(
|
| 1103 |
+
{ facingMode: "environment" },
|
| 1104 |
+
{ fps: 10, qrbox: { width: 250, height: 250 } },
|
| 1105 |
+
onScanSuccess,
|
| 1106 |
+
onScanFailure
|
| 1107 |
+
).catch(err => alert("Не удалось запустить камеру. Убедитесь, что вы дали разрешение."));
|
| 1108 |
+
} else {
|
| 1109 |
+
html5QrCode.stop().then(() => {
|
| 1110 |
+
qrReaderDiv.style.display = 'none';
|
| 1111 |
+
qrResultEl.style.display = 'none';
|
| 1112 |
+
}).catch(err => console.error("Failed to stop QR code scanner.", err));
|
| 1113 |
+
}
|
| 1114 |
+
});
|
| 1115 |
+
|
| 1116 |
+
renderCart();
|
| 1117 |
+
});
|
| 1118 |
+
</script>
|
| 1119 |
+
"""
|
| 1120 |
+
|
| 1121 |
+
CASH_MANAGEMENT_CONTENT = """
|
| 1122 |
+
<div class="row">
|
| 1123 |
+
<div class="col-lg-5 mb-4">
|
| 1124 |
+
<div class="card">
|
| 1125 |
+
<div class="card-header">Кассы</div>
|
| 1126 |
+
<div class="card-body">
|
| 1127 |
+
<ul class="list-group mb-3">
|
| 1128 |
+
{% for cr in cash_registers %}
|
| 1129 |
+
<li class="list-group-item d-flex justify-content-between align-items-center">
|
| 1130 |
+
{{ cr.name }}
|
| 1131 |
+
<span class="badge bg-primary rounded-pill fs-6">{{ format_currency_py(cr.balance) }} сом</span>
|
| 1132 |
+
</li>
|
| 1133 |
+
{% else %}
|
| 1134 |
+
<li class="list-group-item text-muted">Нет созданных касс</li>
|
| 1135 |
+
{% endfor %}
|
| 1136 |
+
</ul>
|
| 1137 |
+
<form method="POST">
|
| 1138 |
+
<input type="hidden" name="action" value="add_register">
|
| 1139 |
+
<div class="input-group">
|
| 1140 |
+
<input type="text" name="name" class="form-control" placeholder="Название новой кассы" required>
|
| 1141 |
+
<input type="text" name="initial_balance" class="form-control" placeholder="Начальный баланс" value="0" inputmode="decimal">
|
| 1142 |
+
<button class="btn btn-outline-secondary" type="submit">Добавить</button>
|
| 1143 |
+
</div>
|
| 1144 |
+
</form>
|
| 1145 |
+
</div>
|
| 1146 |
+
</div>
|
| 1147 |
+
</div>
|
| 1148 |
+
<div class="col-lg-7 mb-4">
|
| 1149 |
+
<div class="card">
|
| 1150 |
+
<div class="card-header">Внесение/Изъятие средств</div>
|
| 1151 |
+
<div class="card-body">
|
| 1152 |
+
<form method="POST">
|
| 1153 |
+
<input type="hidden" name="action" value="add_operation">
|
| 1154 |
+
<div class="row g-2 align-items-end">
|
| 1155 |
+
<div class="col-md-4"><label class="form-label">Касса</label><select name="cash_register_id" class="form-select" required><option value="" disabled selected>-- Выберите --</option>{% for cr in cash_registers %}<option value="{{ cr.id }}">{{ cr.name }}</option>{% endfor %}</select></div>
|
| 1156 |
+
<div class="col-md-3"><label class="form-label">Тип</label><select name="type" class="form-select" required><option value="deposit">Внесение</option><option value="withdrawal">Изъятие/Расход</option></select></div>
|
| 1157 |
+
<div class="col-md-3"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal"></div>
|
| 1158 |
+
<div class="col-md-2"><button type="submit" class="btn btn-primary w-100">OK</button></div>
|
| 1159 |
+
<div class="col-12"><label class="form-label">Описание</label><input type="text" name="description" class="form-control" placeholder="например, оплата аренды"></div>
|
| 1160 |
+
</div>
|
| 1161 |
+
</form>
|
| 1162 |
+
</div>
|
| 1163 |
+
</div>
|
| 1164 |
+
</div>
|
| 1165 |
+
</div>
|
| 1166 |
+
<div class="card">
|
| 1167 |
+
<div class="card-header">История операций с наличными</div>
|
| 1168 |
+
<div class="card-body">
|
| 1169 |
+
<div class="table-responsive">
|
| 1170 |
+
<table class="table table-sm table-hover">
|
| 1171 |
+
<thead><tr><th>Дата</th><th>Касса</th><th>Тип</th><th>Сумма</th><th>Описание</th></tr></thead>
|
| 1172 |
+
<tbody>
|
| 1173 |
+
{% for op in cash_operations %}
|
| 1174 |
+
<tr>
|
| 1175 |
+
<td>{{ parse_iso_datetime(op.timestamp).strftime('%Y-%m-%d %H:%M') }}</td>
|
| 1176 |
+
<td>{{ op.cash_register_name }}</td>
|
| 1177 |
+
<td><span class="badge text-bg-{{ 'success' if op.type == 'deposit' else 'danger' }}">{{ 'Внесение' if op.type == 'deposit' else 'Изъятие' }}</span></td>
|
| 1178 |
+
<td>{{ format_currency_py(op.amount) }} сом</td>
|
| 1179 |
+
<td>{{ op.description }}</td>
|
| 1180 |
+
</tr>
|
| 1181 |
+
{% else %}
|
| 1182 |
+
<tr><td colspan="5" class="text-center text-muted">Операций не найдено.</td></tr>
|
| 1183 |
+
{% endfor %}
|
| 1184 |
+
</tbody>
|
| 1185 |
+
</table>
|
| 1186 |
+
</div>
|
| 1187 |
+
</div>
|
| 1188 |
+
</div>
|
| 1189 |
+
"""
|
| 1190 |
+
|
| 1191 |
+
REPORTS_CONTENT = """
|
| 1192 |
+
<div class="card mb-4">
|
| 1193 |
+
<div class="card-header">Фильтр периода</div>
|
| 1194 |
+
<div class="card-body">
|
| 1195 |
+
<form method="GET" action="{{ url_for('reports') }}">
|
| 1196 |
+
<div class="row g-3 align-items-end">
|
| 1197 |
+
<div class="col-md-auto"><label class="form-label">Период</label><select name="filter" class="form-select"><option value="today" {% if report.filter_type == 'today' %}selected{% endif %}>Сегодня</option><option value="week" {% if report.filter_type == 'week' %}selected{% endif %}>Эта неделя</option><option value="month" {% if report.filter_type == 'month' %}selected{% endif %}>Этот месяц</option><option value="custom" {% if report.filter_type == 'custom' %}selected{% endif %}>Произвольный</option></select></div>
|
| 1198 |
+
<div class="col-md-auto"><label class="form-label">Начало</label><input type="date" name="start_date" class="form-control" value="{{ report.start_date }}"></div>
|
| 1199 |
+
<div class="col-md-auto"><label class="form-label">Конец</label><input type="date" name="end_date" class="form-control" value="{{ report.end_date }}"></div>
|
| 1200 |
+
<div class="col-md-auto"><button type="submit" class="btn btn-primary">Показать</button></div>
|
| 1201 |
+
</div>
|
| 1202 |
+
</form>
|
| 1203 |
+
</div>
|
| 1204 |
+
</div>
|
| 1205 |
+
<h4>Отчет за период: <span class="text-primary">{{ report.start_date }} - {{ report.end_date }}</span></h4>
|
| 1206 |
+
<div class="row row-cols-1 row-cols-xl-4 g-4 my-3">
|
| 1207 |
+
<div class="col"><div class="card h-100"><div class="card-body"><h6 class="card-subtitle text-muted">Выручка</h6><p class="card-text fs-4 fw-bold">{{ format_currency_py(report.total_revenue) }}</p></div></div></div>
|
| 1208 |
+
<div class="col"><div class="card h-100"><div class="card-body"><h6 class="card-subtitle text-muted">Себестоимость</h6><p class="card-text fs-4 fw-bold">{{ format_currency_py(report.total_cost_of_goods) }}</p></div></div></div>
|
| 1209 |
+
<div class="col"><div class="card h-100"><div class="card-body"><h6 class="card-subtitle text-muted">Прочие расходы</h6><p class="card-text fs-4 fw-bold">{{ format_currency_py(report.total_expenses) }}</p></div></div></div>
|
| 1210 |
+
<div class="col"><div class="card text-bg-success h-100"><div class="card-body"><h6 class="card-subtitle">Чистая прибыль</h6><p class="card-text fs-4 fw-bold">{{ format_currency_py(report.net_profit) }}</p></div></div></div>
|
| 1211 |
+
</div>
|
| 1212 |
+
|
| 1213 |
+
<ul class="nav nav-tabs mb-3" id="reportTabs" role="tablist">
|
| 1214 |
+
<li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#sales-tab-pane">Продажи</button></li>
|
| 1215 |
+
<li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#products-tab-pane">Сводка по товарам</button></li>
|
| 1216 |
+
</ul>
|
| 1217 |
+
<div class="tab-content">
|
| 1218 |
+
<div class="tab-pane fade show active" id="sales-tab-pane">
|
| 1219 |
+
<div class="card"><div class="card-body"><div class="table-responsive">
|
| 1220 |
+
<table class="table">
|
| 1221 |
+
<thead><tr><th>Дата</th><th>ID Продажи</th><th>Товары</th><th class="text-end">Сумма</th></tr></thead>
|
| 1222 |
+
<tbody>
|
| 1223 |
+
{% for sale in report.filtered_sales %}
|
| 1224 |
+
<tr>
|
| 1225 |
+
<td>{{ parse_iso_datetime(sale.timestamp).strftime('%Y-%m-%d %H:%M') }}</td>
|
| 1226 |
+
<td><small>{{ sale.id[:8] }}</small></td>
|
| 1227 |
+
<td>
|
| 1228 |
+
<ul class="list-unstyled mb-0">
|
| 1229 |
+
{% for item in sale.items %}
|
| 1230 |
+
<li>{{ item.name }} - {{ item.quantity }} шт. x {{ format_currency_py(item.selling_price) }}</li>
|
| 1231 |
+
{% endfor %}
|
| 1232 |
+
</ul>
|
| 1233 |
+
</td>
|
| 1234 |
+
<td class="text-end fw-bold">{{ format_currency_py(sale.total_amount) }}</td>
|
| 1235 |
+
</tr>
|
| 1236 |
+
{% else %}
|
| 1237 |
+
<tr><td colspan="4" class="text-center text-muted">Продаж за период не было.</td></tr>
|
| 1238 |
+
{% endfor %}
|
| 1239 |
+
</tbody>
|
| 1240 |
+
</table>
|
| 1241 |
+
</div></div></div>
|
| 1242 |
+
</div>
|
| 1243 |
+
<div class="tab-pane fade" id="products-tab-pane">
|
| 1244 |
+
<div class="card"><div class="card-body"><div class="table-responsive">
|
| 1245 |
+
<table class="table">
|
| 1246 |
+
<thead><tr><th>Товар</th><th>Продано, шт</th><th class="text-end">Выручка</th><th class="text-end">Себестоимость</th><th class="text-end">Прибыль</th></tr></thead>
|
| 1247 |
+
<tbody>
|
| 1248 |
+
{% for p_sum in report.product_summary %}
|
| 1249 |
+
<tr>
|
| 1250 |
+
<td>{{ p_sum.name }} <small class="text-muted">({{ p_sum.sku }})</small></td>
|
| 1251 |
+
<td>{{ format_integer_py(p_sum.quantity) }}</td>
|
| 1252 |
+
<td class="text-end">{{ format_currency_py(p_sum.revenue) }}</td>
|
| 1253 |
+
<td class="text-end">{{ format_currency_py(p_sum.cogs) }}</td>
|
| 1254 |
+
<td class="text-end fw-bold">{{ format_currency_py(p_sum.revenue - p_sum.cogs) }}</td>
|
| 1255 |
+
</tr>
|
| 1256 |
+
{% else %}
|
| 1257 |
+
<tr><td colspan="5" class="text-center text-muted">Нет данных.</td></tr>
|
| 1258 |
+
{% endfor %}
|
| 1259 |
+
</tbody>
|
| 1260 |
+
</table>
|
| 1261 |
+
</div></div></div>
|
| 1262 |
+
</div>
|
| 1263 |
+
</div>
|
| 1264 |
+
"""
|
| 1265 |
+
|
| 1266 |
+
REPORTS_SCRIPTS = """
|
| 1267 |
+
<script>
|
| 1268 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 1269 |
+
const filterSelect = document.querySelector('select[name="filter"]');
|
| 1270 |
+
const startDateInput = document.querySelector('input[name="start_date"]');
|
| 1271 |
+
const endDateInput = document.querySelector('input[name="end_date"]');
|
| 1272 |
+
|
| 1273 |
+
function setDates(filter) {
|
| 1274 |
+
const today = new Date();
|
| 1275 |
+
const y = today.getFullYear();
|
| 1276 |
+
const m = today.getMonth();
|
| 1277 |
+
const d = today.getDate();
|
| 1278 |
+
let start = today;
|
| 1279 |
+
let end = today;
|
| 1280 |
+
|
| 1281 |
+
if (filter === 'today') {
|
| 1282 |
+
start = new Date(y, m, d);
|
| 1283 |
+
end = new Date(y, m, d);
|
| 1284 |
+
} else if (filter === 'week') {
|
| 1285 |
+
start = new Date(y, m, d - today.getDay());
|
| 1286 |
+
end = new Date(y, m, d + (6 - today.getDay()));
|
| 1287 |
+
} else if (filter === 'month') {
|
| 1288 |
+
start = new Date(y, m, 1);
|
| 1289 |
+
end = new Date(y, m + 1, 0);
|
| 1290 |
+
}
|
| 1291 |
+
|
| 1292 |
+
const formatDate = (date) => date.toISOString().split('T')[0];
|
| 1293 |
+
if (filter !== 'custom') {
|
| 1294 |
+
startDateInput.value = formatDate(start);
|
| 1295 |
+
endDateInput.value = formatDate(end);
|
| 1296 |
+
}
|
| 1297 |
+
startDateInput.form.submit();
|
| 1298 |
+
}
|
| 1299 |
+
|
| 1300 |
+
filterSelect.addEventListener('change', e => {
|
| 1301 |
+
if(e.target.value !== 'custom') {
|
| 1302 |
+
setDates(e.target.value);
|
| 1303 |
+
}
|
| 1304 |
+
});
|
| 1305 |
+
});
|
| 1306 |
+
</script>
|
| 1307 |
+
"""
|
| 1308 |
+
|
| 1309 |
+
@app.context_processor
|
| 1310 |
+
def inject_utils():
|
| 1311 |
+
return {
|
| 1312 |
+
'get_current_time': get_current_time,
|
| 1313 |
+
'format_currency_py': format_currency_py,
|
| 1314 |
+
'format_integer_py': format_integer_py,
|
| 1315 |
+
'to_decimal': to_decimal,
|
| 1316 |
+
'to_int': to_int,
|
| 1317 |
+
'parse_iso_datetime': parse_iso_datetime,
|
| 1318 |
+
'tojson': json.dumps
|
| 1319 |
+
}
|
| 1320 |
+
|
| 1321 |
+
if __name__ == '__main__':
|
| 1322 |
+
if HF_TOKEN_WRITE != "YOUR_WRITE_TOKEN_HERE" and REPO_ID != "Kgshop/postest":
|
| 1323 |
+
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 1324 |
+
backup_thread.start()
|
| 1325 |
+
else:
|
| 1326 |
+
logging.warning("Hugging Face backup is not configured. Thread not started.")
|
| 1327 |
+
|
| 1328 |
+
try:
|
| 1329 |
+
logging.info("Initial data loading...")
|
| 1330 |
+
load_data()
|
| 1331 |
+
logging.info("Data loaded/initialized successfully.")
|
| 1332 |
+
except Exception as e:
|
| 1333 |
+
logging.critical(f"Failed to load database on startup: {e}", exc_info=True)
|
| 1334 |
+
|
| 1335 |
+
logging.info("Starting Flask application on http://0.0.0.0:7860")
|
| 1336 |
+
app.run(debug=False, host='0.0.0.0', port=7860, use_reloader=False)
|