Delete app.py
Browse files
app.py
DELETED
|
@@ -1,1410 +0,0 @@
|
|
| 1 |
-
from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, send_from_directory
|
| 2 |
-
import json
|
| 3 |
-
import os
|
| 4 |
-
import logging
|
| 5 |
-
import threading
|
| 6 |
-
import time
|
| 7 |
-
from datetime import datetime, timedelta, date
|
| 8 |
-
import pytz
|
| 9 |
-
from huggingface_hub import HfApi, hf_hub_download
|
| 10 |
-
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
|
| 11 |
-
from werkzeug.utils import secure_filename
|
| 12 |
-
import uuid
|
| 13 |
-
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
| 14 |
-
import functools
|
| 15 |
-
from PIL import Image
|
| 16 |
-
import io
|
| 17 |
-
|
| 18 |
-
app = Flask(__name__)
|
| 19 |
-
app.secret_key = os.urandom(24)
|
| 20 |
-
PRODUCTS_DATA_FILE = 'products.json'
|
| 21 |
-
KASSA_DATA_FILE = 'kassa.json'
|
| 22 |
-
UPLOAD_FOLDER = 'uploads'
|
| 23 |
-
THUMBNAIL_FOLDER = os.path.join(UPLOAD_FOLDER, 'thumbnails')
|
| 24 |
-
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 25 |
-
os.makedirs(THUMBNAIL_FOLDER, exist_ok=True)
|
| 26 |
-
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
| 27 |
-
app.config['THUMBNAIL_FOLDER'] = THUMBNAIL_FOLDER
|
| 28 |
-
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
|
| 29 |
-
|
| 30 |
-
HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE")
|
| 31 |
-
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", "YOUR_READ_TOKEN_HERE")
|
| 32 |
-
REPO_ID = "Kgshop/postest"
|
| 33 |
-
|
| 34 |
-
BISHKEK_TZ = pytz.timezone('Asia/Bishkek')
|
| 35 |
-
|
| 36 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 37 |
-
|
| 38 |
-
products_data_lock = threading.Lock()
|
| 39 |
-
kassa_data_lock = threading.Lock()
|
| 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): return str(obj)
|
| 47 |
-
return json.JSONEncoder.default(self, obj)
|
| 48 |
-
|
| 49 |
-
def to_decimal(value_str, default='0.00'):
|
| 50 |
-
if value_str is None or value_str == '': return Decimal(default)
|
| 51 |
-
try: return Decimal(str(value_str).replace(',', '.'))
|
| 52 |
-
except InvalidOperation: logging.warning(f"Could not convert '{value_str}' to Decimal. Returned {default}."); return Decimal(default)
|
| 53 |
-
|
| 54 |
-
def initialize_products_data():
|
| 55 |
-
return {
|
| 56 |
-
'products': [], 'categories': [], 'suppliers': [],
|
| 57 |
-
'config': {'low_stock_threshold': '10'}
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
def initialize_kassa_data():
|
| 61 |
-
return {'registers': [], 'sales': [], 'transactions': []}
|
| 62 |
-
|
| 63 |
-
def load_json_data(file_path, lock, init_func, repo_id, hf_token):
|
| 64 |
-
with lock:
|
| 65 |
-
try:
|
| 66 |
-
logging.info(f"Attempting download of {file_path} from {repo_id}...")
|
| 67 |
-
hf_hub_download(repo_id=repo_id, filename=file_path, repo_type="dataset", token=hf_token, local_dir=".", local_dir_use_symlinks=False, force_download=True)
|
| 68 |
-
logging.info(f"{file_path} downloaded successfully.")
|
| 69 |
-
except RepositoryNotFoundError:
|
| 70 |
-
logging.warning(f"Repository {repo_id} not found. Checking local {file_path}.")
|
| 71 |
-
except HfHubHTTPError as e:
|
| 72 |
-
if e.response.status_code == 404:
|
| 73 |
-
logging.warning(f"File {file_path} not found in repository {repo_id}. Checking local file.")
|
| 74 |
-
else:
|
| 75 |
-
logging.error(f"HTTP error downloading {file_path}: {e}")
|
| 76 |
-
except Exception as e:
|
| 77 |
-
logging.error(f"Unknown error downloading {file_path}: {e}")
|
| 78 |
-
|
| 79 |
-
try:
|
| 80 |
-
with open(file_path, 'r', encoding='utf-8') as file:
|
| 81 |
-
data = json.load(file)
|
| 82 |
-
logging.info(f"Data loaded successfully from local {file_path}.")
|
| 83 |
-
return data
|
| 84 |
-
except FileNotFoundError:
|
| 85 |
-
logging.warning(f"Local file {file_path} not found. Initializing empty structure.")
|
| 86 |
-
return init_func()
|
| 87 |
-
except json.JSONDecodeError:
|
| 88 |
-
logging.error(f"JSON decode error in {file_path}. Initializing empty structure.")
|
| 89 |
-
try:
|
| 90 |
-
bad_file_path = f"{file_path}.{get_current_time().strftime('%Y%m%d%H%M%S')}.bad"
|
| 91 |
-
os.rename(file_path, bad_file_path)
|
| 92 |
-
logging.info(f"Corrupted file {file_path} renamed to {bad_file_path}")
|
| 93 |
-
except Exception as backup_err:
|
| 94 |
-
logging.error(f"Failed to backup corrupted file {file_path}: {backup_err}")
|
| 95 |
-
return init_func()
|
| 96 |
-
except Exception as e:
|
| 97 |
-
logging.error(f"Unknown error loading local data from {file_path}: {e}", exc_info=True)
|
| 98 |
-
return init_func()
|
| 99 |
-
|
| 100 |
-
def save_json_data(data, file_path, lock):
|
| 101 |
-
with lock:
|
| 102 |
-
try:
|
| 103 |
-
temp_file = file_path + ".tmp"
|
| 104 |
-
with open(temp_file, 'w', encoding='utf-8') as file:
|
| 105 |
-
json.dump(data, file, ensure_ascii=False, indent=4, cls=DecimalEncoder)
|
| 106 |
-
os.replace(temp_file, file_path)
|
| 107 |
-
logging.info(f"Data successfully saved to local file {file_path}.")
|
| 108 |
-
except Exception as e:
|
| 109 |
-
logging.error(f"Critical error saving data to {file_path}: {e}", exc_info=True)
|
| 110 |
-
if os.path.exists(temp_file):
|
| 111 |
-
try: os.remove(temp_file)
|
| 112 |
-
except OSError as rm_err: logging.error(f"Failed to remove temporary file {temp_file}: {rm_err}")
|
| 113 |
-
|
| 114 |
-
def load_products_data():
|
| 115 |
-
return load_json_data(PRODUCTS_DATA_FILE, products_data_lock, initialize_products_data, REPO_ID, HF_TOKEN_READ)
|
| 116 |
-
|
| 117 |
-
def save_products_data(data):
|
| 118 |
-
save_json_data(data, PRODUCTS_DATA_FILE, products_data_lock)
|
| 119 |
-
|
| 120 |
-
def load_kassa_data():
|
| 121 |
-
return load_json_data(KASSA_DATA_FILE, kassa_data_lock, initialize_kassa_data, REPO_ID, HF_TOKEN_READ)
|
| 122 |
-
|
| 123 |
-
def save_kassa_data(data):
|
| 124 |
-
save_json_data(data, KASSA_DATA_FILE, kassa_data_lock)
|
| 125 |
-
|
| 126 |
-
@functools.lru_cache(maxsize=1)
|
| 127 |
-
def get_hf_api():
|
| 128 |
-
if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE":
|
| 129 |
-
logging.warning("HF_TOKEN_WRITE not set. Uploads to Hugging Face will be disabled.")
|
| 130 |
-
return None
|
| 131 |
-
try: return HfApi()
|
| 132 |
-
except Exception as e: logging.error(f"Error initializing HfApi: {e}"); return None
|
| 133 |
-
|
| 134 |
-
def upload_db_to_hf(filepath):
|
| 135 |
-
api = get_hf_api()
|
| 136 |
-
if not api: logging.warning(f"HfApi not initialized. Upload of {filepath} to Hugging Face skipped."); return
|
| 137 |
-
if not os.path.exists(filepath): logging.warning(f"Local file {filepath} not found. Upload to Hugging Face skipped."); return
|
| 138 |
-
try:
|
| 139 |
-
filename = os.path.basename(filepath)
|
| 140 |
-
commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z')
|
| 141 |
-
logging.info(f"Starting upload of {filename} to Hugging Face...")
|
| 142 |
-
api.upload_file(
|
| 143 |
-
path_or_fileobj=filepath, path_in_repo=filename, repo_id=REPO_ID, repo_type="dataset",
|
| 144 |
-
token=HF_TOKEN_WRITE, commit_message=f"Automated backup {filename} {commit_time}",
|
| 145 |
-
run_as_future=True
|
| 146 |
-
)
|
| 147 |
-
logging.info(f"Upload of {filename} to Hugging Face initiated.")
|
| 148 |
-
except RepositoryNotFoundError: logging.error(f"Upload error: Repository {REPO_ID} not found on Hugging Face.")
|
| 149 |
-
except Exception as e: logging.error(f"Error initiating upload of {filepath} to Hugging Face: {e}")
|
| 150 |
-
|
| 151 |
-
def periodic_backup():
|
| 152 |
-
logging.info("Starting periodic backup thread.")
|
| 153 |
-
while True:
|
| 154 |
-
backup_interval = 1800
|
| 155 |
-
logging.debug(f"Periodic backup sleeping for {backup_interval} seconds...")
|
| 156 |
-
time.sleep(backup_interval)
|
| 157 |
-
logging.info("Starting scheduled backup...")
|
| 158 |
-
try:
|
| 159 |
-
if os.path.exists(PRODUCTS_DATA_FILE):
|
| 160 |
-
upload_db_to_hf(PRODUCTS_DATA_FILE)
|
| 161 |
-
if os.path.exists(KASSA_DATA_FILE):
|
| 162 |
-
upload_db_to_hf(KASSA_DATA_FILE)
|
| 163 |
-
logging.info("Scheduled backup completed.")
|
| 164 |
-
except Exception as e:
|
| 165 |
-
logging.error(f"Error during scheduled backup: {e}", exc_info=True)
|
| 166 |
-
|
| 167 |
-
def find_product_by_id(product_id):
|
| 168 |
-
products_data = load_products_data()
|
| 169 |
-
for product in products_data.get('products', []):
|
| 170 |
-
if product.get('id') == product_id:
|
| 171 |
-
return product
|
| 172 |
-
return None
|
| 173 |
-
|
| 174 |
-
def find_product_by_barcode(barcode):
|
| 175 |
-
products_data = load_products_data()
|
| 176 |
-
for product in products_data.get('products', []):
|
| 177 |
-
if product.get('barcode') == barcode:
|
| 178 |
-
return product
|
| 179 |
-
return None
|
| 180 |
-
|
| 181 |
-
def find_register_by_id(register_id):
|
| 182 |
-
kassa_data = load_kassa_data()
|
| 183 |
-
for register in kassa_data.get('registers', []):
|
| 184 |
-
if register.get('id') == register_id:
|
| 185 |
-
return register
|
| 186 |
-
return None
|
| 187 |
-
|
| 188 |
-
def create_thumbnail(image_path, thumb_path, size=(100, 100)):
|
| 189 |
-
try:
|
| 190 |
-
with Image.open(image_path) as img:
|
| 191 |
-
img.thumbnail(size)
|
| 192 |
-
img.save(thumb_path, "JPEG")
|
| 193 |
-
logging.info(f"Thumbnail created: {thumb_path}")
|
| 194 |
-
return os.path.basename(thumb_path)
|
| 195 |
-
except Exception as e:
|
| 196 |
-
logging.error(f"Error creating thumbnail for {image_path}: {e}")
|
| 197 |
-
return None
|
| 198 |
-
|
| 199 |
-
def format_currency_py(value):
|
| 200 |
-
try:
|
| 201 |
-
number = to_decimal(value)
|
| 202 |
-
formatted_num = f"{number:,.2f}".replace(",", "TEMP_SPACE").replace(".", ",").replace("TEMP_SPACE", " ")
|
| 203 |
-
return formatted_num
|
| 204 |
-
except (InvalidOperation, TypeError, ValueError): return "0,00"
|
| 205 |
-
|
| 206 |
-
def format_integer_py(value):
|
| 207 |
-
try:
|
| 208 |
-
number = to_decimal(value).to_integral_value(rounding=ROUND_HALF_UP)
|
| 209 |
-
return f"{number:,}".replace(",", " ")
|
| 210 |
-
except (InvalidOperation, TypeError, ValueError): return "0"
|
| 211 |
-
|
| 212 |
-
@app.route('/')
|
| 213 |
-
def index():
|
| 214 |
-
return redirect(url_for('sale'))
|
| 215 |
-
|
| 216 |
-
@app.route('/dashboard')
|
| 217 |
-
def dashboard():
|
| 218 |
-
products_data = load_products_data()
|
| 219 |
-
kassa_data = load_kassa_data()
|
| 220 |
-
today_start = get_current_time().replace(hour=0, minute=0, second=0, microsecond=0)
|
| 221 |
-
|
| 222 |
-
sales_today = [s for s in kassa_data.get('sales', []) if datetime.fromisoformat(s['timestamp']).astimezone(BISHKEK_TZ) >= today_start]
|
| 223 |
-
|
| 224 |
-
sales_today_count = len(sales_today)
|
| 225 |
-
revenue_today = sum(to_decimal(s['total_selling_price']) for s in sales_today)
|
| 226 |
-
profit_today = sum(to_decimal(s['profit']) for s in sales_today)
|
| 227 |
-
|
| 228 |
-
total_products = len(products_data.get('products', []))
|
| 229 |
-
low_stock_threshold = to_decimal(products_data.get('config', {}).get('low_stock_threshold', '10'))
|
| 230 |
-
low_stock_items = [p for p in products_data.get('products', []) if to_decimal(p.get('quantity', '0')) <= low_stock_threshold]
|
| 231 |
-
low_stock_count = len(low_stock_items)
|
| 232 |
-
|
| 233 |
-
registers = kassa_data.get('registers', [])
|
| 234 |
-
for reg in registers:
|
| 235 |
-
reg['balance_dec'] = to_decimal(reg.get('balance', '0.00'))
|
| 236 |
-
|
| 237 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Панель управления").replace('__CONTENT__', DASHBOARD_CONTENT).replace('__SCRIPTS__', DASHBOARD_SCRIPTS)
|
| 238 |
-
return render_template_string(html,
|
| 239 |
-
sales_today_count=sales_today_count,
|
| 240 |
-
revenue_today=revenue_today,
|
| 241 |
-
profit_today=profit_today,
|
| 242 |
-
total_products=total_products,
|
| 243 |
-
low_stock_count=low_stock_count,
|
| 244 |
-
registers=registers)
|
| 245 |
-
|
| 246 |
-
@app.route('/inventory', methods=['GET', 'POST'])
|
| 247 |
-
def inventory():
|
| 248 |
-
products_data = load_products_data()
|
| 249 |
-
|
| 250 |
-
if request.method == 'POST':
|
| 251 |
-
action = request.form.get('action', 'add')
|
| 252 |
-
try:
|
| 253 |
-
if action == 'add':
|
| 254 |
-
name = request.form.get('name', '').strip()
|
| 255 |
-
barcode = request.form.get('barcode', '').strip()
|
| 256 |
-
category_id = request.form.get('category_id')
|
| 257 |
-
purchase_price = request.form.get('purchase_price', '0')
|
| 258 |
-
selling_price = request.form.get('selling_price', '0')
|
| 259 |
-
quantity = request.form.get('quantity', '0')
|
| 260 |
-
|
| 261 |
-
if not name or not selling_price:
|
| 262 |
-
flash("Название и цена продажи обязательны.", "danger")
|
| 263 |
-
return redirect(url_for('inventory'))
|
| 264 |
-
|
| 265 |
-
if barcode and find_product_by_barcode(barcode):
|
| 266 |
-
flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
|
| 267 |
-
return redirect(url_for('inventory'))
|
| 268 |
-
|
| 269 |
-
new_product = {
|
| 270 |
-
'id': uuid.uuid4().hex,
|
| 271 |
-
'name': name,
|
| 272 |
-
'barcode': barcode or None,
|
| 273 |
-
'category_id': category_id or None,
|
| 274 |
-
'purchase_price': str(to_decimal(purchase_price)),
|
| 275 |
-
'selling_price': str(to_decimal(selling_price)),
|
| 276 |
-
'quantity': str(to_decimal(quantity)),
|
| 277 |
-
'image_filename': None,
|
| 278 |
-
'timestamp_added': get_current_time().isoformat(),
|
| 279 |
-
'timestamp_last_updated': get_current_time().isoformat()
|
| 280 |
-
}
|
| 281 |
-
|
| 282 |
-
if 'image' in request.files:
|
| 283 |
-
file = request.files['image']
|
| 284 |
-
if file and file.filename != '':
|
| 285 |
-
original_filename = secure_filename(file.filename)
|
| 286 |
-
file_ext = original_filename.rsplit('.', 1)[1].lower()
|
| 287 |
-
stored_filename = f"{uuid.uuid4().hex}.{file_ext}"
|
| 288 |
-
file_path = os.path.join(app.config['UPLOAD_FOLDER'], stored_filename)
|
| 289 |
-
file.save(file_path)
|
| 290 |
-
new_product['image_filename'] = stored_filename
|
| 291 |
-
thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'], stored_filename)
|
| 292 |
-
create_thumbnail(file_path, thumb_path)
|
| 293 |
-
|
| 294 |
-
products_data['products'].append(new_product)
|
| 295 |
-
save_products_data(products_data)
|
| 296 |
-
upload_db_to_hf(PRODUCTS_DATA_FILE)
|
| 297 |
-
flash(f"Товар '{name}' успешно добавлен.", "success")
|
| 298 |
-
|
| 299 |
-
elif action == 'edit':
|
| 300 |
-
product_id = request.form.get('product_id')
|
| 301 |
-
product_to_edit = next((p for p in products_data['products'] if p['id'] == product_id), None)
|
| 302 |
-
if not product_to_edit:
|
| 303 |
-
flash("Товар не найден.", "danger")
|
| 304 |
-
return redirect(url_for('inventory'))
|
| 305 |
-
|
| 306 |
-
barcode = request.form.get('barcode', '').strip()
|
| 307 |
-
if barcode and barcode != product_to_edit.get('barcode') and find_product_by_barcode(barcode):
|
| 308 |
-
flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning")
|
| 309 |
-
return redirect(url_for('inventory'))
|
| 310 |
-
|
| 311 |
-
product_to_edit.update({
|
| 312 |
-
'name': request.form.get('name', '').strip(),
|
| 313 |
-
'barcode': barcode or None,
|
| 314 |
-
'category_id': request.form.get('category_id'),
|
| 315 |
-
'purchase_price': str(to_decimal(request.form.get('purchase_price'))),
|
| 316 |
-
'selling_price': str(to_decimal(request.form.get('selling_price'))),
|
| 317 |
-
'quantity': str(to_decimal(request.form.get('quantity'))),
|
| 318 |
-
'timestamp_last_updated': get_current_time().isoformat()
|
| 319 |
-
})
|
| 320 |
-
|
| 321 |
-
if 'image' in request.files:
|
| 322 |
-
file = request.files['image']
|
| 323 |
-
if file and file.filename != '':
|
| 324 |
-
original_filename = secure_filename(file.filename)
|
| 325 |
-
file_ext = original_filename.rsplit('.', 1)[1].lower()
|
| 326 |
-
stored_filename = f"{uuid.uuid4().hex}.{file_ext}"
|
| 327 |
-
file_path = os.path.join(app.config['UPLOAD_FOLDER'], stored_filename)
|
| 328 |
-
file.save(file_path)
|
| 329 |
-
product_to_edit['image_filename'] = stored_filename
|
| 330 |
-
thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'], stored_filename)
|
| 331 |
-
create_thumbnail(file_path, thumb_path)
|
| 332 |
-
|
| 333 |
-
save_products_data(products_data)
|
| 334 |
-
upload_db_to_hf(PRODUCTS_DATA_FILE)
|
| 335 |
-
flash("Данные товара обновлены.", "success")
|
| 336 |
-
|
| 337 |
-
except Exception as e:
|
| 338 |
-
logging.error(f"Ошибка при обработке инвентаря: {e}", exc_info=True)
|
| 339 |
-
flash(f"Произошла ошибка: {e}", "danger")
|
| 340 |
-
|
| 341 |
-
return redirect(url_for('inventory'))
|
| 342 |
-
|
| 343 |
-
products = products_data.get('products', [])
|
| 344 |
-
categories = products_data.get('categories', [])
|
| 345 |
-
category_map = {c['id']: c['name'] for c in categories}
|
| 346 |
-
for p in products:
|
| 347 |
-
p['category_name'] = category_map.get(p.get('category_id'), 'Без категории')
|
| 348 |
-
|
| 349 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Инвентарь").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
|
| 350 |
-
return render_template_string(html, products=products, categories=categories)
|
| 351 |
-
|
| 352 |
-
@app.route('/inventory/delete/<product_id>', methods=['POST'])
|
| 353 |
-
def delete_product(product_id):
|
| 354 |
-
products_data = load_products_data()
|
| 355 |
-
products = products_data.get('products', [])
|
| 356 |
-
products[:] = [p for p in products if p.get('id') != product_id]
|
| 357 |
-
save_products_data(products_data)
|
| 358 |
-
upload_db_to_hf(PRODUCTS_DATA_FILE)
|
| 359 |
-
flash("Товар удален.", "success")
|
| 360 |
-
return redirect(url_for('inventory'))
|
| 361 |
-
|
| 362 |
-
@app.route('/inventory/category', methods=['POST'])
|
| 363 |
-
def handle_category():
|
| 364 |
-
products_data = load_products_data()
|
| 365 |
-
categories = products_data.get('categories', [])
|
| 366 |
-
action = request.form.get('action')
|
| 367 |
-
if action == 'add':
|
| 368 |
-
name = request.form.get('name', '').strip()
|
| 369 |
-
if name and name not in [c['name'] for c in categories]:
|
| 370 |
-
categories.append({'id': uuid.uuid4().hex, 'name': name})
|
| 371 |
-
flash(f"Категория '{name}' добавлена.", "success")
|
| 372 |
-
elif action == 'delete':
|
| 373 |
-
cat_id = request.form.get('category_id')
|
| 374 |
-
categories[:] = [c for c in categories if c.get('id') != cat_id]
|
| 375 |
-
for p in products_data.get('products', []):
|
| 376 |
-
if p.get('category_id') == cat_id:
|
| 377 |
-
p['category_id'] = None
|
| 378 |
-
flash("Категория удалена.", "success")
|
| 379 |
-
|
| 380 |
-
save_products_data(products_data)
|
| 381 |
-
upload_db_to_hf(PRODUCTS_DATA_FILE)
|
| 382 |
-
return redirect(url_for('inventory'))
|
| 383 |
-
|
| 384 |
-
@app.route('/sale')
|
| 385 |
-
def sale():
|
| 386 |
-
products_data = load_products_data()
|
| 387 |
-
kassa_data = load_kassa_data()
|
| 388 |
-
registers = kassa_data.get('registers', [])
|
| 389 |
-
products = products_data.get('products', [])
|
| 390 |
-
if not registers:
|
| 391 |
-
flash("Необходимо создать хотя бы одну кассу для начала продаж.", "warning")
|
| 392 |
-
return redirect(url_for('kassa'))
|
| 393 |
-
|
| 394 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALE_CONTENT).replace('__SCRIPTS__', SALE_SCRIPTS)
|
| 395 |
-
return render_template_string(html, registers=registers, products=products)
|
| 396 |
-
|
| 397 |
-
@app.route('/api/product/<barcode>')
|
| 398 |
-
def api_get_product(barcode):
|
| 399 |
-
product = find_product_by_barcode(barcode)
|
| 400 |
-
if product:
|
| 401 |
-
if to_decimal(product.get('quantity', '0')) > 0:
|
| 402 |
-
return jsonify(product)
|
| 403 |
-
else:
|
| 404 |
-
return jsonify({'error': 'Товар закончился'}), 404
|
| 405 |
-
return jsonify({'error': 'Товар не найден'}), 404
|
| 406 |
-
|
| 407 |
-
@app.route('/api/complete_sale', methods=['POST'])
|
| 408 |
-
def complete_sale():
|
| 409 |
-
data = request.get_json()
|
| 410 |
-
cart = data.get('cart')
|
| 411 |
-
register_id = data.get('register_id')
|
| 412 |
-
payment_method = data.get('payment_method')
|
| 413 |
-
|
| 414 |
-
if not cart or not register_id or not payment_method:
|
| 415 |
-
return jsonify({'error': 'Неполные данные о продаже'}), 400
|
| 416 |
-
|
| 417 |
-
products_data = load_products_data()
|
| 418 |
-
kassa_data = load_kassa_data()
|
| 419 |
-
|
| 420 |
-
total_selling_price = Decimal('0.00')
|
| 421 |
-
total_purchase_price = Decimal('0.00')
|
| 422 |
-
sale_items = []
|
| 423 |
-
|
| 424 |
-
with products_data_lock:
|
| 425 |
-
products_map = {p['id']: p for p in products_data['products']}
|
| 426 |
-
for item_id, item_data in cart.items():
|
| 427 |
-
product = products_map.get(item_id)
|
| 428 |
-
if not product:
|
| 429 |
-
return jsonify({'error': f"Товар с ID {item_id} не найден."}), 400
|
| 430 |
-
|
| 431 |
-
quantity_sold = to_decimal(item_data['quantity'])
|
| 432 |
-
current_stock = to_decimal(product.get('quantity', '0'))
|
| 433 |
-
|
| 434 |
-
if quantity_sold > current_stock:
|
| 435 |
-
return jsonify({'error': f"Недостаточно товара '{product['name']}'. В наличии: {current_stock}"}), 400
|
| 436 |
-
|
| 437 |
-
product['quantity'] = str(current_stock - quantity_sold)
|
| 438 |
-
|
| 439 |
-
purchase_price = to_decimal(product.get('purchase_price', '0'))
|
| 440 |
-
selling_price = to_decimal(product.get('selling_price', '0'))
|
| 441 |
-
|
| 442 |
-
total_selling_price += selling_price * quantity_sold
|
| 443 |
-
total_purchase_price += purchase_price * quantity_sold
|
| 444 |
-
|
| 445 |
-
sale_items.append({
|
| 446 |
-
'product_id': product['id'],
|
| 447 |
-
'name': product['name'],
|
| 448 |
-
'quantity': str(quantity_sold),
|
| 449 |
-
'purchase_price': str(purchase_price),
|
| 450 |
-
'selling_price': str(selling_price)
|
| 451 |
-
})
|
| 452 |
-
|
| 453 |
-
save_products_data(products_data)
|
| 454 |
-
|
| 455 |
-
with kassa_data_lock:
|
| 456 |
-
register = find_register_by_id(register_id)
|
| 457 |
-
if not register:
|
| 458 |
-
return jsonify({'error': f"Касса с ID {register_id} не найдена."}), 400
|
| 459 |
-
|
| 460 |
-
if payment_method == 'cash':
|
| 461 |
-
current_balance = to_decimal(register.get('balance', '0.00'))
|
| 462 |
-
register['balance'] = str(current_balance + total_selling_price)
|
| 463 |
-
|
| 464 |
-
new_sale = {
|
| 465 |
-
'id': uuid.uuid4().hex,
|
| 466 |
-
'register_id': register_id,
|
| 467 |
-
'timestamp': get_current_time().isoformat(),
|
| 468 |
-
'items': sale_items,
|
| 469 |
-
'total_purchase_price': str(total_purchase_price),
|
| 470 |
-
'total_selling_price': str(total_selling_price),
|
| 471 |
-
'profit': str(total_selling_price - total_purchase_price),
|
| 472 |
-
'payment_method': payment_method
|
| 473 |
-
}
|
| 474 |
-
kassa_data['sales'].append(new_sale)
|
| 475 |
-
save_kassa_data(kassa_data)
|
| 476 |
-
|
| 477 |
-
upload_db_to_hf(PRODUCTS_DATA_FILE)
|
| 478 |
-
upload_db_to_hf(KASSA_DATA_FILE)
|
| 479 |
-
|
| 480 |
-
return jsonify({'success': True, 'sale_id': new_sale['id'], 'total': str(total_selling_price)})
|
| 481 |
-
|
| 482 |
-
@app.route('/kassa', methods=['GET', 'POST'])
|
| 483 |
-
def kassa():
|
| 484 |
-
kassa_data = load_kassa_data()
|
| 485 |
-
if request.method == 'POST':
|
| 486 |
-
action = request.form.get('action')
|
| 487 |
-
try:
|
| 488 |
-
if action == 'add_register':
|
| 489 |
-
name = request.form.get('name', '').strip()
|
| 490 |
-
initial_balance = request.form.get('initial_balance', '0')
|
| 491 |
-
if name:
|
| 492 |
-
new_register = {
|
| 493 |
-
'id': uuid.uuid4().hex,
|
| 494 |
-
'name': name,
|
| 495 |
-
'balance': str(to_decimal(initial_balance))
|
| 496 |
-
}
|
| 497 |
-
kassa_data['registers'].append(new_register)
|
| 498 |
-
flash(f"Касса '{name}' создана.", "success")
|
| 499 |
-
else:
|
| 500 |
-
flash("Название кассы не может быть пустым.", "danger")
|
| 501 |
-
|
| 502 |
-
elif action == 'transaction':
|
| 503 |
-
register_id = request.form.get('register_id')
|
| 504 |
-
trans_type = request.form.get('type')
|
| 505 |
-
amount = to_decimal(request.form.get('amount', '0'))
|
| 506 |
-
description = request.form.get('description', '').strip()
|
| 507 |
-
|
| 508 |
-
register = find_register_by_id(register_id)
|
| 509 |
-
if register and amount > 0:
|
| 510 |
-
current_balance = to_decimal(register.get('balance', '0.00'))
|
| 511 |
-
if trans_type == 'income':
|
| 512 |
-
register['balance'] = str(current_balance + amount)
|
| 513 |
-
elif trans_type == 'expense':
|
| 514 |
-
if amount > current_balance:
|
| 515 |
-
flash("Сумма изъятия превышает баланс кассы.", "danger")
|
| 516 |
-
return redirect(url_for('kassa'))
|
| 517 |
-
register['balance'] = str(current_balance - amount)
|
| 518 |
-
|
| 519 |
-
new_transaction = {
|
| 520 |
-
'id': uuid.uuid4().hex,
|
| 521 |
-
'register_id': register_id,
|
| 522 |
-
'timestamp': get_current_time().isoformat(),
|
| 523 |
-
'type': trans_type,
|
| 524 |
-
'amount': str(amount),
|
| 525 |
-
'description': description
|
| 526 |
-
}
|
| 527 |
-
kassa_data['transactions'].append(new_transaction)
|
| 528 |
-
flash("Транзакция успешно проведена.", "success")
|
| 529 |
-
else:
|
| 530 |
-
flash("Ошибка транзакции. Проверьте данные.", "danger")
|
| 531 |
-
|
| 532 |
-
save_kassa_data(kassa_data)
|
| 533 |
-
upload_db_to_hf(KASSA_DATA_FILE)
|
| 534 |
-
except Exception as e:
|
| 535 |
-
logging.error(f"Ошибка при управлении кассой: {e}", exc_info=True)
|
| 536 |
-
flash(f"Произошла ошибка: {e}", "danger")
|
| 537 |
-
|
| 538 |
-
return redirect(url_for('kassa'))
|
| 539 |
-
|
| 540 |
-
registers = kassa_data.get('registers', [])
|
| 541 |
-
transactions = sorted(kassa_data.get('transactions', []), key=lambda x: x.get('timestamp', ''), reverse=True)
|
| 542 |
-
register_map = {r['id']: r['name'] for r in registers}
|
| 543 |
-
for t in transactions:
|
| 544 |
-
t['register_name'] = register_map.get(t.get('register_id'), 'N/A')
|
| 545 |
-
|
| 546 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Управление кассами").replace('__CONTENT__', KASSA_CONTENT).replace('__SCRIPTS__', KASSA_SCRIPTS)
|
| 547 |
-
return render_template_string(html, registers=registers, transactions=transactions)
|
| 548 |
-
|
| 549 |
-
@app.route('/reports')
|
| 550 |
-
def reports():
|
| 551 |
-
kassa_data = load_kassa_data()
|
| 552 |
-
products_data = load_products_data()
|
| 553 |
-
now = get_current_time()
|
| 554 |
-
|
| 555 |
-
filter_type = request.args.get('filter', 'month')
|
| 556 |
-
start_date_str = request.args.get('start_date')
|
| 557 |
-
end_date_str = request.args.get('end_date')
|
| 558 |
-
|
| 559 |
-
try:
|
| 560 |
-
if filter_type == 'custom' and start_date_str and end_date_str:
|
| 561 |
-
sd = datetime.strptime(start_date_str, '%Y-%m-%d')
|
| 562 |
-
ed = datetime.strptime(end_date_str, '%Y-%m-%d')
|
| 563 |
-
start_date_dt = BISHKEK_TZ.localize(sd.replace(hour=0, minute=0, second=0))
|
| 564 |
-
end_date_dt = BISHKEK_TZ.localize(ed.replace(hour=23, minute=59, second=59))
|
| 565 |
-
elif filter_type == 'day':
|
| 566 |
-
start_date_dt = now.replace(hour=0, minute=0, second=0)
|
| 567 |
-
end_date_dt = now.replace(hour=23, minute=59, second=59)
|
| 568 |
-
else: # month
|
| 569 |
-
start_date_dt = now.replace(day=1, hour=0, minute=0, second=0)
|
| 570 |
-
end_date_dt = (start_date_dt + timedelta(days=32)).replace(day=1) - timedelta(seconds=1)
|
| 571 |
-
|
| 572 |
-
except (ValueError, TypeError):
|
| 573 |
-
start_date_dt = now.replace(day=1, hour=0, minute=0, second=0)
|
| 574 |
-
end_date_dt = (start_date_dt + timedelta(days=32)).replace(day=1) - timedelta(seconds=1)
|
| 575 |
-
flash("Неверный формат даты, показан отчет за текущий месяц.", "warning")
|
| 576 |
-
|
| 577 |
-
all_sales = kassa_data.get('sales', [])
|
| 578 |
-
filtered_sales = [s for s in all_sales if start_date_dt <= datetime.fromisoformat(s['timestamp']).astimezone(BISHKEK_TZ) <= end_date_dt]
|
| 579 |
-
|
| 580 |
-
total_revenue = sum(to_decimal(s['total_selling_price']) for s in filtered_sales)
|
| 581 |
-
total_profit = sum(to_decimal(s['profit']) for s in filtered_sales)
|
| 582 |
-
total_cost = total_revenue - total_profit
|
| 583 |
-
|
| 584 |
-
product_summary = {}
|
| 585 |
-
for sale in filtered_sales:
|
| 586 |
-
for item in sale['items']:
|
| 587 |
-
pid = item['product_id']
|
| 588 |
-
if pid not in product_summary:
|
| 589 |
-
product_summary[pid] = {'name': item['name'], 'quantity': Decimal('0'), 'revenue': Decimal('0'), 'profit': Decimal('0')}
|
| 590 |
-
|
| 591 |
-
qty = to_decimal(item['quantity'])
|
| 592 |
-
revenue = to_decimal(item['selling_price']) * qty
|
| 593 |
-
profit = (to_decimal(item['selling_price']) - to_decimal(item['purchase_price'])) * qty
|
| 594 |
-
|
| 595 |
-
product_summary[pid]['quantity'] += qty
|
| 596 |
-
product_summary[pid]['revenue'] += revenue
|
| 597 |
-
product_summary[pid]['profit'] += profit
|
| 598 |
-
|
| 599 |
-
sorted_product_summary = sorted(product_summary.values(), key=lambda x: x['revenue'], reverse=True)
|
| 600 |
-
|
| 601 |
-
report_data = {
|
| 602 |
-
'total_sales': len(filtered_sales),
|
| 603 |
-
'total_revenue': total_revenue,
|
| 604 |
-
'total_profit': total_profit,
|
| 605 |
-
'total_cost': total_cost,
|
| 606 |
-
'product_summary': sorted_product_summary,
|
| 607 |
-
'start_date': start_date_dt.strftime('%Y-%m-%d'),
|
| 608 |
-
'end_date': end_date_dt.strftime('%Y-%m-%d'),
|
| 609 |
-
'filter_type': filter_type,
|
| 610 |
-
}
|
| 611 |
-
|
| 612 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
|
| 613 |
-
return render_template_string(html, report=report_data)
|
| 614 |
-
|
| 615 |
-
@app.route('/backup', methods=['POST'])
|
| 616 |
-
def backup_hf():
|
| 617 |
-
try:
|
| 618 |
-
logging.info("Manual backup to Hugging Face initiated...")
|
| 619 |
-
upload_db_to_hf(PRODUCTS_DATA_FILE)
|
| 620 |
-
upload_db_to_hf(KASSA_DATA_FILE)
|
| 621 |
-
flash(f"Backup to Hugging Face initiated.", "success")
|
| 622 |
-
except Exception as e:
|
| 623 |
-
flash(f"An error occurred during backup: {e}", "danger")
|
| 624 |
-
return redirect(url_for('dashboard'))
|
| 625 |
-
|
| 626 |
-
@app.route('/download', methods=['GET'])
|
| 627 |
-
def download_hf():
|
| 628 |
-
try:
|
| 629 |
-
logging.info("Starting data download from Hugging Face...")
|
| 630 |
-
load_products_data()
|
| 631 |
-
load_kassa_data()
|
| 632 |
-
flash(f"Files downloaded successfully and reloaded.", "success")
|
| 633 |
-
except Exception as e:
|
| 634 |
-
flash(f"An error occurred during download: {e}", "danger")
|
| 635 |
-
return redirect(url_for('dashboard'))
|
| 636 |
-
|
| 637 |
-
@app.route('/thumbnail/<filename>')
|
| 638 |
-
def get_thumbnail(filename):
|
| 639 |
-
try:
|
| 640 |
-
return send_from_directory(app.config['THUMBNAIL_FOLDER'], filename)
|
| 641 |
-
except FileNotFoundError:
|
| 642 |
-
return "", 404
|
| 643 |
-
|
| 644 |
-
DASHBOARD_CONTENT = """
|
| 645 |
-
<div class="row">
|
| 646 |
-
<div class="col-lg-3 col-md-6 mb-4">
|
| 647 |
-
<div class="card h-100 border-start border-5 border-primary">
|
| 648 |
-
<div class="card-body">
|
| 649 |
-
<h6 class="card-subtitle mb-2 text-body-secondary">Продаж сегодня</h6>
|
| 650 |
-
<p class="card-text display-5 fw-bold">{{ sales_today_count }}</p>
|
| 651 |
-
</div>
|
| 652 |
-
</div>
|
| 653 |
-
</div>
|
| 654 |
-
<div class="col-lg-3 col-md-6 mb-4">
|
| 655 |
-
<div class="card h-100 border-start border-5 border-success">
|
| 656 |
-
<div class="card-body">
|
| 657 |
-
<h6 class="card-subtitle mb-2 text-body-secondary">Выручка сегодня</h6>
|
| 658 |
-
<p class="card-text display-5 fw-bold">{{ format_currency_py(revenue_today) }}</p>
|
| 659 |
-
</div>
|
| 660 |
-
</div>
|
| 661 |
-
</div>
|
| 662 |
-
<div class="col-lg-3 col-md-6 mb-4">
|
| 663 |
-
<div class="card h-100 border-start border-5 border-info">
|
| 664 |
-
<div class="card-body">
|
| 665 |
-
<h6 class="card-subtitle mb-2 text-body-secondary">Прибыль сегодня</h6>
|
| 666 |
-
<p class="card-text display-5 fw-bold">{{ format_currency_py(profit_today) }}</p>
|
| 667 |
-
</div>
|
| 668 |
-
</div>
|
| 669 |
-
</div>
|
| 670 |
-
<div class="col-lg-3 col-md-6 mb-4">
|
| 671 |
-
<div class="card h-100 border-start border-5 border-danger">
|
| 672 |
-
<div class="card-body">
|
| 673 |
-
<h6 class="card-subtitle mb-2 text-body-secondary">Мало товара</h6>
|
| 674 |
-
<p class="card-text display-5 fw-bold">{{ low_stock_count }}</p>
|
| 675 |
-
</div>
|
| 676 |
-
</div>
|
| 677 |
-
</div>
|
| 678 |
-
</div>
|
| 679 |
-
<div class="row">
|
| 680 |
-
<div class="col-12">
|
| 681 |
-
<div class="card">
|
| 682 |
-
<div class="card-header"><h5 class="mb-0"><i class="fas fa-cash-register me-2"></i>Баланс касс</h5></div>
|
| 683 |
-
<div class="card-body">
|
| 684 |
-
{% if registers %}
|
| 685 |
-
<div class="table-responsive">
|
| 686 |
-
<table class="table">
|
| 687 |
-
<thead><tr><th>Название кассы</th><th class="text-end">Баланс</th></tr></thead>
|
| 688 |
-
<tbody>
|
| 689 |
-
{% for register in registers %}
|
| 690 |
-
<tr>
|
| 691 |
-
<td>{{ register.name }}</td>
|
| 692 |
-
<td class="text-end fw-bold fs-5">{{ format_currency_py(register.balance_dec) }} сом</td>
|
| 693 |
-
</tr>
|
| 694 |
-
{% endfor %}
|
| 695 |
-
</tbody>
|
| 696 |
-
</table>
|
| 697 |
-
</div>
|
| 698 |
-
{% else %}
|
| 699 |
-
<p class="text-center text-body-secondary py-3">Нет созданных касс.</p>
|
| 700 |
-
{% endif %}
|
| 701 |
-
</div>
|
| 702 |
-
</div>
|
| 703 |
-
</div>
|
| 704 |
-
</div>
|
| 705 |
-
"""
|
| 706 |
-
DASHBOARD_SCRIPTS = ""
|
| 707 |
-
|
| 708 |
-
INVENTORY_CONTENT = """
|
| 709 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 710 |
-
<h1 class="h2">Инвентарь</h1>
|
| 711 |
-
<div>
|
| 712 |
-
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus me-2"></i>Добавить товар</button>
|
| 713 |
-
<button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#categoryModal"><i class="fas fa-tags me-2"></i>Категории</button>
|
| 714 |
-
</div>
|
| 715 |
-
</div>
|
| 716 |
-
<div class="card">
|
| 717 |
-
<div class="card-body">
|
| 718 |
-
<input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию, штрих-коду, категории...">
|
| 719 |
-
<div class="table-responsive">
|
| 720 |
-
<table class="table table-hover table-bordered" id="products-table">
|
| 721 |
-
<thead class="table-light">
|
| 722 |
-
<tr>
|
| 723 |
-
<th>Товар</th>
|
| 724 |
-
<th>Категория</th>
|
| 725 |
-
<th>Штрих-код</th>
|
| 726 |
-
<th class="text-end">Кол-во</th>
|
| 727 |
-
<th class="text-end">Цена закупки</th>
|
| 728 |
-
<th class="text-end">Цена продажи</th>
|
| 729 |
-
<th class="text-center">Действия</th>
|
| 730 |
-
</tr>
|
| 731 |
-
</thead>
|
| 732 |
-
<tbody>
|
| 733 |
-
{% for product in products %}
|
| 734 |
-
<tr class="product-row" data-search="{{ product.name|lower }} {{ product.barcode|default('') }} {{ product.category_name|lower }}">
|
| 735 |
-
<td>
|
| 736 |
-
{% if product.image_filename %}
|
| 737 |
-
<img src="{{ url_for('get_thumbnail', filename=product.image_filename) }}" class="rounded me-2" style="width: 40px; height: 40px; object-fit: cover;">
|
| 738 |
-
{% endif %}
|
| 739 |
-
<strong>{{ product.name }}</strong>
|
| 740 |
-
</td>
|
| 741 |
-
<td>{{ product.category_name }}</td>
|
| 742 |
-
<td>{{ product.barcode or '—' }}</td>
|
| 743 |
-
<td class="text-end">{{ format_integer_py(product.quantity) }}</td>
|
| 744 |
-
<td class="text-end">{{ format_currency_py(product.purchase_price) }}</td>
|
| 745 |
-
<td class="text-end">{{ format_currency_py(product.selling_price) }}</td>
|
| 746 |
-
<td class="text-center">
|
| 747 |
-
<button class="btn btn-sm btn-outline-primary" onclick="openEditModal({{ product|tojson|safe }})"><i class="fas fa-edit"></i></button>
|
| 748 |
-
<form action="{{ url_for('delete_product', product_id=product.id) }}" method="POST" class="d-inline" onsubmit="return confirm('Удалить товар?');">
|
| 749 |
-
<button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
|
| 750 |
-
</form>
|
| 751 |
-
</td>
|
| 752 |
-
</tr>
|
| 753 |
-
{% endfor %}
|
| 754 |
-
<tr class="no-result-row" style="display: none;"><td colspan="7" class="text-center text-body-secondary py-4"></td></tr>
|
| 755 |
-
</tbody>
|
| 756 |
-
</table>
|
| 757 |
-
</div>
|
| 758 |
-
</div>
|
| 759 |
-
</div>
|
| 760 |
-
|
| 761 |
-
<!-- Add/Edit Product Modal -->
|
| 762 |
-
<div class="modal fade" id="addProductModal" tabindex="-1">
|
| 763 |
-
<div class="modal-dialog modal-lg">
|
| 764 |
-
<div class="modal-content">
|
| 765 |
-
<form method="POST" action="{{ url_for('inventory') }}" enctype="multipart/form-data">
|
| 766 |
-
<div class="modal-header">
|
| 767 |
-
<h5 class="modal-title" id="productModalLabel">Добавить товар</h5>
|
| 768 |
-
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
| 769 |
-
</div>
|
| 770 |
-
<div class="modal-body">
|
| 771 |
-
<input type="hidden" name="action" id="product_action" value="add">
|
| 772 |
-
<input type="hidden" name="product_id" id="product_id">
|
| 773 |
-
<div class="row">
|
| 774 |
-
<div class="col-md-8">
|
| 775 |
-
<div class="mb-3">
|
| 776 |
-
<label class="form-label">Название товара *</label>
|
| 777 |
-
<input type="text" name="name" id="product_name" class="form-control" required>
|
| 778 |
-
</div>
|
| 779 |
-
<div class="row">
|
| 780 |
-
<div class="col-md-6 mb-3">
|
| 781 |
-
<label class="form-label">Штрих-код</label>
|
| 782 |
-
<div class="input-group">
|
| 783 |
-
<input type="text" name="barcode" id="product_barcode" class="form-control">
|
| 784 |
-
<button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('product_barcode').focus();"><i class="fas fa-barcode"></i></button>
|
| 785 |
-
</div>
|
| 786 |
-
</div>
|
| 787 |
-
<div class="col-md-6 mb-3">
|
| 788 |
-
<label class="form-label">Категория</label>
|
| 789 |
-
<select name="category_id" id="product_category" class="form-select">
|
| 790 |
-
<option value="">Без категории</option>
|
| 791 |
-
{% for cat in categories %}
|
| 792 |
-
<option value="{{ cat.id }}">{{ cat.name }}</option>
|
| 793 |
-
{% endfor %}
|
| 794 |
-
</select>
|
| 795 |
-
</div>
|
| 796 |
-
</div>
|
| 797 |
-
<div class="row">
|
| 798 |
-
<div class="col-md-4 mb-3">
|
| 799 |
-
<label class="form-label">Цена закупки</label>
|
| 800 |
-
<input type="text" name="purchase_price" id="product_purchase_price" class="form-control" inputmode="decimal">
|
| 801 |
-
</div>
|
| 802 |
-
<div class="col-md-4 mb-3">
|
| 803 |
-
<label class="form-label">Цена продажи *</label>
|
| 804 |
-
<input type="text" name="selling_price" id="product_selling_price" class="form-control" inputmode="decimal" required>
|
| 805 |
-
</div>
|
| 806 |
-
<div class="col-md-4 mb-3">
|
| 807 |
-
<label class="form-label">Количество</label>
|
| 808 |
-
<input type="text" name="quantity" id="product_quantity" class="form-control" inputmode="decimal">
|
| 809 |
-
</div>
|
| 810 |
-
</div>
|
| 811 |
-
</div>
|
| 812 |
-
<div class="col-md-4">
|
| 813 |
-
<label class="form-label">Изображение</label>
|
| 814 |
-
<input type="file" name="image" class="form-control" accept="image/*">
|
| 815 |
-
<img id="product_image_preview" src="" class="img-thumbnail mt-2" style="display:none; max-height: 150px;">
|
| 816 |
-
</div>
|
| 817 |
-
</div>
|
| 818 |
-
</div>
|
| 819 |
-
<div class="modal-footer">
|
| 820 |
-
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
| 821 |
-
<button type="submit" class="btn btn-primary">Сохранить</button>
|
| 822 |
-
</div>
|
| 823 |
-
</form>
|
| 824 |
-
</div>
|
| 825 |
-
</div>
|
| 826 |
-
</div>
|
| 827 |
-
|
| 828 |
-
<!-- Category Modal -->
|
| 829 |
-
<div class="modal fade" id="categoryModal" tabindex="-1">
|
| 830 |
-
<div class="modal-dialog">
|
| 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 |
-
<div class="modal-body">
|
| 837 |
-
<form action="{{ url_for('handle_category') }}" method="POST" class="input-group mb-3">
|
| 838 |
-
<input type="hidden" name="action" value="add">
|
| 839 |
-
<input type="text" name="name" class="form-control" placeholder="Новая категория" required>
|
| 840 |
-
<button class="btn btn-outline-primary" type="submit">Добавить</button>
|
| 841 |
-
</form>
|
| 842 |
-
<hr>
|
| 843 |
-
<h6>Существующие категории:</h6>
|
| 844 |
-
<ul class="list-group">
|
| 845 |
-
{% for cat in categories %}
|
| 846 |
-
<li class="list-group-item d-flex justify-content-between align-items-center">
|
| 847 |
-
{{ cat.name }}
|
| 848 |
-
<form action="{{ url_for('handle_category') }}" method="POST" onsubmit="return confirm('Удалить категорию? Товары останутся без категории.');">
|
| 849 |
-
<input type="hidden" name="action" value="delete">
|
| 850 |
-
<input type="hidden" name="category_id" value="{{ cat.id }}">
|
| 851 |
-
<button type="submit" class="btn-close"></button>
|
| 852 |
-
</form>
|
| 853 |
-
</li>
|
| 854 |
-
{% else %}
|
| 855 |
-
<li class="list-group-item text-body-secondary">Категорий нет.</li>
|
| 856 |
-
{% endfor %}
|
| 857 |
-
</ul>
|
| 858 |
-
</div>
|
| 859 |
-
</div>
|
| 860 |
-
</div>
|
| 861 |
-
</div>
|
| 862 |
-
"""
|
| 863 |
-
INVENTORY_SCRIPTS = """
|
| 864 |
-
<script>
|
| 865 |
-
document.addEventListener('DOMContentLoaded', function () {
|
| 866 |
-
const searchInput = document.getElementById('product-search');
|
| 867 |
-
const tableBody = document.getElementById('products-table')?.querySelector('tbody');
|
| 868 |
-
if (searchInput && tableBody) {
|
| 869 |
-
searchInput.addEventListener('input', function() {
|
| 870 |
-
const searchTerm = searchInput.value.toLowerCase().trim();
|
| 871 |
-
const rows = tableBody.querySelectorAll('tr.product-row');
|
| 872 |
-
const noResultRow = tableBody.querySelector('.no-result-row');
|
| 873 |
-
let found = false;
|
| 874 |
-
rows.forEach(row => {
|
| 875 |
-
if ((row.dataset.search || '').includes(searchTerm)) {
|
| 876 |
-
row.style.display = ''; found = true;
|
| 877 |
-
} else { row.style.display = 'none'; }
|
| 878 |
-
});
|
| 879 |
-
if (noResultRow) {
|
| 880 |
-
if (!found && searchTerm) {
|
| 881 |
-
noResultRow.querySelector('td').textContent = `Товары не найдены по запросу "${searchTerm}".`;
|
| 882 |
-
noResultRow.style.display = '';
|
| 883 |
-
} else { noResultRow.style.display = 'none'; }
|
| 884 |
-
}
|
| 885 |
-
});
|
| 886 |
-
}
|
| 887 |
-
});
|
| 888 |
-
|
| 889 |
-
const productModal = new bootstrap.Modal(document.getElementById('addProductModal'));
|
| 890 |
-
const modalLabel = document.getElementById('productModalLabel');
|
| 891 |
-
const form = document.querySelector('#addProductModal form');
|
| 892 |
-
|
| 893 |
-
document.getElementById('addProductModal').addEventListener('hidden.bs.modal', function() {
|
| 894 |
-
form.reset();
|
| 895 |
-
document.getElementById('product_action').value = 'add';
|
| 896 |
-
document.getElementById('product_id').value = '';
|
| 897 |
-
modalLabel.textContent = 'Добавить товар';
|
| 898 |
-
document.getElementById('product_image_preview').style.display = 'none';
|
| 899 |
-
document.getElementById('product_image_preview').src = '';
|
| 900 |
-
});
|
| 901 |
-
|
| 902 |
-
function openEditModal(product) {
|
| 903 |
-
modalLabel.textContent = 'Редактировать товар';
|
| 904 |
-
document.getElementById('product_action').value = 'edit';
|
| 905 |
-
document.getElementById('product_id').value = product.id;
|
| 906 |
-
document.getElementById('product_name').value = product.name;
|
| 907 |
-
document.getElementById('product_barcode').value = product.barcode || '';
|
| 908 |
-
document.getElementById('product_category').value = product.category_id || '';
|
| 909 |
-
document.getElementById('product_purchase_price').value = String(product.purchase_price).replace('.', ',');
|
| 910 |
-
document.getElementById('product_selling_price').value = String(product.selling_price).replace('.', ',');
|
| 911 |
-
document.getElementById('product_quantity').value = String(product.quantity).replace('.', ',');
|
| 912 |
-
if(product.image_filename) {
|
| 913 |
-
document.getElementById('product_image_preview').src = `/thumbnail/${product.image_filename}`;
|
| 914 |
-
document.getElementById('product_image_preview').style.display = 'block';
|
| 915 |
-
}
|
| 916 |
-
productModal.show();
|
| 917 |
-
}
|
| 918 |
-
</script>
|
| 919 |
-
"""
|
| 920 |
-
|
| 921 |
-
SALE_CONTENT = """
|
| 922 |
-
<div class="row">
|
| 923 |
-
<div class="col-lg-7 col-xl-8 mb-4">
|
| 924 |
-
<div class="card">
|
| 925 |
-
<div class="card-body">
|
| 926 |
-
<div class="input-group mb-3">
|
| 927 |
-
<span class="input-group-text"><i class="fas fa-barcode"></i></span>
|
| 928 |
-
<input type="text" id="barcode-scanner" class="form-control form-control-lg" placeholder="Сканируйте штрих-код или начните вводить название..." autofocus>
|
| 929 |
-
</div>
|
| 930 |
-
<div class="table-responsive" style="min-height: 400px; max-height:60vh;">
|
| 931 |
-
<table class="table" id="sale-cart-table">
|
| 932 |
-
<thead class="table-light"><tr><th>Товар</th><th class="text-center">Количество</th><th class="text-end">Цена</th><th class="text-end">Сумма</th><th></th></tr></thead>
|
| 933 |
-
<tbody>
|
| 934 |
-
<tr id="cart-empty-row"><td colspan="5" class="text-center text-body-secondary py-5">Корзина пуста</td></tr>
|
| 935 |
-
</tbody>
|
| 936 |
-
</table>
|
| 937 |
-
</div>
|
| 938 |
-
</div>
|
| 939 |
-
</div>
|
| 940 |
-
</div>
|
| 941 |
-
<div class="col-lg-5 col-xl-4">
|
| 942 |
-
<div class="card sticky-top" style="top: 80px;">
|
| 943 |
-
<div class="card-body">
|
| 944 |
-
<div class="mb-3">
|
| 945 |
-
<label class="form-label">Текущая касса</label>
|
| 946 |
-
<select id="register-select" class="form-select">
|
| 947 |
-
{% for register in registers %}
|
| 948 |
-
<option value="{{ register.id }}">{{ register.name }}</option>
|
| 949 |
-
{% endfor %}
|
| 950 |
-
</select>
|
| 951 |
-
</div>
|
| 952 |
-
<hr>
|
| 953 |
-
<div class="d-flex justify-content-between align-items-center mb-3">
|
| 954 |
-
<h5 class="mb-0">Итого:</h5>
|
| 955 |
-
<h4 class="mb-0 fw-bold" id="cart-total">0,00 сом</h4>
|
| 956 |
-
</div>
|
| 957 |
-
<div class="d-grid gap-2">
|
| 958 |
-
<button id="pay-cash-btn" class="btn btn-success btn-lg" disabled><i class="fas fa-money-bill-wave me-2"></i>Наличные</button>
|
| 959 |
-
<button id="pay-card-btn" class="btn btn-primary btn-lg" disabled><i class="far fa-credit-card me-2"></i>Карта</button>
|
| 960 |
-
<button id="clear-cart-btn" class="btn btn-outline-danger mt-2">Очистить корзину</button>
|
| 961 |
-
</div>
|
| 962 |
-
</div>
|
| 963 |
-
</div>
|
| 964 |
-
</div>
|
| 965 |
-
</div>
|
| 966 |
-
|
| 967 |
-
<!-- Cash Payment Modal -->
|
| 968 |
-
<div class="modal fade" id="cashPaymentModal" tabindex="-1">
|
| 969 |
-
<div class="modal-dialog">
|
| 970 |
-
<div class="modal-content">
|
| 971 |
-
<div class="modal-header"><h5 class="modal-title">Оплата наличными</h5></div>
|
| 972 |
-
<div class="modal-body">
|
| 973 |
-
<p class="fs-5">К оплате: <strong id="cash-total-due">0,00 сом</strong></p>
|
| 974 |
-
<div class="mb-3">
|
| 975 |
-
<label for="cash-received" class="form-label">Получено от клиента</label>
|
| 976 |
-
<input type="text" id="cash-received" class="form-control form-control-lg" inputmode="decimal">
|
| 977 |
-
</div>
|
| 978 |
-
<p class="fs-5">Сдача: <strong id="cash-change" class="text-danger">0,00 сом</strong></p>
|
| 979 |
-
</div>
|
| 980 |
-
<div class="modal-footer">
|
| 981 |
-
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
| 982 |
-
<button type="button" id="confirm-cash-payment" class="btn btn-success" disabled>Подтвердить</button>
|
| 983 |
-
</div>
|
| 984 |
-
</div>
|
| 985 |
-
</div>
|
| 986 |
-
</div>
|
| 987 |
-
"""
|
| 988 |
-
SALE_SCRIPTS = """
|
| 989 |
-
<script>
|
| 990 |
-
let cart = {};
|
| 991 |
-
let totalDue = 0;
|
| 992 |
-
|
| 993 |
-
document.addEventListener('DOMContentLoaded', () => {
|
| 994 |
-
const barcodeScanner = document.getElementById('barcode-scanner');
|
| 995 |
-
const clearCartBtn = document.getElementById('clear-cart-btn');
|
| 996 |
-
const payCashBtn = document.getElementById('pay-cash-btn');
|
| 997 |
-
const payCardBtn = document.getElementById('pay-card-btn');
|
| 998 |
-
const cashModal = new bootstrap.Modal(document.getElementById('cashPaymentModal'));
|
| 999 |
-
|
| 1000 |
-
barcodeScanner.addEventListener('keypress', e => {
|
| 1001 |
-
if (e.key === 'Enter' && e.target.value) {
|
| 1002 |
-
e.preventDefault();
|
| 1003 |
-
addProductByBarcode(e.target.value);
|
| 1004 |
-
e.target.value = '';
|
| 1005 |
-
}
|
| 1006 |
-
});
|
| 1007 |
-
|
| 1008 |
-
clearCartBtn.addEventListener('click', clearCart);
|
| 1009 |
-
payCashBtn.addEventListener('click', () => {
|
| 1010 |
-
document.getElementById('cash-total-due').textContent = formatCurrencyJS(totalDue) + ' сом';
|
| 1011 |
-
document.getElementById('cash-received').value = '';
|
| 1012 |
-
document.getElementById('cash-change').textContent = '0,00 сом';
|
| 1013 |
-
document.getElementById('confirm-cash-payment').disabled = true;
|
| 1014 |
-
cashModal.show();
|
| 1015 |
-
});
|
| 1016 |
-
payCardBtn.addEventListener('click', () => completeSale('card'));
|
| 1017 |
-
|
| 1018 |
-
document.getElementById('cash-received').addEventListener('input', calculateChange);
|
| 1019 |
-
document.getElementById('confirm-cash-payment').addEventListener('click', () => completeSale('cash'));
|
| 1020 |
-
});
|
| 1021 |
-
|
| 1022 |
-
function addProductByBarcode(barcode) {
|
| 1023 |
-
fetch(`/api/product/${barcode}`)
|
| 1024 |
-
.then(response => {
|
| 1025 |
-
if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
|
| 1026 |
-
return response.json();
|
| 1027 |
-
})
|
| 1028 |
-
.then(product => {
|
| 1029 |
-
if (product.error) {
|
| 1030 |
-
flashMessage(product.error, 'danger');
|
| 1031 |
-
} else {
|
| 1032 |
-
addProductToCart(product);
|
| 1033 |
-
}
|
| 1034 |
-
})
|
| 1035 |
-
.catch(error => {
|
| 1036 |
-
flashMessage(`Товар со штрих-кодом ${barcode} не найден`, 'warning');
|
| 1037 |
-
});
|
| 1038 |
-
}
|
| 1039 |
-
|
| 1040 |
-
function addProductToCart(product) {
|
| 1041 |
-
if (cart[product.id]) {
|
| 1042 |
-
cart[product.id].quantity += 1;
|
| 1043 |
-
} else {
|
| 1044 |
-
cart[product.id] = {
|
| 1045 |
-
name: product.name,
|
| 1046 |
-
price: parseFloat(product.selling_price),
|
| 1047 |
-
quantity: 1
|
| 1048 |
-
};
|
| 1049 |
-
}
|
| 1050 |
-
updateCartDisplay();
|
| 1051 |
-
}
|
| 1052 |
-
|
| 1053 |
-
function updateCartDisplay() {
|
| 1054 |
-
const cartTableBody = document.querySelector('#sale-cart-table tbody');
|
| 1055 |
-
cartTableBody.innerHTML = '';
|
| 1056 |
-
let currentTotal = 0;
|
| 1057 |
-
|
| 1058 |
-
if (Object.keys(cart).length === 0) {
|
| 1059 |
-
cartTableBody.innerHTML = '<tr id="cart-empty-row"><td colspan="5" class="text-center text-body-secondary py-5">Корзина пуста</td></tr>';
|
| 1060 |
-
document.getElementById('pay-cash-btn').disabled = true;
|
| 1061 |
-
document.getElementById('pay-card-btn').disabled = true;
|
| 1062 |
-
} else {
|
| 1063 |
-
document.getElementById('pay-cash-btn').disabled = false;
|
| 1064 |
-
document.getElementById('pay-card-btn').disabled = false;
|
| 1065 |
-
}
|
| 1066 |
-
|
| 1067 |
-
for (const id in cart) {
|
| 1068 |
-
const item = cart[id];
|
| 1069 |
-
const itemTotal = item.price * item.quantity;
|
| 1070 |
-
currentTotal += itemTotal;
|
| 1071 |
-
const row = document.createElement('tr');
|
| 1072 |
-
row.innerHTML = `
|
| 1073 |
-
<td>${item.name}</td>
|
| 1074 |
-
<td class="text-center" style="width: 150px;">
|
| 1075 |
-
<div class="input-group input-group-sm">
|
| 1076 |
-
<button class="btn btn-outline-secondary" onclick="changeQuantity('${id}', -1)">-</button>
|
| 1077 |
-
<input type="number" class="form-control text-center" value="${item.quantity}" onchange="setQuantity('${id}', this.value)">
|
| 1078 |
-
<button class="btn btn-outline-secondary" onclick="changeQuantity('${id}', 1)">+</button>
|
| 1079 |
-
</div>
|
| 1080 |
-
</td>
|
| 1081 |
-
<td class="text-end">${formatCurrencyJS(item.price)}</td>
|
| 1082 |
-
<td class="text-end fw-bold">${formatCurrencyJS(itemTotal)}</td>
|
| 1083 |
-
<td class="text-center"><button class="btn btn-sm btn-outline-danger" onclick="removeFromCart('${id}')"><i class="fas fa-trash"></i></button></td>
|
| 1084 |
-
`;
|
| 1085 |
-
cartTableBody.appendChild(row);
|
| 1086 |
-
}
|
| 1087 |
-
|
| 1088 |
-
totalDue = currentTotal;
|
| 1089 |
-
document.getElementById('cart-total').textContent = formatCurrencyJS(currentTotal) + ' сом';
|
| 1090 |
-
}
|
| 1091 |
-
|
| 1092 |
-
function changeQuantity(id, delta) {
|
| 1093 |
-
if (cart[id]) {
|
| 1094 |
-
cart[id].quantity += delta;
|
| 1095 |
-
if (cart[id].quantity <= 0) {
|
| 1096 |
-
delete cart[id];
|
| 1097 |
-
}
|
| 1098 |
-
updateCartDisplay();
|
| 1099 |
-
}
|
| 1100 |
-
}
|
| 1101 |
-
|
| 1102 |
-
function setQuantity(id, newQuantity) {
|
| 1103 |
-
const qty = parseInt(newQuantity);
|
| 1104 |
-
if (cart[id]) {
|
| 1105 |
-
if (qty > 0) {
|
| 1106 |
-
cart[id].quantity = qty;
|
| 1107 |
-
} else {
|
| 1108 |
-
delete cart[id];
|
| 1109 |
-
}
|
| 1110 |
-
updateCartDisplay();
|
| 1111 |
-
}
|
| 1112 |
-
}
|
| 1113 |
-
|
| 1114 |
-
function removeFromCart(id) {
|
| 1115 |
-
if (cart[id]) {
|
| 1116 |
-
delete cart[id];
|
| 1117 |
-
updateCartDisplay();
|
| 1118 |
-
}
|
| 1119 |
-
}
|
| 1120 |
-
|
| 1121 |
-
function clearCart() {
|
| 1122 |
-
cart = {};
|
| 1123 |
-
updateCartDisplay();
|
| 1124 |
-
}
|
| 1125 |
-
|
| 1126 |
-
function calculateChange() {
|
| 1127 |
-
const receivedInput = document.getElementById('cash-received');
|
| 1128 |
-
const receivedAmount = parseFloat(receivedInput.value.replace(',', '.')) || 0;
|
| 1129 |
-
const change = receivedAmount - totalDue;
|
| 1130 |
-
document.getElementById('cash-change').textContent = formatCurrencyJS(change) + ' сом';
|
| 1131 |
-
|
| 1132 |
-
if (change >= 0) {
|
| 1133 |
-
document.getElementById('confirm-cash-payment').disabled = false;
|
| 1134 |
-
document.getElementById('cash-change').classList.remove('text-danger');
|
| 1135 |
-
document.getElementById('cash-change').classList.add('text-success');
|
| 1136 |
-
} else {
|
| 1137 |
-
document.getElementById('confirm-cash-payment').disabled = true;
|
| 1138 |
-
document.getElementById('cash-change').classList.remove('text-success');
|
| 1139 |
-
document.getElementById('cash-change').classList.add('text-danger');
|
| 1140 |
-
}
|
| 1141 |
-
}
|
| 1142 |
-
|
| 1143 |
-
function completeSale(paymentMethod) {
|
| 1144 |
-
if (Object.keys(cart).length === 0) {
|
| 1145 |
-
flashMessage('Корзина пуста', 'warning');
|
| 1146 |
-
return;
|
| 1147 |
-
}
|
| 1148 |
-
|
| 1149 |
-
const registerId = document.getElementById('register-select').value;
|
| 1150 |
-
|
| 1151 |
-
fetch('/api/complete_sale', {
|
| 1152 |
-
method: 'POST',
|
| 1153 |
-
headers: { 'Content-Type': 'application/json' },
|
| 1154 |
-
body: JSON.stringify({
|
| 1155 |
-
cart: cart,
|
| 1156 |
-
register_id: registerId,
|
| 1157 |
-
payment_method: paymentMethod
|
| 1158 |
-
})
|
| 1159 |
-
})
|
| 1160 |
-
.then(response => response.json())
|
| 1161 |
-
.then(data => {
|
| 1162 |
-
if (data.success) {
|
| 1163 |
-
flashMessage(`Продажа #${data.sale_id.substring(0,8)} на сумму ${formatCurrencyJS(data.total)} сом завершена.`, 'success');
|
| 1164 |
-
clearCart();
|
| 1165 |
-
const modalEl = document.getElementById('cashPaymentModal');
|
| 1166 |
-
if (modalEl) {
|
| 1167 |
-
const modalInstance = bootstrap.Modal.getInstance(modalEl);
|
| 1168 |
-
if (modalInstance) modalInstance.hide();
|
| 1169 |
-
}
|
| 1170 |
-
} else {
|
| 1171 |
-
flashMessage('Ошибка: ' + data.error, 'danger');
|
| 1172 |
-
}
|
| 1173 |
-
})
|
| 1174 |
-
.catch(error => flashMessage('Ошибка сети при завершении продажи.', 'danger'));
|
| 1175 |
-
}
|
| 1176 |
-
|
| 1177 |
-
function flashMessage(message, category = 'info') {
|
| 1178 |
-
const container = document.querySelector('.flash-messages');
|
| 1179 |
-
if (!container) return;
|
| 1180 |
-
const alert = `
|
| 1181 |
-
<div class="alert alert-${category} alert-dismissible fade show" role="alert">
|
| 1182 |
-
${message}
|
| 1183 |
-
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
| 1184 |
-
</div>`;
|
| 1185 |
-
container.innerHTML += alert;
|
| 1186 |
-
}
|
| 1187 |
-
</script>
|
| 1188 |
-
"""
|
| 1189 |
-
|
| 1190 |
-
KASSA_CONTENT = """
|
| 1191 |
-
<div class="row">
|
| 1192 |
-
<div class="col-lg-5 mb-4">
|
| 1193 |
-
<div class="card">
|
| 1194 |
-
<div class="card-header"><h5 class="mb-0">Управление кассами</h5></div>
|
| 1195 |
-
<div class="card-body">
|
| 1196 |
-
<h6>Добавить кассу</h6>
|
| 1197 |
-
<form action="{{ url_for('kassa') }}" method="POST" class="mb-4">
|
| 1198 |
-
<input type="hidden" name="action" value="add_register">
|
| 1199 |
-
<div class="input-group">
|
| 1200 |
-
<input type="text" name="name" class="form-control" placeholder="Название кассы" required>
|
| 1201 |
-
<input type="text" name="initial_balance" class="form-control" placeholder="Начальный баланс" value="0">
|
| 1202 |
-
<button type="submit" class="btn btn-primary"><i class="fas fa-plus"></i></button>
|
| 1203 |
-
</div>
|
| 1204 |
-
</form>
|
| 1205 |
-
<h6>Провести транзакцию</h6>
|
| 1206 |
-
<form action="{{ url_for('kassa') }}" method="POST">
|
| 1207 |
-
<input type="hidden" name="action" value="transaction">
|
| 1208 |
-
<div class="mb-2"><select name="register_id" class="form-select" required><option value="">-- Выберите кассу --</option>{% for r in registers %}<option value="{{ r.id }}">{{ r.name }}</option>{% endfor %}</select></div>
|
| 1209 |
-
<div class="mb-2"><select name="type" class="form-select" required><option value="income">Внесение</option><option value="expense">Изъятие</option></select></div>
|
| 1210 |
-
<div class="mb-2"><input type="text" name="amount" class="form-control" placeholder="Сумма" required inputmode="decimal"></div>
|
| 1211 |
-
<div class="mb-2"><input type="text" name="description" class="form-control" placeholder="Описание" required></div>
|
| 1212 |
-
<div class="d-grid"><button type="submit" class="btn btn-success">Провести</button></div>
|
| 1213 |
-
</form>
|
| 1214 |
-
</div>
|
| 1215 |
-
</div>
|
| 1216 |
-
</div>
|
| 1217 |
-
<div class="col-lg-7">
|
| 1218 |
-
<div class="card">
|
| 1219 |
-
<div class="card-header"><h5 class="mb-0">История транзакций</h5></div>
|
| 1220 |
-
<div class="card-body">
|
| 1221 |
-
<div class="table-responsive">
|
| 1222 |
-
<table class="table table-hover table-sm">
|
| 1223 |
-
<thead><tr><th>Дата</th><th>Касса</th><th>Тип</th><th>Сумма</th><th>Описание</th></tr></thead>
|
| 1224 |
-
<tbody>
|
| 1225 |
-
{% for t in transactions %}
|
| 1226 |
-
<tr class="{{ 'text-success' if t.type == 'income' else 'text-danger' }}">
|
| 1227 |
-
<td>{{ t.timestamp[:16]|replace('T', ' ') }}</td>
|
| 1228 |
-
<td>{{ t.register_name }}</td>
|
| 1229 |
-
<td>{{ 'Внесение' if t.type == 'income' else 'Изъятие' }}</td>
|
| 1230 |
-
<td>{{ format_currency_py(t.amount) }}</td>
|
| 1231 |
-
<td>{{ t.description }}</td>
|
| 1232 |
-
</tr>
|
| 1233 |
-
{% else %}
|
| 1234 |
-
<tr><td colspan="5" class="text-center text-body-secondary py-4">Транзакций не было.</td></tr>
|
| 1235 |
-
{% endfor %}
|
| 1236 |
-
</tbody>
|
| 1237 |
-
</table>
|
| 1238 |
-
</div>
|
| 1239 |
-
</div>
|
| 1240 |
-
</div>
|
| 1241 |
-
</div>
|
| 1242 |
-
</div>
|
| 1243 |
-
"""
|
| 1244 |
-
KASSA_SCRIPTS = ""
|
| 1245 |
-
|
| 1246 |
-
REPORTS_CONTENT = """
|
| 1247 |
-
<div class="card mb-4">
|
| 1248 |
-
<div class="card-header"><h5 class="mb-0"><i class="fas fa-filter me-2"></i>Фильтр периода</h5></div>
|
| 1249 |
-
<div class="card-body">
|
| 1250 |
-
<form method="GET" action="{{ url_for('reports') }}">
|
| 1251 |
-
<div class="row g-3 align-items-end">
|
| 1252 |
-
<div class="col-md-auto"><select name="filter" class="form-select"><option value="day" {% if report.filter_type == 'day' %}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>
|
| 1253 |
-
<div class="col-md-auto custom-date" style="display: none;"><label class="form-label">Начало</label><input type="text" name="start_date" class="form-control flatpickr-date" value="{{ report.start_date }}"></div>
|
| 1254 |
-
<div class="col-md-auto custom-date" style="display: none;"><label class="form-label">Конец</label><input type="text" name="end_date" class="form-control flatpickr-date" value="{{ report.end_date }}"></div>
|
| 1255 |
-
<div class="col-md-auto"><button type="submit" class="btn btn-primary w-100">Показать</button></div>
|
| 1256 |
-
</div>
|
| 1257 |
-
</form>
|
| 1258 |
-
</div>
|
| 1259 |
-
</div>
|
| 1260 |
-
<h4>Отчет за период: <span class="text-primary">{{ report.start_date }} - {{ report.end_date }}</span></h4>
|
| 1261 |
-
<div class="row g-4 my-3">
|
| 1262 |
-
<div class="col-md-3"><div class="card h-100"><div class="card-body"><h6 class="card-subtitle text-body-secondary">Продаж</h6><p class="display-5 fw-bold">{{ report.total_sales }}</p></div></div></div>
|
| 1263 |
-
<div class="col-md-3"><div class="card h-100"><div class="card-body"><h6 class="card-subtitle text-body-secondary">Выручка</h6><p class="display-5 fw-bold">{{ format_currency_py(report.total_revenue) }}</p></div></div></div>
|
| 1264 |
-
<div class="col-md-3"><div class="card h-100"><div class="card-body"><h6 class="card-subtitle text-body-secondary">Себестоимость</h6><p class="display-5 fw-bold">{{ format_currency_py(report.total_cost) }}</p></div></div></div>
|
| 1265 |
-
<div class="col-md-3"><div class="card h-100"><div class="card-body"><h6 class="card-subtitle text-body-secondary">Прибыль</h6><p class="display-5 fw-bold">{{ format_currency_py(report.total_profit) }}</p></div></div></div>
|
| 1266 |
-
</div>
|
| 1267 |
-
<div class="card">
|
| 1268 |
-
<div class="card-header"><h5 class="mb-0">Топ продаж по выручке</h5></div>
|
| 1269 |
-
<div class="card-body">
|
| 1270 |
-
<div class="table-responsive">
|
| 1271 |
-
<table class="table table-hover">
|
| 1272 |
-
<thead><tr><th>Товар</th><th class="text-end">Продано (шт)</th><th class="text-end">Выручка</th><th class="text-end">Прибыль</th></tr></thead>
|
| 1273 |
-
<tbody>
|
| 1274 |
-
{% for item in report.product_summary %}
|
| 1275 |
-
<tr>
|
| 1276 |
-
<td>{{ item.name }}</td>
|
| 1277 |
-
<td class="text-end">{{ format_integer_py(item.quantity) }}</td>
|
| 1278 |
-
<td class="text-end">{{ format_currency_py(item.revenue) }}</td>
|
| 1279 |
-
<td class="text-end">{{ format_currency_py(item.profit) }}</td>
|
| 1280 |
-
</tr>
|
| 1281 |
-
{% else %}
|
| 1282 |
-
<tr><td colspan="4" class="text-center text-body-secondary py-4">Нет данных о продажах за период.</td></tr>
|
| 1283 |
-
{% endfor %}
|
| 1284 |
-
</tbody>
|
| 1285 |
-
</table>
|
| 1286 |
-
</div>
|
| 1287 |
-
</div>
|
| 1288 |
-
</div>
|
| 1289 |
-
"""
|
| 1290 |
-
REPORTS_SCRIPTS = """
|
| 1291 |
-
<script>
|
| 1292 |
-
document.addEventListener('DOMContentLoaded', function () {
|
| 1293 |
-
flatpickr(".flatpickr-date", { dateFormat: "Y-m-d", locale: "ru" });
|
| 1294 |
-
const filterTypeSelect = document.querySelector('select[name="filter"]');
|
| 1295 |
-
|
| 1296 |
-
function toggleDateSelectors() {
|
| 1297 |
-
const selectedType = filterTypeSelect.value;
|
| 1298 |
-
document.querySelectorAll('.custom-date').forEach(el => {
|
| 1299 |
-
el.style.display = selectedType === 'custom' ? 'block' : 'none';
|
| 1300 |
-
});
|
| 1301 |
-
}
|
| 1302 |
-
|
| 1303 |
-
filterTypeSelect.addEventListener('change', toggleDateSelectors);
|
| 1304 |
-
toggleDateSelectors();
|
| 1305 |
-
});
|
| 1306 |
-
</script>
|
| 1307 |
-
"""
|
| 1308 |
-
|
| 1309 |
-
BASE_TEMPLATE = """
|
| 1310 |
-
<!DOCTYPE html>
|
| 1311 |
-
<html lang="ru" data-bs-theme="light">
|
| 1312 |
-
<head>
|
| 1313 |
-
<meta charset="UTF-8">
|
| 1314 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1315 |
-
<title>__TITLE__ - POS</title>
|
| 1316 |
-
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
| 1317 |
-
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
| 1318 |
-
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
|
| 1319 |
-
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
| 1320 |
-
<style>
|
| 1321 |
-
:root { --bs-body-font-family: 'Inter', sans-serif; --sidebar-width: 260px; --topbar-height: 60px; }
|
| 1322 |
-
body { background-color: #f3f4f6; }
|
| 1323 |
-
[data-bs-theme="dark"] body { background-color: #111827; }
|
| 1324 |
-
.sidebar { position: fixed; top: 0; left: 0; width: var(--sidebar-width); height: 100vh; background-color: #111827; z-index: 1030; }
|
| 1325 |
-
.sidebar-brand { font-size: 1.5rem; font-weight: 700; color: white; text-decoration: none; }
|
| 1326 |
-
.sidebar .nav-link { color: #9ca3af; font-weight: 500; padding: 0.75rem 1.5rem; margin: 0.125rem 0.5rem; border-radius: 0.375rem; }
|
| 1327 |
-
.sidebar .nav-link:hover { color: #ffffff; background-color: #374151; }
|
| 1328 |
-
.sidebar .nav-link.active { color: #ffffff; background-color: #4f46e5; }
|
| 1329 |
-
.sidebar .nav-link i.fa-fw { width: 1.25em; margin-right: 0.75rem; }
|
| 1330 |
-
.main-content { margin-left: var(--sidebar-width); padding-top: calc(var(--topbar-height) + 1rem); }
|
| 1331 |
-
.topbar { position: fixed; top: 0; right: 0; left: var(--sidebar-width); height: var(--topbar-height); background: var(--bs-body-bg); border-bottom: 1px solid var(--bs-border-color); z-index: 1020; }
|
| 1332 |
-
.flash-messages { position: fixed; top: 70px; right: 20px; z-index: 2000; width: 350px; }
|
| 1333 |
-
@media (max-width: 992px) { .sidebar { transform: translateX(calc(-1 * var(--sidebar-width))); } .sidebar.active { transform: translateX(0); } .main-content { margin-left: 0; } .topbar { left: 0; } }
|
| 1334 |
-
</style>
|
| 1335 |
-
</head>
|
| 1336 |
-
<body>
|
| 1337 |
-
<div class="sidebar p-3">
|
| 1338 |
-
<a href="{{ url_for('dashboard') }}" class="sidebar-brand d-block mb-3"><i class="fas fa-cash-register text-primary"></i> POS System</a>
|
| 1339 |
-
<nav class="nav flex-column">
|
| 1340 |
-
<a class="nav-link {% if request.endpoint == 'sale' %}active{% endif %}" href="{{ url_for('sale') }}"><i class="fas fa-fw fa-cash-register"></i>Касса</a>
|
| 1341 |
-
<a class="nav-link {% if request.endpoint == 'dashboard' %}active{% endif %}" href="{{ url_for('dashboard') }}"><i class="fas fa-fw fa-tachometer-alt"></i>Панель</a>
|
| 1342 |
-
<a class="nav-link {% if request.endpoint == 'inventory' %}active{% endif %}" href="{{ url_for('inventory') }}"><i class="fas fa-fw fa-boxes"></i>Инвентарь</a>
|
| 1343 |
-
<a class="nav-link {% if request.endpoint == 'kassa' %}active{% endif %}" href="{{ url_for('kassa') }}"><i class="fas fa-fw fa-coins"></i>Упр. кассами</a>
|
| 1344 |
-
<a class="nav-link {% if request.endpoint == 'reports' %}active{% endif %}" href="{{ url_for('reports') }}"><i class="fas fa-fw fa-chart-line"></i>Отчеты</a>
|
| 1345 |
-
</nav>
|
| 1346 |
-
</div>
|
| 1347 |
-
|
| 1348 |
-
<div class="main-content p-4">
|
| 1349 |
-
<header class="topbar px-4 d-flex align-items-center justify-content-between">
|
| 1350 |
-
<button class="btn btn-outline-secondary d-lg-none" id="sidebar-toggle"><i class="fas fa-bars"></i></button>
|
| 1351 |
-
<h4 class="h5 mb-0 d-none d-lg-block">__TITLE__</h4>
|
| 1352 |
-
<div class="d-flex align-items-center">
|
| 1353 |
-
<form method="POST" action="{{ url_for('backup_hf') }}" class="me-2 mb-0"><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></form>
|
| 1354 |
-
<form method="GET" action="{{ url_for('download_hf') }}" onsubmit="return confirm('Перезаписать локальные данные с Hugging Face?');" class="mb-0"><button type="submit" class="btn btn-sm btn-outline-secondary" title="Download from Hugging Face"><i class="fas fa-cloud-download-alt me-1"></i> Download</button></form>
|
| 1355 |
-
</div>
|
| 1356 |
-
</header>
|
| 1357 |
-
<main>
|
| 1358 |
-
<div class="flash-messages">
|
| 1359 |
-
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 1360 |
-
{% if messages %}{% for category, message in messages %}
|
| 1361 |
-
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
| 1362 |
-
{{ message }}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
| 1363 |
-
</div>
|
| 1364 |
-
{% endfor %}{% endif %}
|
| 1365 |
-
{% endwith %}
|
| 1366 |
-
</div>
|
| 1367 |
-
__CONTENT__
|
| 1368 |
-
</main>
|
| 1369 |
-
</div>
|
| 1370 |
-
|
| 1371 |
-
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
| 1372 |
-
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
|
| 1373 |
-
<script src="https://npmcdn.com/flatpickr/dist/l10n/ru.js"></script>
|
| 1374 |
-
<script>
|
| 1375 |
-
document.addEventListener('DOMContentLoaded', () => {
|
| 1376 |
-
const sidebarToggle = document.getElementById('sidebar-toggle');
|
| 1377 |
-
const sidebar = document.querySelector('.sidebar');
|
| 1378 |
-
if(sidebarToggle && sidebar) {
|
| 1379 |
-
sidebarToggle.addEventListener('click', () => sidebar.classList.toggle('active'));
|
| 1380 |
-
}
|
| 1381 |
-
});
|
| 1382 |
-
function formatCurrencyJS(value) { try { const number = parseFloat(String(value).replace(/\\s/g, '').replace(',', '.')); return isNaN(number) ? '0,00' : number.toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } catch (e) { return '0,00'; } }
|
| 1383 |
-
</script>
|
| 1384 |
-
__SCRIPTS__
|
| 1385 |
-
</body>
|
| 1386 |
-
</html>
|
| 1387 |
-
"""
|
| 1388 |
-
|
| 1389 |
-
@app.context_processor
|
| 1390 |
-
def inject_utils():
|
| 1391 |
-
return {
|
| 1392 |
-
'get_current_time': get_current_time,
|
| 1393 |
-
'format_currency_py': format_currency_py,
|
| 1394 |
-
'format_integer_py': format_integer_py,
|
| 1395 |
-
'to_decimal': to_decimal
|
| 1396 |
-
}
|
| 1397 |
-
|
| 1398 |
-
if __name__ == '__main__':
|
| 1399 |
-
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 1400 |
-
backup_thread.start()
|
| 1401 |
-
try:
|
| 1402 |
-
logging.info("Initial data loading...")
|
| 1403 |
-
load_products_data()
|
| 1404 |
-
load_kassa_data()
|
| 1405 |
-
logging.info("Data loaded/initialized successfully.")
|
| 1406 |
-
except Exception as e:
|
| 1407 |
-
logging.critical(f"Failed to load databases on startup: {e}", exc_info=True)
|
| 1408 |
-
|
| 1409 |
-
logging.info("Starting Flask application on http://0.0.0.0:7860")
|
| 1410 |
-
app.run(debug=False, host='0.0.0.0', port=7860, use_reloader=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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