diff --git "a/app.py" "b/app.py" deleted file mode 100644--- "a/app.py" +++ /dev/null @@ -1,4127 +0,0 @@ - - -from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, send_from_directory -import json -import os -import logging -import threading -import time -from datetime import datetime, timedelta, date -import pytz -from huggingface_hub import HfApi, hf_hub_download -from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError -from werkzeug.utils import secure_filename -import uuid -from decimal import Decimal, InvalidOperation, ROUND_HALF_UP -import functools -from PIL import Image -import io - -app = Flask(__name__) -app.secret_key = os.urandom(24) -DATA_FILE = 'data.json' -CLIENT_DATA_FILE = 'clients.json' -UPLOAD_FOLDER = 'uploads' -THUMBNAIL_FOLDER = os.path.join(UPLOAD_FOLDER, 'thumbnails') -os.makedirs(UPLOAD_FOLDER, exist_ok=True) -os.makedirs(THUMBNAIL_FOLDER, exist_ok=True) -app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER -app.config['THUMBNAIL_FOLDER'] = THUMBNAIL_FOLDER -app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 - -HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE") -HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", "YOUR_READ_TOKEN_HERE") -REPO_ID = "Kgshop/testbasebase" - -BISHKEK_TZ = pytz.timezone('Asia/Bishkek') - -logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') - -data_lock = threading.Lock() -client_data_lock = threading.Lock() - -def get_current_time(): - return datetime.now(BISHKEK_TZ) - -def load_data(): - with data_lock: - try: - logging.info(f"Attempting download of {DATA_FILE} from {REPO_ID}...") - 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, - ) - logging.info(f"{DATA_FILE} downloaded successfully from Hugging Face.") - except RepositoryNotFoundError: - logging.warning(f"Repository {REPO_ID} not found. Checking local {DATA_FILE}.") - except HfHubHTTPError as e: - if e.response.status_code == 404: - logging.warning(f"File {DATA_FILE} not found in repository {REPO_ID}. Checking local file.") - else: - logging.error(f"HTTP error downloading {DATA_FILE} from Hugging Face: {e}") - except Exception as e: - logging.error(f"Unknown error downloading {DATA_FILE} from Hugging Face: {e}") - - try: - with open(DATA_FILE, 'r', encoding='utf-8') as file: - data = json.load(file) - logging.info("Main data loaded successfully from local JSON.") - if not isinstance(data, dict): - logging.warning(f"{DATA_FILE} is not a dictionary, initializing empty structure.") - return initialize_data_structure() - default_data = initialize_data_structure() - changed = False - for key in default_data.keys(): - if key not in data: - logging.warning(f"Key '{key}' missing in {DATA_FILE}. Initializing with default.") - data[key] = default_data[key] - changed = True - elif not isinstance(data[key], type(default_data[key])): - logging.warning(f"Key '{key}' in {DATA_FILE} has wrong type ({type(data[key])} instead of {type(default_data[key])}). Initializing with default.") - data[key] = default_data[key] - changed = True - - if 'config' not in data or not isinstance(data['config'], dict): - logging.warning(f"'config' key missing or invalid in {DATA_FILE}. Initializing with default.") - data['config'] = default_data['config'] - changed = True - else: - for config_key, default_value in default_data['config'].items(): - if config_key not in data['config']: - logging.warning(f"Config key '{config_key}' missing in {DATA_FILE}['config']. Initializing with default.") - data['config'][config_key] = default_value - changed = True - elif not isinstance(data['config'][config_key], str): - logging.warning(f"Config key '{config_key}' in {DATA_FILE}['config'] has wrong type ({type(data['config'][config_key])} instead of str). Attempting conversion to string.") - try: - data['config'][config_key] = str(data['config'][config_key]) - changed = True - except Exception: - logging.error(f"Failed to convert config value '{config_key}' to string. Setting default.") - data['config'][config_key] = default_value - changed = True - - if changed: - logging.info(f"Data structure of {DATA_FILE} updated on load. Saving changes...") - save_data(data) - - return data - except FileNotFoundError: - logging.warning(f"Local file {DATA_FILE} not found. Initializing empty structure.") - return initialize_data_structure() - except json.JSONDecodeError: - logging.error(f"JSON decode error in {DATA_FILE}. Initializing empty structure.") - try: - bad_file_path = f"{DATA_FILE}.{get_current_time().strftime('%Y%m%d%H%M%S')}.bad" - os.rename(DATA_FILE, bad_file_path) - logging.info(f"Corrupted file {DATA_FILE} renamed to {bad_file_path}") - except Exception as backup_err: - logging.error(f"Failed to backup corrupted file {DATA_FILE}: {backup_err}") - return initialize_data_structure() - except Exception as e: - logging.error(f"Unknown error loading local main data: {e}", exc_info=True) - return initialize_data_structure() - -def save_data(data): - try: - temp_file = DATA_FILE + ".tmp" - with open(temp_file, 'w', encoding='utf-8') as file: - json.dump(data, file, ensure_ascii=False, indent=4, cls=DecimalEncoder) - os.replace(temp_file, DATA_FILE) - logging.info(f"Main data successfully saved to local file {DATA_FILE}.") - except Exception as e: - logging.error(f"Critical error saving main data: {e}", exc_info=True) - if os.path.exists(temp_file): - try: os.remove(temp_file) - except OSError as rm_err: logging.error(f"Failed to remove temporary file {temp_file}: {rm_err}") - -def load_client_data(): - with client_data_lock: - try: - logging.info(f"Attempting download of {CLIENT_DATA_FILE} from {REPO_ID}...") - hf_hub_download( - repo_id=REPO_ID, filename=CLIENT_DATA_FILE, repo_type="dataset", token=HF_TOKEN_READ, - local_dir=".", local_dir_use_symlinks=False, force_download=True, - ) - logging.info(f"{CLIENT_DATA_FILE} downloaded successfully from Hugging Face.") - except RepositoryNotFoundError: logging.warning(f"Repository {REPO_ID} not found. Checking local {CLIENT_DATA_FILE}.") - except HfHubHTTPError as e: - if e.response.status_code == 404: logging.warning(f"File {CLIENT_DATA_FILE} not found in repository {REPO_ID}. Checking local file.") - else: logging.error(f"HTTP error downloading {CLIENT_DATA_FILE} from Hugging Face: {e}") - except Exception as e: logging.error(f"Unknown error downloading {CLIENT_DATA_FILE} from Hugging Face: {e}") - - try: - with open(CLIENT_DATA_FILE, 'r', encoding='utf-8') as file: - clients = json.load(file) - logging.info("Client data loaded successfully from local JSON.") - if not isinstance(clients, list): - logging.warning(f"{CLIENT_DATA_FILE} is not a list, initializing empty list.") - return [] - valid_clients = [] - changed = False - for client in clients: - if isinstance(client, dict) and 'id' in client and 'name' in client: - client_changed = False - if 'history' not in client or not isinstance(client.get('history'), list): - logging.warning(f"Incorrect 'history' format for client {client.get('id')} found on load. Initialized as empty list.") - client['history'] = [] - client_changed = True - else: - valid_history = [] - history_changed = False - for record in client['history']: - if isinstance(record, dict) and 'timestamp' in record: - record_changed = False - if 'items' not in record or not isinstance(record.get('items'), list): - logging.warning(f"Incorrect 'items' format in history record for client {client.get('id')}, shipment {record.get('shipment_id', 'N/A')}. Initialized as empty list.") - record['items'] = [] - record_changed = True - valid_history.append(record) - if record_changed: history_changed = True - else: - logging.warning(f"Invalid history record found for client {client.get('id')}. Skipped: {record}") - history_changed = True - if history_changed: - client['history'] = valid_history - client_changed = True - - valid_clients.append(client) - if client_changed: changed = True - else: - logging.warning(f"Invalid client record found in {CLIENT_DATA_FILE}. Skipped: {client}") - changed = True - - if changed: - logging.info(f"Client data structure in {CLIENT_DATA_FILE} updated on load. Saving changes...") - save_client_data(valid_clients) - - return valid_clients - except FileNotFoundError: logging.warning(f"Local file {CLIENT_DATA_FILE} not found. Initializing empty list."); return [] - except json.JSONDecodeError: - logging.error(f"JSON decode error in {CLIENT_DATA_FILE}. Initializing empty list.") - try: - bad_file_path = f"{CLIENT_DATA_FILE}.{get_current_time().strftime('%Y%m%d%H%M%S')}.bad" - os.rename(CLIENT_DATA_FILE, bad_file_path) - logging.info(f"Corrupted file {CLIENT_DATA_FILE} renamed to {bad_file_path}") - except Exception as backup_err: - logging.error(f"Failed to backup corrupted file {CLIENT_DATA_FILE}: {backup_err}") - return [] - except Exception as e: logging.error(f"Unknown error loading local client data: {e}", exc_info=True); return [] - -def save_client_data(clients): - if not isinstance(clients, list): - logging.error(f"Attempt to save non-list as {CLIENT_DATA_FILE}. Operation cancelled.") - return - for i, client in enumerate(clients): - if not isinstance(client, dict) or 'id' not in client: - logging.error(f"Attempt to save invalid client object at index {i} in {CLIENT_DATA_FILE}. Operation cancelled.") - return - if 'history' in client and not isinstance(client['history'], list): - logging.error(f"Attempt to save invalid history (not a list) for client {client.get('id')} in {CLIENT_DATA_FILE}. Operation cancelled.") - return - if 'history' in client and isinstance(client['history'], list): - for j, record in enumerate(client['history']): - if not isinstance(record, dict): - logging.error(f"Attempt to save invalid history record (not a dict) at index {j} for client {client.get('id')} in {CLIENT_DATA_FILE}. Operation cancelled.") - return - if 'items' in record and not isinstance(record['items'], list): - logging.error(f"Attempt to save invalid items (not a list) in history record {j} for client {client.get('id')} in {CLIENT_DATA_FILE}. Operation cancelled.") - return - - try: - temp_file = CLIENT_DATA_FILE + ".tmp" - with open(temp_file, 'w', encoding='utf-8') as file: - json.dump(clients, file, ensure_ascii=False, indent=4) - os.replace(temp_file, CLIENT_DATA_FILE) - logging.info(f"Client data successfully saved to local file {CLIENT_DATA_FILE}.") - except Exception as e: - logging.error(f"Critical error saving client data: {e}", exc_info=True) - if os.path.exists(temp_file): - try: os.remove(temp_file) - except OSError as rm_err: logging.error(f"Failed to remove temporary file {temp_file}: {rm_err}") - -def initialize_data_structure(): - return { - 'materials': [], 'categories': [], 'cutting_tasks': [], 'sewing_tasks': [], - 'qc_packing_items': [], 'defect_log': [], 'expenses': [], 'dordoi_shipments': [], - 'cloud_files': [], 'orders': [], 'advances': [], 'monthly_salaries': {}, - 'config': {'salary_cutter_per_unit': '0.00', 'salary_sewer_per_unit': '0.00', - 'salary_packer_per_unit': '0.00', 'margin_per_item': '0.00'} - } - -@functools.lru_cache(maxsize=1) -def get_hf_api(): - if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE": - logging.warning("HF_TOKEN_WRITE not set. Uploads to Hugging Face will be disabled.") - return None - try: return HfApi() - except Exception as e: logging.error(f"Error initializing HfApi: {e}"); return None - -def upload_db_to_hf(filepath=DATA_FILE): - api = get_hf_api() - if not api: logging.warning(f"HfApi not initialized. Upload of {filepath} to Hugging Face skipped."); return - if not os.path.exists(filepath): logging.warning(f"Local file {filepath} not found. Upload to Hugging Face skipped."); return - try: - filename = os.path.basename(filepath) - commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z') - logging.info(f"Starting upload of {filename} to Hugging Face...") - api.upload_file( - path_or_fileobj=filepath, path_in_repo=filename, repo_id=REPO_ID, repo_type="dataset", - token=HF_TOKEN_WRITE, commit_message=f"Automated backup {filename} {commit_time}", - run_as_future=True - ) - logging.info(f"Upload of {filename} to Hugging Face initiated.") - except RepositoryNotFoundError: logging.error(f"Upload error: Repository {REPO_ID} not found on Hugging Face.") - except Exception as e: logging.error(f"Error initiating upload of {filepath} to Hugging Face: {e}") - -def periodic_backup(): - logging.info("Starting periodic backup thread.") - while True: - backup_interval = 1800 - logging.debug(f"Periodic backup sleeping for {backup_interval} seconds...") - time.sleep(backup_interval) - logging.info("Starting scheduled backup...") - try: - if os.path.exists(DATA_FILE): - upload_db_to_hf(DATA_FILE) - else: - logging.warning(f"File {DATA_FILE} not found for scheduled backup.") - - if os.path.exists(CLIENT_DATA_FILE): - upload_db_to_hf(CLIENT_DATA_FILE) - else: - logging.warning(f"File {CLIENT_DATA_FILE} not found for scheduled backup.") - logging.info("Scheduled backup completed.") - except Exception as e: - logging.error(f"Error during scheduled backup: {e}", exc_info=True) - -class DecimalEncoder(json.JSONEncoder): - def default(self, obj): - if isinstance(obj, Decimal): return str(obj) - return json.JSONEncoder.default(self, obj) - -def to_decimal(value_str, default='0.00'): - if value_str is None or value_str == '': return Decimal(default) - try: return Decimal(str(value_str).replace(',', '.')) - except InvalidOperation: logging.warning(f"Could not convert '{value_str}' to Decimal. Returned {default}."); return Decimal(default) - -def parse_iso_datetime(timestamp_str): - if not timestamp_str: return None - try: - try: dt = datetime.fromisoformat(timestamp_str) - except ValueError: - if '.' in timestamp_str: timestamp_str = timestamp_str.split('.', 1)[0] - dt = datetime.fromisoformat(timestamp_str) - - if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None: - return pytz.utc.localize(dt).astimezone(BISHKEK_TZ) - else: - return dt.astimezone(BISHKEK_TZ) - except (ValueError, TypeError) as e: - logging.warning(f"Failed to parse date: '{timestamp_str}'. Error: {e}") - return None - -def find_item_by_id(item_id, item_list_name): - data = load_data() - items = data.get(item_list_name, []) - if not isinstance(items, list): - logging.error(f"Expected list for '{item_list_name}', but got {type(items)}. Returning None.") - return None - - for item in items: - if not isinstance(item, dict): - logging.warning(f"Found non-dict in list '{item_list_name}': {item}. Skipped.") - continue - - current_item_id = item.get('id') or item.get('log_id') or item.get('file_id') - if current_item_id == item_id: - item_copy = item.copy() - - decimal_fields = [] - int_fields = [] - - try: - if item_list_name == 'materials': - decimal_fields = ['quantity', 'price_per_unit', 'material_per_unit'] - int_fields = ['items_per_unit'] - elif item_list_name == 'cutting_tasks': - decimal_fields = ['fabric_used', 'material_cost', 'cutting_salary_cost'] - int_fields = ['cut_items_quantity', 'sewn_quantity'] - elif item_list_name == 'sewing_tasks': - decimal_fields = ['fittings_cost', 'sewing_salary_cost'] - int_fields = ['sewn_quantity', 'qc_packed_quantity', 'qc_defective_quantity'] - if 'fittings_consumed' in item_copy and isinstance(item_copy['fittings_consumed'], list): - for f in item_copy['fittings_consumed']: - if isinstance(f, dict): - f['quantity_used'] = int(to_decimal(f.get('quantity_used', '0'))) - f['cost'] = to_decimal(f.get('cost', '0.00')) - if 'defects_reported' in item_copy and isinstance(item_copy['defects_reported'], list): - for d in item_copy['defects_reported']: - if isinstance(d, dict): - qty_str = d.get('quantity', '0') - defect_type = d.get('type') - d['cost'] = to_decimal(d.get('cost', '0.00')) - if defect_type == 'fabric': - d['quantity'] = to_decimal(qty_str) - elif defect_type in ['fittings', 'finished_product']: - try: d['quantity'] = int(to_decimal(qty_str)) - except (InvalidOperation, ValueError): d['quantity'] = 0 - else: d['quantity'] = 0 - elif item_list_name == 'qc_packing_items': - decimal_fields = ['packed_material_cost', 'packed_salary_cost', 'packed_total_cost', 'packed_margin', 'packed_final_price'] - int_fields = ['quantity'] - elif item_list_name == 'expenses': - decimal_fields = ['amount'] - elif item_list_name == 'defect_log': - decimal_fields = ['cost'] - qty_str = item_copy.get('quantity', '0') - defect_type = item_copy.get('type') - item_copy['cost_dec'] = to_decimal(item_copy.get('cost', '0.00')) - if defect_type == 'fabric': - qty_dec = to_decimal(qty_str) - item_copy['quantity_view'] = f"{qty_dec:.2f}".replace('.', ',') - item_copy['quantity_raw'] = qty_dec - elif defect_type in ['fittings', 'finished_product']: - try: - qty_int = int(to_decimal(qty_str)) - item_copy['quantity_view'] = str(qty_int) - item_copy['quantity_raw'] = qty_int - except (InvalidOperation, ValueError): - item_copy['quantity_view'] = '0'; item_copy['quantity_raw'] = 0 - else: - item_copy['quantity_view'] = str(qty_str); item_copy['quantity_raw'] = qty_str - - for field in decimal_fields: - if item_copy.get(field) is not None: - item_copy[field] = to_decimal(item_copy.get(field)) - else: - item_copy[field] = Decimal('0.00') - logging.debug(f"Decimal field '{field}' missing in {item_list_name} ID {item_id}. Set to '0.00'.") - for field in int_fields: - if item_copy.get(field) is not None: - item_copy[field] = int(to_decimal(item_copy.get(field, '0'))) - else: - item_copy[field] = 0 - logging.debug(f"Int field '{field}' missing in {item_list_name} ID {item_id}. Set to 0.") - - except Exception as conversion_error: - logging.error(f"Type conversion error for {item_list_name} ID {item_id}: {conversion_error}", exc_info=True) - return None - - return item_copy - return None - -def find_client_by_id(client_id): - clients = load_client_data() - for client in clients: - if client.get('id') == client_id: - client_copy = client.copy() - if 'history' in client_copy: - for record in client_copy['history']: - record['timestamp_dt'] = parse_iso_datetime(record.get('timestamp')) - return client_copy - return None - -def create_thumbnail(image_path, thumb_path, size=(100, 100)): - try: - with Image.open(image_path) as img: - img.thumbnail(size) - try: - img.save(thumb_path, "JPEG") - logging.info(f"Thumbnail created: {thumb_path}") - return os.path.basename(thumb_path) - except OSError as e: - try: - img.save(thumb_path, "PNG") - logging.info(f"Thumbnail created (PNG): {thumb_path}") - return os.path.basename(thumb_path) - except Exception as png_e: - logging.error(f"Failed to save thumbnail as PNG for {image_path}: {png_e}") - return None - except Exception as e: - logging.error(f"Failed to save thumbnail as JPEG for {image_path}: {e}") - return None - - except Exception as e: - logging.error(f"Error creating thumbnail for {image_path}: {e}") - return None - -def format_currency_py(value): - try: - number = to_decimal(value) - formatted_num = f"{number:,.2f}".replace(",", "TEMP_SPACE").replace(".", ",").replace("TEMP_SPACE", " ") - return formatted_num - except (InvalidOperation, TypeError, ValueError): - return "0,00" - -def format_integer_py(value): - try: - number = to_decimal(value).to_integral_value(rounding=ROUND_HALF_UP) - return f"{number:,}".replace(",", " ") - except (InvalidOperation, TypeError, ValueError): - return "0" - -def getStatusText(statusKey): - statusMap = { - 'pending': 'Ожидает пошива', - 'completed': 'Завершено', - 'pending_qc': 'Ожидает ОТК', - 'packed_ready_to_ship': 'Готово к отправке', - 'shipped_client': 'Отправлено клиенту', - 'shipped_dor_doi': 'Отправлено на Дордой', - 'pending_procurement': 'Ожидает закупа' - } - return statusMap.get(statusKey, statusKey) - -def getStatusClass(statusKey): - classMap = { - 'pending': 'status-pending text-info', - 'completed': 'status-completed text-success', - 'pending_qc': 'status-pending_qc text-warning', - 'packed_ready_to_ship': 'status-packed_ready_to_ship text-ready', - 'shipped_client': 'status-shipped_client text-shipped-client', - 'shipped_dor_doi': 'status-shipped_dor_doi text-shipped-dordoi' - } - return classMap.get(statusKey, '') - -@app.route('/') -def index(): - return redirect(url_for('admin_panel')) - -@app.route('/orders', methods=['GET', 'POST']) -def orders(): - data = load_data() - clients_data = load_client_data() - - fabrics = [m for m in data.get('materials', []) - if isinstance(m, dict) and m.get('type') == 'fabric'] - fittings = [m for m in data.get('materials', []) - if isinstance(m, dict) and m.get('type') == 'fittings'] - - if request.method == 'POST': - try: - client_id = request.form.get('client_id') - model_name = request.form.get('model_name', '').strip() - fabric_name = request.form.get('fabric_name', '').strip() - fabric_quantity = request.form.get('fabric_quantity') - size_range = request.form.get('size_range', '').strip() - items_quantity = request.form.get('items_quantity') - prepayment = request.form.get('prepayment', '0') - - if not all([client_id, model_name, fabric_name, fabric_quantity, items_quantity]): - flash("Заполните все обязательные поля заказа.", "danger") - return redirect(url_for('orders')) - - client = find_client_by_id(client_id) - if not client: - flash("Выбранный клиент не найден.", "danger") - return redirect(url_for('orders')) - - creation_time = get_current_time().isoformat() - new_order = { - 'id': uuid.uuid4().hex, - 'client_id': client_id, - 'client_name': client.get('name', 'N/A'), - 'model_name': model_name, - 'fabric_name': fabric_name, - 'fabric_quantity': fabric_quantity, - 'size_range': size_range, - 'items_quantity': items_quantity, - 'prepayment': str(to_decimal(prepayment)), - 'status': 'pending_procurement', - 'timestamp_created': creation_time, - 'timestamp': creation_time, - 'is_procured': False, - 'fittings': [] - } - - fitting_names = request.form.getlist('fitting_names[]') - fitting_quantities = request.form.getlist('fitting_quantities[]') - - for i in range(len(fitting_names)): - name = fitting_names[i].strip() - qty = fitting_quantities[i].strip() - if name and qty: - new_order['fittings'].append({ - 'fitting_name': name, - 'quantity': qty - }) - - if 'orders' not in data: - data['orders'] = [] - - data['orders'].append(new_order) - save_data(data) - - flash(f"Заказ на {items_quantity} ед. '{model_name}' успешно создан.", "success") - upload_db_to_hf(DATA_FILE) - return redirect(url_for('orders')) - - except Exception as e: - logging.error(f"Ошибка при создании заказа: {e}", exc_info=True) - flash(f"Произошла ошибка при создании заказа: {e}", "danger") - return redirect(url_for('orders')) - - orders_list = data.get('orders', []) - for order in orders_list: - if isinstance(order, dict): - fabric = find_item_by_id(order.get('fabric_id'), 'materials') if order.get('fabric_id') else None - if fabric: - order['fabric_unit'] = fabric.get('unit', 'м') - else: - order['fabric_unit'] = 'м' - - if 'fittings' in order and isinstance(order['fittings'], list): - for f in order['fittings']: - if isinstance(f, dict) and f.get('fitting_id'): - fitting = find_item_by_id(f.get('fitting_id'), 'materials') - if fitting: - f['fitting_name'] = fitting.get('name', 'N/A') - elif not isinstance(f, dict) or not f.get('fitting_name'): - f['fitting_name'] = f.get('fitting_name', 'N/A') - - for order in orders_list: - if isinstance(order, dict) and not order.get('timestamp_created'): - order['timestamp_created'] = order.get('timestamp', '') - - orders_list.sort(key=lambda x: x.get('timestamp_created', ''), reverse=True) - - html = BASE_TEMPLATE.replace('__TITLE__', "Заказы").replace('__CONTENT__', ORDERS_CONTENT).replace('__SCRIPTS__', ORDERS_SCRIPTS) - return render_template_string(html, - clients=clients_data, - fabrics=fabrics, - fittings=fittings, - orders=orders_list, - getStatusText=getStatusText, - getStatusClass=getStatusClass) - -@app.route('/orders/edit/', methods=['POST']) -def edit_order(order_id): - data = load_data() - orders = data.get('orders', []) - order_index = None - for i, order in enumerate(orders): - if isinstance(order, dict) and order.get('id') == order_id: - order_index = i - break - - if order_index is None: - flash("Заказ не найден.", "danger") - return redirect(url_for('orders')) - - try: - orders[order_index].update({ - 'model_name': request.form.get('model_name', '').strip(), - 'fabric_name': request.form.get('fabric_name', '').strip(), - 'fabric_quantity': request.form.get('fabric_quantity'), - 'size_range': request.form.get('size_range', '').strip(), - 'items_quantity': request.form.get('items_quantity'), - 'prepayment': str(to_decimal(request.form.get('prepayment', '0'))) - }) - - fitting_names = request.form.getlist('fitting_names[]') - fitting_quantities = request.form.getlist('fitting_quantities[]') - orders[order_index]['fittings'] = [] - for i in range(len(fitting_names)): - name = fitting_names[i].strip() - qty = fitting_quantities[i].strip() - if name and qty: - orders[order_index]['fittings'].append({ - 'fitting_name': name, - 'quantity': qty - }) - - save_data(data) - flash("Заказ успешно обновлен.", "success") - upload_db_to_hf(DATA_FILE) - - except Exception as e: - logging.error(f"Ошибка при обновлении заказа {order_id}: {e}", exc_info=True) - flash(f"Произошла ошибка при обновлении заказа: {e}", "danger") - - return redirect(url_for('orders')) - -@app.route('/orders/delete/', methods=['POST']) -def delete_order(order_id): - data = load_data() - orders = data.get('orders', []) - initial_length = len(orders) - deleted_order = next((o for o in orders if isinstance(o, dict) and o.get('id') == order_id), None) - - if deleted_order and deleted_order.get('status') == 'completed': - flash("Нельзя удалить выполненный заказ.", "danger") - return redirect(url_for('orders')) - - updated_orders = [order for order in orders if not (isinstance(order, dict) and order.get('id') == order_id)] - - if len(updated_orders) < initial_length: - data['orders'] = updated_orders - save_data(data) - flash("Заказ успешно удален.", "success") - upload_db_to_hf(DATA_FILE) - elif deleted_order: - flash("Нельзя удалить выполненный заказ (хотя он был найден).", "danger") - else: - flash("Заказ не найден.", "warning") - - return redirect(url_for('orders')) - - -@app.route('/procurement', methods=['GET', 'POST']) -def procurement(): - data = load_data() - categories = data.get('categories', []) - pending_orders = [ - order for order in data.get('orders', []) - if isinstance(order, dict) and - order.get('status') == 'pending_procurement' and - not order.get('is_procured', False) - ] - - if request.method == 'POST': - order_id = request.form.get('order_id') - if order_id: - order_found = False - for order in data.get('orders', []): - if isinstance(order, dict) and order.get('id') == order_id: - order['is_procured'] = True - order['status'] = 'pending' - order['procurement_timestamp'] = get_current_time().isoformat() - order_found = True - break - if order_found: - save_data(data) - flash(f"Заказ '{order.get('model_name')}' отмечен как закупленный и готов к раскрою.", "success") - upload_db_to_hf(DATA_FILE) - else: - flash(f"Заказ с ID {order_id} не найден.", "danger") - return redirect(url_for('procurement')) - - try: - materials_to_add = [] - valid_items_processed = 0 - - item_names = request.form.getlist('item_name[]') - item_quantities = request.form.getlist('item_quantity[]') - item_units = request.form.getlist('item_unit[]') - item_prices = request.form.getlist('item_price_per_unit[]') - item_material_per_unit_list = request.form.getlist('item_per_unit[]') # Get list of submitted values (only fabric) - item_types = request.form.getlist('item_type[]') - item_categories = request.form.getlist('item_category[]') - item_new_categories = request.form.getlist('item_new_category[]') - - if not item_names or all(not name.strip() for name in item_names): - flash("Не добавлено ни одного товара. Заполните хотя бы одну строку.", "warning") - return redirect(url_for('procurement')) - - procurement_time = get_current_time().isoformat() - current_materials = data.get('materials', []) - fabric_per_unit_index = 0 # Index for the shorter item_material_per_unit_list - - for i in range(len(item_names)): - # --- FIX: Removed item_material_per_unit from length check --- - if i >= len(item_quantities) or i >= len(item_units) or \ - i >= len(item_prices) or \ - i >= len(item_types) or i >= len(item_categories) or \ - i >= len(item_new_categories): - logging.warning(f"Inconsistent form data lengths at index {i} in procurement. Skipping row.") - flash(f"Ошибка в данных формы для строки {i+1}. Пропущено.", "danger") - continue - # --- END FIX --- - - name = item_names[i].strip() - quantity_str = item_quantities[i] - unit = item_units[i] - price_str = item_prices[i] - item_type = item_types[i] - category = item_categories[i] - new_category = item_new_categories[i].strip() - - if not name and not quantity_str and not price_str and not category and not new_category: - continue - - if not name or not quantity_str or not unit or not price_str or not item_type: - flash(f"Ошибка в строке {i+1}: Необходимо заполнить название, количество, единицу измерения, цену за единицу и тип.", "danger") - continue - - try: - quantity = to_decimal(quantity_str) - price = to_decimal(price_str) - except InvalidOperation: - flash(f"Ошибка в строке {i+1}: Некорректный формат числа для количества или цены.", "danger") - continue - if quantity <= 0: - flash(f"Ошибка в строке {i+1}: Количество должно быть больше нуля.", "danger") - continue - if price < 0: - flash(f"Ошибка в строке {i+1}: Цена не может быть отрицательной.", "danger") - continue - - material_per_unit = Decimal('0') # Default for fittings or invalid fabric input - material_per_unit_str = '' - if item_type == 'fabric': - # --- FIX: Get value only if fabric and handle potential missing item --- - if fabric_per_unit_index < len(item_material_per_unit_list): - material_per_unit_str = item_material_per_unit_list[fabric_per_unit_index] - if material_per_unit_str: - try: - material_per_unit_val = to_decimal(material_per_unit_str) - if material_per_unit_val >= 0: - material_per_unit = material_per_unit_val - else: - flash(f"Предупреждение в строке {i+1}: Отрицательное значение 'Расход на одно изделие', установлено 0.", "warning") - except InvalidOperation: - flash(f"Предупреждение в строке {i+1}: Некорректное значение 'Расход на одно изделие', установлено 0.", "warning") - fabric_per_unit_index += 1 # Increment index only for fabric rows processed - else: - # Should not happen if JS works, but log if it does - logging.warning(f"Procurement: Missing 'item_per_unit' value for fabric row at index {i} (expected list index {fabric_per_unit_index}).") - # --- END FIX --- - - final_category = new_category if new_category else (category if category and category != "__new__" else "Без категории") - current_valid_categories = [c for c in categories if isinstance(c, str)] - if new_category and final_category not in current_valid_categories: - current_valid_categories.append(final_category) - categories = current_valid_categories - - existing_material_index = -1 - for idx, mat in enumerate(current_materials): - if isinstance(mat, dict) and \ - mat.get('name','').lower() == name.lower() and \ - mat.get('type') == item_type and \ - mat.get('category', 'Без категории') == final_category: - existing_material_index = idx - break - - if existing_material_index != -1: - existing_material = current_materials[existing_material_index] - existing_material['price_per_unit'] = str(price) - current_quantity = to_decimal(existing_material.get('quantity', '0')) - new_quantity = current_quantity + quantity - existing_material['quantity'] = str(new_quantity) - existing_material['unit'] = unit - existing_material['material_per_unit'] = str(material_per_unit) # Update with potentially 0 for fittings - existing_material['timestamp_last_updated'] = procurement_time - logging.info(f"Material '{name}' updated. New qty: {new_quantity}, Price: {price}, Category: {final_category}, MatPerUnit: {material_per_unit}") - valid_items_processed += 1 - else: - new_material = { - 'id': uuid.uuid4().hex, - 'name': name, - 'quantity': str(quantity), - 'unit': unit, - 'price_per_unit': str(price), - 'material_per_unit': str(material_per_unit), # Set to 0 for fittings - 'items_per_unit': 0, - 'type': item_type, - 'category': final_category, - 'timestamp_added': procurement_time, - 'timestamp_last_updated': procurement_time - } - materials_to_add.append(new_material) - logging.info(f"New material '{name}' added. Qty: {quantity}, Price: {price}, Category: {final_category}, MatPerUnit: {material_per_unit}") - valid_items_processed += 1 - - if valid_items_processed > 0 : - if materials_to_add: - data['materials'].extend(materials_to_add) - data['categories'] = sorted(list(set(c for c in categories if isinstance(c, str))), key=str.lower) - save_data(data) - flash(f"Закуп успешно зарегистрирован! Обработано {valid_items_processed} позиций.", "success") - upload_db_to_hf(DATA_FILE) - else: - flash("Не было добавлено или обновлено ни одной валидной позиции.", "warning") - - return redirect(url_for('procurement')) - - except Exception as e: - logging.error(f"Ошибка при обработке закупа: {e}", exc_info=True) - flash(f"Произошла внутренняя ошибка при обработке закупа: {e}", "danger") - return redirect(url_for('procurement')) - - materials_display = [] - for m in data.get('materials', []): - if isinstance(m, dict) and 'id' in m: - m_data = find_item_by_id(m['id'], 'materials') - if m_data: - if m_data.get('type') == 'fabric': - m_data['quantity_str'] = format_currency_py(m_data.get('quantity', '0.00')) - else: - m_data['quantity_str'] = format_integer_py(m_data.get('quantity', '0')) - m_data['price_str'] = format_currency_py(m_data.get('price_per_unit', '0.00')) - materials_display.append(m_data) - valid_categories = [c for c in categories if isinstance(c, str)] - pending_orders_display = [ - order for order in data.get('orders', []) - if isinstance(order, dict) and - order.get('status') == 'pending_procurement' and - not order.get('is_procured', False) - ] - pending_orders_display.sort(key=lambda x: x.get('timestamp_created', ''), reverse=True) - - html = BASE_TEMPLATE.replace('__TITLE__', "Закуп материалов").replace('__CONTENT__', PROCUREMENT_CONTENT).replace('__SCRIPTS__', PROCUREMENT_SCRIPTS) - return render_template_string(html, categories=valid_categories, materials_display=materials_display, orders=pending_orders_display) - -@app.route('/cutting', methods=['GET', 'POST']) -def cutting(): - data = load_data() - fabrics = [] - for m in data.get('materials', []): - if isinstance(m, dict) and m.get('type') == 'fabric': - if to_decimal(m.get('quantity', '0')) > 0: - fabrics.append(m) - - config = data.get('config', {}) - - if request.method == 'POST': - try: - fabric_id = request.form.get('fabric_id') - cut_items_quantity_str = request.form.get('cut_items_quantity') - fabric_used_str = request.form.get('fabric_used') - - if not fabric_id or not cut_items_quantity_str or not fabric_used_str: - flash("Необходимо выбрать ткань и заполнить все поля.", "danger") - return redirect(url_for('cutting')) - - fabric_material = find_item_by_id(fabric_id, 'materials') - if not fabric_material: - flash("Выбранная ткань не найдена в базе данных.", "danger") - return redirect(url_for('cutting')) - - try: - cut_items_quantity = int(to_decimal(cut_items_quantity_str).to_integral_value()) - if cut_items_quantity <= 0: raise ValueError("Количество должно быть > 0") - except (InvalidOperation, ValueError): - flash("Некорректное количество раскроенных изделий. Введите целое положительное число.", "danger") - return redirect(url_for('cutting')) - - try: - fabric_used = to_decimal(fabric_used_str) - if fabric_used <= 0: raise ValueError("Расход ткани должен быть > 0") - except (InvalidOperation, ValueError): - flash("Некорректное значение использованной ткани. Введите положительное число.", "danger") - return redirect(url_for('cutting')) - - available_quantity = fabric_material.get('quantity', Decimal('0.00')) - if fabric_used > available_quantity: - flash(f"Недостаточно ткани '{fabric_material['name']}'. В наличии: {format_currency_py(available_quantity)} {fabric_material['unit']}, требуется: {format_currency_py(fabric_used)} {fabric_material['unit']}.", "danger") - return redirect(url_for('cutting')) - - price_per_unit = fabric_material.get('price_per_unit', Decimal('0.00')) - material_cost = fabric_used * price_per_unit - - salary_cutter_per_unit = to_decimal(config.get('salary_cutter_per_unit', '0.00')) - cutting_salary_cost = Decimal(cut_items_quantity) * salary_cutter_per_unit - - creation_time = get_current_time().isoformat() - cutting_task = { - 'id': uuid.uuid4().hex, - 'fabric_id': fabric_id, - 'fabric_name': fabric_material['name'], - 'fabric_unit': fabric_material['unit'], - 'cut_items_quantity': cut_items_quantity, - 'fabric_used': str(fabric_used), - 'status': 'pending', - 'sewn_quantity': 0, - 'timestamp_created': creation_time, - 'timestamp_completed': None, - 'material_cost': str(material_cost), - 'cutting_salary_cost': str(cutting_salary_cost) - } - - new_available_quantity = available_quantity - fabric_used - material_updated = False - current_materials = data.get('materials', []) - for i, mat in enumerate(current_materials): - if isinstance(mat, dict) and mat.get('id') == fabric_id: - current_materials[i]['quantity'] = str(new_available_quantity.quantize(Decimal('0.01'))) - current_materials[i]['timestamp_last_updated'] = creation_time - material_updated = True - break - - if not material_updated: - flash(f"Критическая ошибка: не удалось обновить остаток ткани '{fabric_material['name']}'.", "danger") - return redirect(url_for('cutting')) - - if 'cutting_tasks' not in data: data['cutting_tasks'] = [] - data['cutting_tasks'].append(cutting_task) - save_data(data) - - flash(f"Задание на раскрой для {cut_items_quantity} ед. из '{fabric_material['name']}' успешно создано. Статус: Ожидает пошива.", "success") - upload_db_to_hf(DATA_FILE) - return redirect(url_for('cutting')) - - except Exception as e: - logging.error(f"Ошибка при регистрации раскроя: {e}", exc_info=True) - flash(f"Произошла внутренняя ошибка при регистрации раскроя: {e}", "danger") - return redirect(url_for('cutting')) - - fabrics_display = [] - for f in fabrics: - if isinstance(f, dict) and 'id' in f: - f_copy = find_item_by_id(f['id'], 'materials') - if f_copy: - f_copy['quantity_str'] = format_currency_py(f_copy.get('quantity', '0.00')) - fabrics_display.append(f_copy) - - html = BASE_TEMPLATE.replace('__TITLE__', "Раскрой ткани").replace('__CONTENT__', CUTTING_CONTENT).replace('__SCRIPTS__', CUTTING_SCRIPTS) - return render_template_string(html, fabrics=fabrics_display) - -@app.route('/sewing', methods=['GET', 'POST']) -def sewing(): - data = load_data() - config = data.get('config', {}) - - if request.method == 'POST': - try: - cutting_task_id = request.form.get('cutting_task_id') - product_name = request.form.get('product_name', '').strip() - quantity_to_sew_str = request.form.get('quantity_to_sew') - fitting_ids = request.form.getlist('fitting_ids[]') - fitting_quantities = request.form.getlist('fitting_quantities[]') - - if not cutting_task_id or not product_name or not quantity_to_sew_str: - flash("Необходимо выбрать задание раскроя, указать название изделия и количество для пошива.", "danger") - return redirect(url_for('sewing')) - - cutting_task = find_item_by_id(cutting_task_id, 'cutting_tasks') - if not cutting_task: - flash("Выбранное задание на раскрой не найдено.", "danger") - return redirect(url_for('sewing')) - - try: - quantity_to_sew = int(to_decimal(quantity_to_sew_str).to_integral_value()) - except (InvalidOperation, ValueError): - flash("Некорректное количество для пошива.", "danger") - return redirect(url_for('sewing')) - - cut_qty = cutting_task.get('cut_items_quantity', 0) - already_sewn = cutting_task.get('sewn_quantity', 0) - remaining_to_cut = cut_qty - already_sewn - - if quantity_to_sew <= 0: - flash("Количество для пошива должно быть больше нуля.", "danger") - return redirect(url_for('sewing')) - if quantity_to_sew > remaining_to_cut: - flash(f"Нельзя сшить {quantity_to_sew} ед. Доступно только {remaining_to_cut} раскроенных.", "danger") - return redirect(url_for('sewing')) - - fittings_consumed = [] - total_fittings_cost = Decimal('0.00') - fitting_updates = {} - - current_materials = data.get('materials', []) - - for i in range(len(fitting_ids)): - fitting_id = fitting_ids[i] - qty_str = fitting_quantities[i].strip() - - if not fitting_id or not qty_str: - continue - - try: - quantity_used = int(to_decimal(qty_str).to_integral_value()) - if quantity_used <= 0: - flash(f"Количество для фурнитуры в строке {i+1} должно быть положительным.", "warning") - continue - except (InvalidOperation, ValueError): - flash(f"Некорректное количество для фурнитуры в строке {i+1}.", "warning") - continue - - fitting_material = None - for mat in current_materials: - if isinstance(mat, dict) and mat.get('id') == fitting_id: - fitting_material = find_item_by_id(fitting_id, 'materials') - break - - if not fitting_material: - flash(f"Фурнитура с ID {fitting_id} (строка {i+1}) не найдена.", "danger") - return redirect(url_for('sewing')) - - available_fitting_qty = fitting_material.get('quantity', Decimal('0')) - if available_fitting_qty < quantity_used: - flash(f"Недостаточно фурнитуры '{fitting_material.get('name')}'. В наличии: {format_integer_py(available_fitting_qty)}, требуется: {quantity_used}.", "danger") - return redirect(url_for('sewing')) - - price_per_fitting = fitting_material.get('price_per_unit', Decimal('0.00')) - cost_for_this_fitting = price_per_fitting * Decimal(quantity_used) - total_fittings_cost += cost_for_this_fitting - - fittings_consumed.append({ - 'fitting_id': fitting_id, - 'fitting_name': fitting_material.get('name', 'N/A'), - 'quantity_used': quantity_used, - 'cost': str(cost_for_this_fitting) - }) - - if fitting_id not in fitting_updates: - fitting_updates[fitting_id] = {'decrease_by': 0} - fitting_updates[fitting_id]['decrease_by'] += quantity_used - - sewing_time = get_current_time().isoformat() - salary_sewer_per_unit = to_decimal(config.get('salary_sewer_per_unit', '0.00')) - sewing_salary_cost = salary_sewer_per_unit * Decimal(quantity_to_sew) - - new_sewing_task = { - 'id': uuid.uuid4().hex, - 'cutting_task_id': cutting_task_id, - 'product_name': product_name, - 'sewn_quantity': quantity_to_sew, - 'fittings_consumed': fittings_consumed, - 'fittings_cost': str(total_fittings_cost), - 'sewing_salary_cost': str(sewing_salary_cost), - 'status': 'pending_qc', - 'qc_packed_quantity': 0, - 'qc_defective_quantity': 0, - 'defects_reported': [], - 'timestamp_created': sewing_time, - 'timestamp_completed': None - } - - if 'sewing_tasks' not in data: data['sewing_tasks'] = [] - data['sewing_tasks'].append(new_sewing_task) - - cutting_task_updated = False - current_cutting_tasks = data.get('cutting_tasks', []) - for i, task in enumerate(current_cutting_tasks): - if isinstance(task, dict) and task.get('id') == cutting_task_id: - current_cutting_tasks[i]['sewn_quantity'] = int(task.get('sewn_quantity', 0)) + quantity_to_sew - if current_cutting_tasks[i]['sewn_quantity'] >= int(task.get('cut_items_quantity', 0)): - current_cutting_tasks[i]['status'] = 'completed' - current_cutting_tasks[i]['timestamp_completed'] = sewing_time - cutting_task_updated = True - break - - if not cutting_task_updated: - flash(f"Критическая ошибка: не удалось обновить задание на раскрой {cutting_task_id}.", "danger") - - materials_updated = False - for mat_idx, mat in enumerate(current_materials): - if isinstance(mat, dict) and mat.get('id') in fitting_updates: - fitting_id = mat.get('id') - decrease_by = fitting_updates[fitting_id]['decrease_by'] - current_qty = to_decimal(mat.get('quantity', '0')) - new_qty = current_qty - Decimal(decrease_by) - if new_qty < 0: - flash(f"Критическая ошибка: Отрицательный остаток фурнитуры {mat.get('name')}.", "danger") - return redirect(url_for('sewing')) - current_materials[mat_idx]['quantity'] = str(new_qty.to_integral_value()) - current_materials[mat_idx]['timestamp_last_updated'] = sewing_time - materials_updated = True - - save_data(data) - flash(f"{quantity_to_sew} ед. изделия '{product_name}' успешно сшито и отправлено на ОТК.", "success") - upload_db_to_hf(DATA_FILE) - return redirect(url_for('sewing')) - - except Exception as e: - logging.error(f"Ошибка при регистрации пошива: {e}", exc_info=True) - flash(f"Произошла внутренняя ошибка при регистрации пошива: {e}", "danger") - return redirect(url_for('sewing')) - - pending_cutting_tasks_raw = [ - t for t in data.get('cutting_tasks', []) - if isinstance(t, dict) and t.get('status') == 'pending' and int(t.get('cut_items_quantity', 0)) > int(t.get('sewn_quantity', 0)) - ] - pending_cutting_tasks_display = [] - for task_raw in pending_cutting_tasks_raw: - if 'id' in task_raw: - task_data = find_item_by_id(task_raw['id'], 'cutting_tasks') - if task_data: - task_data['remaining_quantity'] = task_data.get('cut_items_quantity', 0) - task_data.get('sewn_quantity', 0) - if task_data['remaining_quantity'] > 0: - task_data['fabric_used_str'] = format_currency_py(task_data.get('fabric_used', '0.00')) - pending_cutting_tasks_display.append(task_data) - pending_cutting_tasks_display.sort(key=lambda x: x.get('timestamp_created', ''), reverse=True) - - available_fittings_raw = [ - m for m in data.get('materials', []) - if isinstance(m, dict) and m.get('type') == 'fittings' and int(to_decimal(m.get('quantity', '0'))) > 0 - ] - available_fittings_display = [] - for fitting_raw in available_fittings_raw: - if 'id' in fitting_raw: - fitting_data = find_item_by_id(fitting_raw['id'], 'materials') - if fitting_data: - fitting_data['quantity_str'] = format_integer_py(fitting_data.get('quantity', '0')) - available_fittings_display.append(fitting_data) - available_fittings_display.sort(key=lambda x: x.get('name', '').lower()) - - html = BASE_TEMPLATE.replace('__TITLE__', "Пошив").replace('__CONTENT__', NEW_SEWING_CONTENT).replace('__SCRIPTS__', NEW_SEWING_SCRIPTS) - return render_template_string(html, - cutting_tasks=pending_cutting_tasks_display, - available_fittings=available_fittings_display) - - -@app.route('/qc_packing', methods=['GET', 'POST']) -def qc_packing(): - data = load_data() - pending_qc_tasks = [] - for t in data.get('sewing_tasks', []): - if isinstance(t, dict) and t.get('status') == 'pending_qc': - task_data_full = find_item_by_id(t['id'], 'sewing_tasks') - if task_data_full: - total_sewn = task_data_full.get('sewn_quantity', 0) - already_processed = task_data_full.get('qc_packed_quantity', 0) + task_data_full.get('qc_defective_quantity', 0) - remaining = total_sewn - already_processed - if remaining > 0: - t['remaining_quantity'] = remaining - pending_qc_tasks.append(t) - - config = data.get('config', {}) - - if request.method == 'POST': - try: - sewing_task_id = request.form.get('sewing_task_id') - quantity_packed_str = request.form.get('quantity_packed') - quantity_defective_str = request.form.get('quantity_defective', '0') - defect_reason = request.form.get('defect_reason', 'Брак при ОТК/упаковке').strip() - - if not sewing_task_id: - flash("Необходимо выбрать задание на пошив.", "danger") - return redirect(url_for('qc_packing')) - - sewing_task = find_item_by_id(sewing_task_id, 'sewing_tasks') - if not sewing_task or sewing_task.get('status') != 'pending_qc': - flash("Выбранное задание на пошив не найдено или уже не ожидает ОТК.", "danger") - return redirect(url_for('qc_packing')) - - try: - quantity_packed = int(to_decimal(quantity_packed_str).to_integral_value()) if quantity_packed_str else 0 - quantity_defective = int(to_decimal(quantity_defective_str).to_integral_value()) if quantity_defective_str else 0 - - if quantity_packed < 0 or quantity_defective < 0: - raise ValueError("Количество не может быть отрицательным") - - total_processed_now = quantity_packed + quantity_defective - if total_processed_now <= 0: - flash("Необходимо указать количество упакованных или бракованных изделий (сумма должна быть > 0).", "warning") - return redirect(url_for('qc_packing')) - - total_sewn = sewing_task.get('sewn_quantity', 0) - already_packed = sewing_task.get('qc_packed_quantity', 0) - already_defective = sewing_task.get('qc_defective_quantity', 0) - remaining_to_process = total_sewn - (already_packed + already_defective) - - if total_processed_now > remaining_to_process: - flash(f"Ошибка: Сумма упакованных ({quantity_packed}) и брака ({quantity_defective}) = {total_processed_now}, что превышает остаток изделий для обработки ({remaining_to_process}).", "danger") - return redirect(url_for('qc_packing')) - - except (InvalidOperation, ValueError) as e: - flash(f"Некорректное количество упакованных или бракованных изделий: {e}", "danger") - return redirect(url_for('qc_packing')) - - qc_time = get_current_time().isoformat() - new_packed_item_entry = None - new_defect_log_entry = None - - cutting_task_id = sewing_task.get('cutting_task_id') - cutting_task = find_item_by_id(cutting_task_id, 'cutting_tasks') - - if not cutting_task: - logging.warning(f"Cutting task {cutting_task_id} not found for sewing task {sewing_task_id} during QC cost calculation.") - cutting_task = {'material_cost': Decimal('0'), 'cutting_salary_cost': Decimal('0'), 'cut_items_quantity': 1} - - fabric_cost_total = cutting_task.get('material_cost', Decimal('0')) - cutting_salary_total = cutting_task.get('cutting_salary_cost', Decimal('0')) - fittings_cost_total = sewing_task.get('fittings_cost', Decimal('0')) - sewing_salary_total = sewing_task.get('sewing_salary_cost', Decimal('0')) - - cut_qty = cutting_task.get('cut_items_quantity', 1) or 1 - sewn_qty_from_task = sewing_task.get('sewn_quantity', 1) or 1 - - fabric_cost_per_item = fabric_cost_total / Decimal(cut_qty) - fittings_cost_per_item = fittings_cost_total / Decimal(sewn_qty_from_task) - material_cost_per_item = fabric_cost_per_item + fittings_cost_per_item - - cutting_salary_per_item = cutting_salary_total / Decimal(cut_qty) - sewing_salary_per_item = sewing_salary_total / Decimal(sewn_qty_from_task) - packing_salary_per_item = to_decimal(config.get('salary_packer_per_unit', '0.00')) - - if quantity_packed > 0: - salary_cost_per_packed_item = cutting_salary_per_item + sewing_salary_per_item + packing_salary_per_item - total_cost_per_packed_item = material_cost_per_item + salary_cost_per_packed_item - - margin_per_item = to_decimal(config.get('margin_per_item', '0.00')) - final_price_per_packed_item = total_cost_per_packed_item + margin_per_item - - packed_batch_material_cost = material_cost_per_item * Decimal(quantity_packed) - packed_batch_salary_cost = salary_cost_per_packed_item * Decimal(quantity_packed) - packed_batch_total_cost = total_cost_per_packed_item * Decimal(quantity_packed) - packed_batch_margin = margin_per_item * Decimal(quantity_packed) - packed_batch_final_price = final_price_per_packed_item * Decimal(quantity_packed) - - new_packed_item_entry = { - 'id': uuid.uuid4().hex, - 'sewing_task_id': sewing_task_id, - 'product_name': sewing_task['product_name'], - 'quantity': quantity_packed, - 'timestamp_packed': qc_time, - 'packed_material_cost': str(packed_batch_material_cost), - 'packed_salary_cost': str(packed_batch_salary_cost), - 'packed_total_cost': str(packed_batch_total_cost), - 'packed_margin': str(packed_batch_margin), - 'packed_final_price': str(packed_batch_final_price), - 'status': 'packed_ready_to_ship', - 'shipment_details': None - } - - if 'qc_packing_items' not in data: data['qc_packing_items'] = [] - data['qc_packing_items'].append(new_packed_item_entry) - - if quantity_defective > 0: - salary_cost_per_defective_item = cutting_salary_per_item + sewing_salary_per_item - cost_per_defective_item = material_cost_per_item + salary_cost_per_defective_item - total_defect_cost = cost_per_defective_item * Decimal(quantity_defective) - - new_defect_log_entry = { - 'log_id': uuid.uuid4().hex, - 'material_id': None, - 'material_name': f"{sewing_task['product_name']} (готовое изделие)", - 'quantity': quantity_defective, - 'unit': 'шт', - 'type': 'finished_product', - 'stage': 'qc_packing', - 'reason': defect_reason if defect_reason else 'Брак при ОТК/упаковке', - 'cost': str(total_defect_cost), - 'sewing_task_id': sewing_task_id, - 'timestamp': qc_time - } - - if 'defect_log' not in data: data['defect_log'] = [] - data['defect_log'].append(new_defect_log_entry) - logging.info(f"QC defect logged: {quantity_defective} pcs of '{sewing_task['product_name']}' (Total cost: {format_currency_py(total_defect_cost)})") - - sewing_task_updated = False - current_sewing_tasks = data.get('sewing_tasks', []) - for i, task in enumerate(current_sewing_tasks): - if isinstance(task, dict) and task.get('id') == sewing_task_id: - current_sewing_tasks[i]['qc_packed_quantity'] = int(task.get('qc_packed_quantity', 0)) + quantity_packed - current_sewing_tasks[i]['qc_defective_quantity'] = int(task.get('qc_defective_quantity', 0)) + quantity_defective - - total_processed_for_task = current_sewing_tasks[i]['qc_packed_quantity'] + current_sewing_tasks[i]['qc_defective_quantity'] - task_sewn_qty = int(task.get('sewn_quantity', 0)) - - if total_processed_for_task >= task_sewn_qty: - current_sewing_tasks[i]['status'] = 'completed' - current_sewing_tasks[i]['timestamp_completed'] = qc_time - logging.info(f"Sewing task {sewing_task_id} fully processed and completed.") - else: - current_sewing_tasks[i]['status'] = 'pending_qc' - logging.info(f"Sewing task {sewing_task_id} partially processed. Remaining: {task_sewn_qty - total_processed_for_task}") - - sewing_task_updated = True - break - - if not sewing_task_updated: - logging.error(f"Critical error: Failed to find and update sewing task {sewing_task_id}.") - flash(f"Критическая ошибка при обновлении задания на пошив {sewing_task_id}.", "danger") - - save_data(data) - - flash_message = f"ОТК/У��аковка для '{sewing_task['product_name']}': упаковано {quantity_packed} ед., брак {quantity_defective} ед. " - if new_packed_item_entry: - flash_message += f"Статус упакованных: Готово к отправке." - elif new_defect_log_entry: - flash_message += f"Брак зарегистрирован." - - flash(flash_message, "success") - upload_db_to_hf(DATA_FILE) - return redirect(url_for('qc_packing')) - - except Exception as e: - logging.error(f"Ошибка при обработке ОТК и упаковки: {e}", exc_info=True) - flash(f"Произошла внутренняя ошибка при обработке ОТК и упаковки: {e}", "danger") - return redirect(url_for('qc_packing')) - - tasks_for_template = [] - for task in pending_qc_tasks: - if isinstance(task, dict) and 'id' in task: - if task.get('remaining_quantity', 0) > 0: - tasks_for_template.append(task) - - html = BASE_TEMPLATE.replace('__TITLE__', "ОТК и Упаковка").replace('__CONTENT__', QC_PACKING_CONTENT).replace('__SCRIPTS__', QC_PACKING_SCRIPTS) - return render_template_string(html, sewing_tasks=tasks_for_template) - - -@app.route('/clients', methods=['GET', 'POST']) -def clients_panel(): - if request.method == 'POST': - action = request.form.get('action', 'add') - clients = load_client_data() - - if action == 'edit': - client_id = request.form.get('client_id') - name = request.form.get('client_name', '').strip() - phone = request.form.get('client_phone', '').strip() - address = request.form.get('client_address', '').strip() - - if not name or not phone or not client_id: - flash("Все обязательные поля должны быть заполнены.", "danger") - return redirect(url_for('clients_panel')) - - client_found = False - normalized_phone = ''.join(filter(str.isdigit, phone)) - for client in clients: - if client.get('id') == client_id: - current_phone = ''.join(filter(str.isdigit, client.get('phone', ''))) - if normalized_phone != current_phone: - if any(''.join(filter(str.isdigit, c.get('phone',''))) == normalized_phone - for c in clients if c.get('id') != client_id): - flash(f"Телефон {phone} уже используется другим клиентом.", "warning") - return redirect(url_for('clients_panel')) - - client['name'] = name - client['phone'] = phone - client['address'] = address if address else None - client_found = True - break - - if client_found: - save_client_data(clients) - flash(f"Данные клиента '{name}' обновлены.", "success") - upload_db_to_hf(CLIENT_DATA_FILE) - else: - flash("Клиент не найден.", "danger") - return redirect(url_for('clients_panel')) - - elif action == 'delete': - client_id = request.form.get('client_id') - if not client_id: - flash("ID клиента не указан.", "danger") - return redirect(url_for('clients_panel')) - - client_found = False - for i, client in enumerate(clients): - if client.get('id') == client_id: - if client.get('history', []): - flash("Невозможно удалить клиента с историей отправок.", "warning") - return redirect(url_for('clients_panel')) - deleted_name = client.get('name', 'Неизвестный клиент') - del clients[i] - client_found = True - break - - if client_found: - save_client_data(clients) - flash(f"Клиент '{deleted_name}' удален.", "success") - upload_db_to_hf(CLIENT_DATA_FILE) - else: - flash("Клиент не найден.", "danger") - return redirect(url_for('clients_panel')) - - else: - name = request.form.get('client_name','').strip() - phone = request.form.get('client_phone','').strip() - address = request.form.get('client_address','').strip() - - if not name or not phone: - flash("Имя/Название организации и номер телефона обязательны.", "danger") - return redirect(url_for('clients_panel')) - - normalized_phone = ''.join(filter(str.isdigit, phone)) - if any(''.join(filter(str.isdigit, c.get('phone',''))) == normalized_phone for c in clients): - flash(f"Клиент с похожим номером телефона ({phone}) уже существует в базе.", "warning") - return redirect(url_for('clients_panel')) - - new_client = { - 'id': uuid.uuid4().hex, - 'name': name, - 'phone': phone, - 'address': address if address else None, - 'history': [] - } - clients.append(new_client) - save_client_data(clients) - flash(f"Клиент '{name}' успешно добавлен.", "success") - upload_db_to_hf(CLIENT_DATA_FILE) - return redirect(url_for('clients_panel')) - - try: - clients_data = load_client_data() - clients_data.sort(key=lambda x: x.get('name','').lower()) - - for client in clients_data: - if 'history' in client: - client['history'].sort(key=lambda x: x.get('timestamp',''), reverse=True) - for record in client['history']: - record['timestamp_dt'] = parse_iso_datetime(record.get('timestamp')) - - html = BASE_TEMPLATE.replace('__TITLE__', "База клиентов").replace('__CONTENT__', CLIENTS_CONTENT).replace('__SCRIPTS__', CLIENTS_SCRIPTS) - return render_template_string(html, clients=clients_data) - - except Exception as e: - logging.error(f"Unexpected error in GET /clients: {e}", exc_info=True) - flash("Произошла ошибка при отображении страницы клиентов.", "danger") - return redirect(url_for('admin_panel')) - -@app.route('/admin') -def admin_panel(): - data = load_data() - clients_data = load_client_data() - config = data.get('config', {}) - - all_materials = [m for m_id in [m.get('id') for m in data.get('materials', []) if isinstance(m, dict)] - if (m := find_item_by_id(m_id, 'materials')) is not None and to_decimal(m.get('quantity', '0')) > 0] - materials_count = len(all_materials) - - all_cutting_tasks = [t for t_id in [t.get('id') for t in data.get('cutting_tasks', []) if isinstance(t, dict)] if (t := find_item_by_id(t_id, 'cutting_tasks')) is not None] - all_sewing_tasks = [s for s_id in [s.get('id') for s in data.get('sewing_tasks', []) if isinstance(s, dict)] if (s := find_item_by_id(s_id, 'sewing_tasks')) is not None] - all_packed_items = [p for p_id in [p.get('id') for p in data.get('qc_packing_items', []) if isinstance(p, dict)] if (p := find_item_by_id(p_id, 'qc_packing_items')) is not None] - all_defect_log = [d for d_id in [d.get('log_id') for d in data.get('defect_log', []) if isinstance(d, dict)] if (d := find_item_by_id(d_id, 'defect_log')) is not None] - all_expenses = [e for e_id in [e.get('id') for e in data.get('expenses', []) if isinstance(e, dict)] if (e := find_item_by_id(e_id, 'expenses')) is not None] - dordoi_shipments = data.get('dordoi_shipments', []) - for ship in dordoi_shipments: - ship['timestamp_dt'] = parse_iso_datetime(ship.get('timestamp')) - dordoi_shipments.sort(key=lambda x: x.get('timestamp',''), reverse=True) - - categories = data.get('categories', []) - - items_ready_to_ship = [item for item in all_packed_items if item.get('status') == 'packed_ready_to_ship'] - items_ready_ship_count = len(items_ready_to_ship) - items_ready_ship_qty = sum(item.get('quantity', 0) for item in items_ready_to_ship) - - total_packed_count = items_ready_ship_qty - - pending_cutting_count = len([task for task in all_cutting_tasks if task.get('status') == 'pending' and task.get('cut_items_quantity', 0) > task.get('sewn_quantity', 0)]) - - pending_qc_tasks = [] - pending_qc_quantity = 0 - for task in all_sewing_tasks: - if task.get('status') == 'pending_qc': - total_sewn = task.get('sewn_quantity', 0) - already_processed = task.get('qc_packed_quantity', 0) + task.get('qc_defective_quantity', 0) - remaining = total_sewn - already_processed - if remaining > 0: - pending_qc_tasks.append(task) - pending_qc_quantity += remaining - pending_qc_count = len(pending_qc_tasks) - - - total_defect_fabric_m = sum(d.get('quantity_raw', Decimal('0')) for d in all_defect_log if d.get('type') == 'fabric') - total_defect_fittings_pcs = sum(d.get('quantity_raw', 0) for d in all_defect_log if d.get('type') == 'fittings') - total_defect_finished_pcs = sum(d.get('quantity_raw', 0) for d in all_defect_log if d.get('type') == 'finished_product') - total_defect_cost = sum(d.get('cost_dec', Decimal('0')) for d in all_defect_log) - - config_decimal = {k: to_decimal(v) for k, v in config.items()} - - html = BASE_TEMPLATE.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_CONTENT).replace('__SCRIPTS__', ADMIN_SCRIPTS) - return render_template_string(html, - materials=all_materials, - cutting_tasks=all_cutting_tasks, - sewing_tasks=all_sewing_tasks, - packed_items=all_packed_items, - items_ready_to_ship=items_ready_to_ship, - clients=sorted(clients_data, key=lambda x: x.get('name','').lower()), - defect_log=all_defect_log, - expenses=all_expenses, - dordoi_shipments=dordoi_shipments, - categories=categories, - config=config_decimal, - materials_count=materials_count, - pending_cutting_count=pending_cutting_count, - pending_qc_count=pending_qc_count, - pending_qc_quantity=pending_qc_quantity, - total_packed_count=total_packed_count, - items_ready_ship_count=items_ready_ship_count, - items_ready_ship_qty=items_ready_ship_qty, - total_defect_fabric_m=format_currency_py(total_defect_fabric_m), - total_defect_fittings_pcs=format_integer_py(total_defect_fittings_pcs), - total_defect_finished_pcs=format_integer_py(total_defect_finished_pcs), - total_defect_cost=format_currency_py(total_defect_cost) - ) - -@app.route('/dispatch_item', methods=['POST']) -def dispatch_item(): - item_id = request.form.get('item_id') - destination_type = request.form.get('destination_type') - client_id = request.form.get('client_id') - quantity_to_dispatch_str = request.form.get('quantity_to_dispatch') - - redirect_target = url_for('admin_panel') + '#dispatch-content' - - if not item_id or not destination_type or not quantity_to_dispatch_str: - flash("Ошибка: Не указан ID товара, тип назначения или количество для отправки.", "danger") - return redirect(redirect_target) - - data = load_data() - clients = load_client_data() - - packed_item_to_update = None - item_index = -1 - packed_items_list = data.get('qc_packing_items', []) - - for i, item in enumerate(packed_items_list): - if isinstance(item, dict) and item.get('id') == item_id and item.get('status') == 'packed_ready_to_ship': - packed_item_to_update = item - item_index = i - break - - if not packed_item_to_update: - flash(f"Ошибка: Товар с ID {item_id}, готовый к отправке, не найден.", "danger") - return redirect(redirect_target) - - try: - quantity_to_dispatch = int(to_decimal(quantity_to_dispatch_str).to_integral_value()) - current_quantity = int(to_decimal(packed_item_to_update.get('quantity', '0'))) - - if quantity_to_dispatch <= 0: - raise ValueError("Количество должно быть положительным") - if quantity_to_dispatch > current_quantity: - flash(f"Ошибка: Нельзя отправить {quantity_to_dispatch} шт., так как в наличии только {current_quantity} шт.", "danger") - return redirect(redirect_target) - except (InvalidOperation, ValueError) as e: - flash(f"Некорректное количество для отправки: {e}", "danger") - return redirect(redirect_target) - - dispatch_time_iso = get_current_time().isoformat() - client_data_changed = False - main_data_changed = False - product_name = packed_item_to_update.get('product_name', 'N/A') - destination_display_text = '' - is_full_dispatch = (quantity_to_dispatch == current_quantity) - history_items = [{'product_name': product_name, 'quantity': quantity_to_dispatch}] - - if destination_type == 'client': - if not client_id: - flash("Ошибка: Не выбран клиент для отправки.", "danger") - return redirect(redirect_target) - - client_object_to_update = None - client_name = "Клиент не найден" - for cl in clients: - if cl.get('id') == client_id: - client_object_to_update = cl - client_name = cl.get('name', 'Имя не найдено') - break - - if not client_object_to_update: - flash(f"Ошибка: Клиент с ID {client_id} не найден в базе.", "danger") - return redirect(redirect_target) - - history_entry = { - 'shipment_id': uuid.uuid4().hex, - 'timestamp': dispatch_time_iso, - 'items': history_items, - 'packed_item_id': item_id - } - if not isinstance(client_object_to_update.get('history'), list): - client_object_to_update['history'] = [] - client_object_to_update['history'].append(history_entry) - client_data_changed = True - destination_display_text = f"клиенту '{client_name}'" - - if is_full_dispatch: - packed_item_to_update['status'] = 'shipped_client' - packed_item_to_update['shipment_details'] = { - 'type': destination_type, - 'timestamp': dispatch_time_iso, - 'client_id': client_id, - 'client_name': client_name - } - main_data_changed = True - - elif destination_type == 'dor_doi_point': - dordoi_entry = { - 'shipment_id': uuid.uuid4().hex, - 'timestamp': dispatch_time_iso, - 'items': history_items, - 'packed_item_id': item_id - } - if 'dordoi_shipments' not in data or not isinstance(data['dordoi_shipments'], list): - data['dordoi_shipments'] = [] - data['dordoi_shipments'].append(dordoi_entry) - destination_display_text = "на Торговую точку Дордой" - main_data_changed = True - - if is_full_dispatch: - packed_item_to_update['status'] = 'shipped_dor_doi' - packed_item_to_update['shipment_details'] = { - 'type': destination_type, - 'timestamp': dispatch_time_iso, - 'destination': 'Торговая точка Дордой' - } - - else: - flash("Ошибка: Неверный тип назначения.", "danger") - return redirect(redirect_target) - - if not is_full_dispatch: - remaining_quantity = current_quantity - quantity_to_dispatch - proportion_remaining = Decimal(remaining_quantity) / Decimal(current_quantity) - fields_to_recalculate = [ - 'packed_material_cost', 'packed_salary_cost', - 'packed_total_cost', 'packed_margin', 'packed_final_price' - ] - for field in fields_to_recalculate: - current_cost = to_decimal(packed_item_to_update.get(field, '0')) - remaining_cost = (current_cost * proportion_remaining).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) - packed_item_to_update[field] = str(remaining_cost) - - packed_item_to_update['quantity'] = remaining_quantity - main_data_changed = True - logging.info(f"Partial dispatch of item {item_id} ({product_name}): {quantity_to_dispatch} pcs. Remaining: {remaining_quantity} pcs.") - - if main_data_changed: - save_data(data) - upload_db_to_hf(DATA_FILE) - logging.info(f"Main data saved after dispatching item {item_id}.") - - if client_data_changed: - save_client_data(clients) - upload_db_to_hf(CLIENT_DATA_FILE) - logging.info(f"Client data {client_id} saved.") - - flash(f"{quantity_to_dispatch} шт. товара '{product_name}' успешно отправлено {destination_display_text}.", "success") - return redirect(redirect_target) - -@app.route('/advances/delete/', methods=['POST']) -def delete_advance(advance_id): - data = load_data() - advances = data.get('advances', []) - initial_length = len(advances) - advances[:] = [adv for adv in advances if not (isinstance(adv, dict) and adv.get('id') == advance_id)] - - if len(advances) < initial_length: - data['advances'] = advances - save_data(data) - flash("Аванс успешно удален.", "success") - upload_db_to_hf(DATA_FILE) - else: - flash("Аванс для удаления не найден.", "warning") - return redirect(url_for('advances')) - -@app.route('/admin/expense/delete/', methods=['POST']) -def delete_expense(expense_id): - data = load_data() - expenses = data.get('expenses', []) - initial_length = len(expenses) - expenses[:] = [exp for exp in expenses if not (isinstance(exp, dict) and exp.get('id') == expense_id)] - - if len(expenses) < initial_length: - data['expenses'] = expenses - save_data(data) - flash("Расход успешно удален.", "success") - upload_db_to_hf(DATA_FILE) - else: - flash("Расход для удаления не найден.", "warning") - return redirect(url_for('admin_panel') + '#expenses-report-content') - -@app.route('/advances', methods=['GET', 'POST']) -def advances(): - data = load_data() - if 'advances' not in data: data['advances'] = [] - if 'monthly_salaries' not in data: data['monthly_salaries'] = {} - - if request.method == 'POST': - try: - employee_name = request.form.get('employee_name', '').strip() - role = request.form.get('role', '').strip() - amount_str = request.form.get('amount', '0') - month_year = get_current_time().strftime('%Y-%m') - - if month_year not in data['monthly_salaries']: data['monthly_salaries'][month_year] = {} - if employee_name not in data['monthly_salaries'][month_year]: - data['monthly_salaries'][month_year][employee_name] = {'role': role, 'earned': Decimal('0'), 'advances': Decimal('0'), 'final_payout': Decimal('0')} - - if not employee_name or not role or not amount_str: - flash("Заполните все поля", "danger") - return redirect(url_for('advances')) - - amount = to_decimal(amount_str) - if amount <= 0: - flash("Сумма аванса должна быть положительной", "danger") - return redirect(url_for('advances')) - - advance = {'id': uuid.uuid4().hex, 'employee_name': employee_name, 'role': role, 'amount': str(amount), 'timestamp': get_current_time().isoformat(), 'is_processed': False} - data['advances'].append(advance) - save_data(data) - flash(f"Аванс {format_currency_py(amount)} сом выдан {employee_name}", "success") - upload_db_to_hf(DATA_FILE) - except Exception as e: - logging.error(f"Ошибка при выдаче аванса: {e}", exc_info=True) - flash(f"Ошибка при выдаче аванса: {e}", "danger") - - advances_list = data.get('advances', []) - advances_list.sort(key=lambda x: x.get('timestamp', ''), reverse=True) - - html = BASE_TEMPLATE.replace('__TITLE__', "Авансы").replace('__CONTENT__', ADVANCES_CONTENT).replace('__SCRIPTS__', ADVANCES_SCRIPTS) - return render_template_string(html, advances=advances_list) - -@app.route('/admin/config/update', methods=['POST']) -def update_config(): - data = load_data() - config = data.get('config', {}) - try: - config['salary_cutter_per_unit'] = str(to_decimal(request.form.get('salary_cutter'))) - config['salary_sewer_per_unit'] = str(to_decimal(request.form.get('salary_sewer'))) - config['salary_packer_per_unit'] = str(to_decimal(request.form.get('salary_packer'))) - config['margin_per_item'] = str(to_decimal(request.form.get('margin'))) - data['config'] = config - save_data(data) - flash("Настройки зарплат и маржи успешно сохранены.", "success") - upload_db_to_hf(DATA_FILE) - except InvalidOperation: - flash("Ошибка: Введено некорректное числовое значение.", "danger") - except Exception as e: - logging.error(f"Ошибка при обновлении конфигурации: {e}", exc_info=True) - flash(f"Произошла ошибка при сохранении настроек: {e}", "danger") - return redirect(url_for('admin_panel')) - -@app.route('/admin/expense/add', methods=['POST']) -def add_expense(): - data = load_data() - description = request.form.get('expense_description','').strip() - amount_str = request.form.get('expense_amount') - redirect_target = url_for('admin_panel') + '#expenses-report-content' - - if not description or not amount_str: - flash("Необходимо заполнить описание и сумму расхода.", "warning") - return redirect(redirect_target) - - try: - amount = to_decimal(amount_str) - if amount <= 0: raise ValueError("Сумма должна быть > 0") - except (InvalidOperation, ValueError): - flash("Некорректное значение суммы расхода. Введите положительное число.", "warning") - return redirect(redirect_target) - - if 'expenses' not in data or not isinstance(data['expenses'], list): - data['expenses'] = [] - - new_expense = {'id': uuid.uuid4().hex, 'description': description, 'amount': str(amount), 'timestamp': get_current_time().isoformat()} - data['expenses'].append(new_expense) - save_data(data) - flash(f"Расход '{description}' на сумму {format_currency_py(amount)} сом успешно добавлен.", "success") - upload_db_to_hf(DATA_FILE) - return redirect(redirect_target) - -@app.route('/admin/category/add', methods=['POST']) -def add_category(): - data = load_data() - categories = data.get('categories', []) - new_category_name = request.form.get('new_category_name','').strip() - - if not new_category_name: - flash("Название категории не может быть пустым.", "warning") - return redirect(url_for('admin_panel')) - - current_valid_categories = [c for c in categories if isinstance(c, str)] - if new_category_name.lower() not in [c.lower() for c in current_valid_categories]: - current_valid_categories.append(new_category_name) - data['categories'] = sorted(list(set(current_valid_categories)), key=str.lower) - save_data(data) - flash(f"Категория '{new_category_name}' успешно добавлена.", "success") - upload_db_to_hf(DATA_FILE) - else: - flash(f"Категория '{new_category_name}' уже существует.", "warning") - return redirect(url_for('admin_panel')) - -@app.route('/admin/category/delete', methods=['POST']) -def delete_category(): - data = load_data() - categories = data.get('categories', []) - category_to_delete = request.form.get('category_to_delete') - - if not category_to_delete: - flash("Не выбрана категория для удаления.", "warning") - return redirect(url_for('admin_panel')) - - if category_to_delete == 'Без категории': - flash("Нельзя удалить системную категорию 'Без категории'.", "danger") - return redirect(url_for('admin_panel')) - - original_category_name = None - category_found = False - current_valid_categories = [c for c in categories if isinstance(c, str)] - for cat in current_valid_categories: - if cat.lower() == category_to_delete.lower(): - original_category_name = cat - category_found = True - break - - if category_found and original_category_name: - current_valid_categories.remove(original_category_name) - data['categories'] = sorted(current_valid_categories, key=str.lower) - materials_updated_count = 0 - current_materials = data.get('materials', []) - update_time = get_current_time().isoformat() - for mat in current_materials: - if isinstance(mat, dict) and mat.get('category', 'Без категории') == original_category_name: - mat['category'] = 'Без категории' - mat['timestamp_last_updated'] = update_time - materials_updated_count += 1 - save_data(data) - flash(f"Категория '{original_category_name}' успешно удалена.", "success") - if materials_updated_count > 0: - flash(f"{materials_updated_count} материалов были перенесены в категорию 'Без категории'.", "info") - upload_db_to_hf(DATA_FILE) - else: - flash(f"Категория '{category_to_delete}' не найдена.", "warning") - return redirect(url_for('admin_panel')) - -@app.route('/backup', methods=['POST']) -def backup_hf(): - files_uploaded_count = 0 - try: - logging.info("Manual backup to Hugging Face initiated...") - with data_lock: - if os.path.exists(DATA_FILE): - upload_db_to_hf(DATA_FILE) - files_uploaded_count += 1 - else: - flash(f"Local file '{DATA_FILE}' not found for backup.", "warning") - with client_data_lock: - if os.path.exists(CLIENT_DATA_FILE): - upload_db_to_hf(CLIENT_DATA_FILE) - files_uploaded_count += 1 - else: - flash(f"Local file '{CLIENT_DATA_FILE}' not found for backup.", "warning") - if files_uploaded_count > 0: - flash(f"Backup of {files_uploaded_count} files to Hugging Face initiated.", "success") - else: - flash("No local files found to initiate backup.", "warning") - except Exception as e: - logging.error(f"Error during manual backup: {e}", exc_info=True) - flash(f"An error occurred during backup: {e}", "danger") - return redirect(url_for('admin_panel')) - -@app.route('/download', methods=['GET']) -def download_hf(): - downloaded_files = [] - errors = [] - logging.info("Starting data download from Hugging Face...") - try: - logging.info(f"Attempting download of {DATA_FILE}...") - 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) - downloaded_files.append(DATA_FILE) - logging.info(f"{DATA_FILE} downloaded successfully.") - except RepositoryNotFoundError: msg = f"Repository '{REPO_ID}' not found on Hugging Face."; logging.error(msg); errors.append(msg) - except HfHubHTTPError as e: - if e.response.status_code == 404: msg = f"File '{DATA_FILE}' not found in repository '{REPO_ID}'."; logging.warning(msg); errors.append(msg) - else: msg = f"HTTP error ({e.response.status_code}) downloading {DATA_FILE}: {e}"; logging.error(msg); errors.append(msg) - except Exception as e: msg = f"Unknown error downloading {DATA_FILE}: {e}"; logging.error(msg, exc_info=True); errors.append(msg) - - try: - logging.info(f"Attempting download of {CLIENT_DATA_FILE}...") - hf_hub_download(repo_id=REPO_ID, filename=CLIENT_DATA_FILE, repo_type="dataset", token=HF_TOKEN_READ, local_dir=".", local_dir_use_symlinks=False, force_download=True) - downloaded_files.append(CLIENT_DATA_FILE) - logging.info(f"{CLIENT_DATA_FILE} downloaded successfully.") - except RepositoryNotFoundError: - if not any(f"Repository '{REPO_ID}' not found" in err for err in errors): msg = f"Repository '{REPO_ID}' not found on Hugging Face."; logging.error(msg); errors.append(msg) - except HfHubHTTPError as e: - if e.response.status_code == 404: msg = f"File '{CLIENT_DATA_FILE}' not found in repository '{REPO_ID}'."; logging.warning(msg); errors.append(msg) - else: msg = f"HTTP error ({e.response.status_code}) downloading {CLIENT_DATA_FILE}: {e}"; logging.error(msg); errors.append(msg) - except Exception as e: msg = f"Unknown error downloading {CLIENT_DATA_FILE}: {e}"; logging.error(msg, exc_info=True); errors.append(msg) - - if downloaded_files: flash(f"Files ({', '.join(downloaded_files)}) downloaded successfully and overwritten locally.", "success") - if errors: flash("Errors occurred during download: " + "; ".join(errors), "danger") - if not downloaded_files and not errors: flash("Failed to initiate file download.", "warning") - - try: - logging.info("Reloading data into memory after download...") - load_data() - load_client_data() - logging.info("In-memory data updated.") - except Exception as e: - logging.error(f"Error reloading data after download: {e}", exc_info=True) - flash("Warning: Files downloaded, but an error occurred updating application data. A restart may be required.", "warning") - return redirect(url_for('admin_panel')) - -@app.route('/reports', methods=['GET']) -def reports(): - data = load_data() - config = data.get('config', {}) - now = get_current_time() - - filter_type = request.args.get('filter', 'month') - start_date_str = request.args.get('start_date') - end_date_str = request.args.get('end_date') - date_str = request.args.get('date') - month_str = request.args.get('month') - year_str = request.args.get('year') - - start_date_dt = None - end_date_dt = None - - try: - if filter_type == 'custom' and start_date_str and end_date_str: - sd = datetime.strptime(start_date_str, '%Y-%m-%d') - ed = datetime.strptime(end_date_str, '%Y-%m-%d') - start_date_dt = BISHKEK_TZ.localize(sd.replace(hour=0, minute=0, second=0, microsecond=0)) - end_date_dt = BISHKEK_TZ.localize(ed.replace(hour=23, minute=59, second=59, microsecond=999999)) - elif filter_type == 'day': - day_to_use_str = date_str if date_str else now.strftime('%Y-%m-%d') - d = datetime.strptime(day_to_use_str, '%Y-%m-%d') - start_date_dt = BISHKEK_TZ.localize(d.replace(hour=0, minute=0, second=0, microsecond=0)) - end_date_dt = start_date_dt.replace(hour=23, minute=59, second=59, microsecond=999999) - elif filter_type == 'week': - today_start = now.replace(hour=0, minute=0, second=0, microsecond=0) - start_date_dt = today_start - timedelta(days=today_start.weekday()) - end_date_dt = start_date_dt + timedelta(days=6, hours=23, minutes=59, seconds=59, microseconds=999999) - elif filter_type == 'year': - year_to_use_str = year_str if year_str else str(now.year) - year_int = int(year_to_use_str) - start_date_dt = BISHKEK_TZ.localize(datetime(year_int, 1, 1, 0, 0, 0)) - end_date_dt = BISHKEK_TZ.localize(datetime(year_int, 12, 31, 23, 59, 59, 999999)) - else: - month_to_use_str = month_str if month_str else now.strftime('%Y-%m') - year, month = map(int, month_to_use_str.split('-')) - start_date_dt = BISHKEK_TZ.localize(datetime(year, month, 1, 0, 0, 0)) - next_month_start = (start_date_dt.replace(day=28) + timedelta(days=4)).replace(day=1) - end_date_dt = (next_month_start - timedelta(microseconds=1)).replace(hour=23, minute=59, second=59, microsecond=999999) - - if not start_date_dt or not end_date_dt or start_date_dt > end_date_dt: - raise ValueError("Invalid time range.") - - except (ValueError, TypeError) as e: - flash(f"Error setting period: {e}. Displaying report for current month.", "warning") - filter_type = 'month' - start_date_dt = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) - next_month_start = (start_date_dt.replace(day=28) + timedelta(days=4)).replace(day=1) - end_date_dt = (next_month_start - timedelta(microseconds=1)).replace(hour=23, minute=59, second=59, microsecond=999999) - - filtered_packed_items = [] - all_packed_items_raw = data.get('qc_packing_items', []) - for item_raw in all_packed_items_raw: - if isinstance(item_raw, dict) and 'id' in item_raw: - item_data = find_item_by_id(item_raw['id'], 'qc_packing_items') - if not item_data: continue - packed_time = parse_iso_datetime(item_data.get('timestamp_packed')) - if packed_time and start_date_dt <= packed_time <= end_date_dt: - shipment_time = None - shipment_details = item_data.get('shipment_details') - if shipment_details and shipment_details.get('timestamp'): - shipment_time = parse_iso_datetime(shipment_details.get('timestamp')) - item_data['shipment_time_dt'] = shipment_time - filtered_packed_items.append(item_data) - - all_defect_log_raw = data.get('defect_log', []) - filtered_defects = [] - for defect_raw in all_defect_log_raw: - if isinstance(defect_raw, dict) and 'log_id' in defect_raw: - defect_data = find_item_by_id(defect_raw['log_id'], 'defect_log') - if not defect_data: continue - defect_time = parse_iso_datetime(defect_data.get('timestamp')) - if defect_time and start_date_dt <= defect_time <= end_date_dt: - filtered_defects.append(defect_data) - - all_expenses_raw = data.get('expenses', []) - filtered_expenses = [] - for expense_raw in all_expenses_raw: - if isinstance(expense_raw, dict) and 'id' in expense_raw: - expense_data = find_item_by_id(expense_raw['id'], 'expenses') - if not expense_data: continue - expense_time = parse_iso_datetime(expense_data.get('timestamp')) - if expense_time and start_date_dt <= expense_time <= end_date_dt: - filtered_expenses.append(expense_data) - - total_packed_quantity = sum(item.get('quantity', 0) for item in filtered_packed_items) - total_revenue = sum(item.get('packed_final_price', Decimal('0')) for item in filtered_packed_items) - total_material_cost_packed = sum(item.get('packed_material_cost', Decimal('0')) for item in filtered_packed_items) - total_salary_cost_packed = sum(item.get('packed_salary_cost', Decimal('0')) for item in filtered_packed_items) - total_cost_packed = total_material_cost_packed + total_salary_cost_packed - total_defect_cost = sum(defect.get('cost_dec', Decimal('0')) for defect in filtered_defects) - total_expenses_cost = sum(expense.get('amount', Decimal('0')) for expense in filtered_expenses) - total_overall_cost = total_cost_packed + total_defect_cost + total_expenses_cost - total_profit = total_revenue - total_overall_cost - - total_cutter_salary = Decimal('0') - total_sewer_salary = Decimal('0') - total_packer_salary = Decimal('0') - cutter_rate = to_decimal(config.get('salary_cutter_per_unit', '0')) - sewer_rate = to_decimal(config.get('salary_sewer_per_unit', '0')) - packer_rate = to_decimal(config.get('salary_packer_per_unit', '0')) - - for item in filtered_packed_items: - qty = item.get('quantity', 0) - if qty > 0: - total_cutter_salary += Decimal(qty) * cutter_rate - total_sewer_salary += Decimal(qty) * sewer_rate - total_packer_salary += Decimal(qty) * packer_rate - - calculated_total_salary = total_cutter_salary + total_sewer_salary + total_packer_salary - if total_packed_quantity > 0 and abs(calculated_total_salary - total_salary_cost_packed) > Decimal('0.01') * total_packed_quantity : - logging.warning(f"Calculated salary breakdown ({calculated_total_salary}) differs from total salary in packed items ({total_salary_cost_packed}).") - - production_summary = {} - for item in filtered_packed_items: - product_name = item.get('product_name', 'Unknown Product') - quantity = item.get('quantity', 0) - revenue = item.get('packed_final_price', Decimal('0')) - cost = item.get('packed_total_cost', Decimal('0')) - profit = revenue - cost - if product_name not in production_summary: - production_summary[product_name] = {'quantity': 0, 'revenue': Decimal('0'), 'cost': Decimal('0'), 'profit': Decimal('0')} - production_summary[product_name]['quantity'] += quantity - production_summary[product_name]['revenue'] += revenue - production_summary[product_name]['cost'] += cost - production_summary[product_name]['profit'] += profit - - report_data = { - 'total_packed_qty': total_packed_quantity, 'total_revenue': total_revenue, - 'total_material_cost': total_material_cost_packed, 'total_salary_cost': total_salary_cost_packed, - 'total_cost_packed': total_cost_packed, 'total_defect_cost': total_defect_cost, - 'total_expenses': total_expenses_cost, 'total_overall_cost': total_overall_cost, - 'total_profit': total_profit, 'total_cutter_salary': total_cutter_salary, - 'total_sewer_salary': total_sewer_salary, 'total_packer_salary': total_packer_salary, - 'production_summary': production_summary, 'filtered_packed_items': filtered_packed_items, - 'filtered_defects': filtered_defects, 'filtered_expenses': filtered_expenses, - 'start_date': start_date_dt.strftime('%Y-%m-%d'), 'end_date': end_date_dt.strftime('%Y-%m-%d'), - 'filter_type': filter_type, 'current_day': now.strftime('%Y-%m-%d'), - 'current_month': now.strftime('%Y-%m'), 'current_year': now.year, - 'filter_values': request.args - } - - html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS) - return render_template_string(html, report=report_data) - -ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'txt', 'doc', 'docx', 'xls', 'xlsx'} - -def allowed_file(filename): - return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS - -@app.route('/cloud', methods=['GET', 'POST']) -def cloud_storage(): - data = load_data() - cloud_files = data.get('cloud_files', []) - - if request.method == 'POST': - description = request.form.get('description', '').strip() - if 'file' not in request.files: - flash('Файл не был выбран.', 'warning') - return redirect(url_for('cloud_storage')) - file = request.files['file'] - if file.filename == '': - flash('Файл не был выбран.', 'warning') - return redirect(url_for('cloud_storage')) - - if file and allowed_file(file.filename): - original_filename = secure_filename(file.filename) - file_ext = original_filename.rsplit('.', 1)[1].lower() - stored_filename = f"{uuid.uuid4().hex}.{file_ext}" - file_path = os.path.join(app.config['UPLOAD_FOLDER'], stored_filename) - thumbnail_filename = None - - try: - file.save(file_path) - logging.info(f"File '{original_filename}' saved as '{stored_filename}'") - - if file_ext in {'png', 'jpg', 'jpeg', 'gif'}: - thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'], stored_filename) - thumbnail_filename = create_thumbnail(file_path, thumb_path) - - file_meta = { - 'file_id': uuid.uuid4().hex, 'original_filename': original_filename, - 'stored_filename': stored_filename, 'thumbnail_filename': thumbnail_filename, - 'description': description, 'timestamp': get_current_time().isoformat(), - 'size': os.path.getsize(file_path) - } - cloud_files.append(file_meta) - data['cloud_files'] = cloud_files - save_data(data) - flash(f"Файл '{original_filename}' успешно загружен.", 'success') - upload_db_to_hf(DATA_FILE) - - except Exception as e: - logging.error(f"Error saving file or creating thumbnail: {e}", exc_info=True) - flash(f"Ошибка при загрузке файла: {e}", 'danger') - if os.path.exists(file_path): - try: os.remove(file_path) - except OSError: pass - return redirect(url_for('cloud_storage')) - else: - flash('Недопустимый тип файла.', 'danger') - return redirect(url_for('cloud_storage')) - - search_query = request.args.get('search', '').lower() - if search_query: - filtered_files = [ - f for f in cloud_files - if isinstance(f, dict) and - (search_query in f.get('description', '').lower() or \ - search_query in f.get('original_filename', '').lower()) - ] - else: - filtered_files = [f for f in cloud_files if isinstance(f, dict)] - - filtered_files.sort(key=lambda x: x.get('timestamp', ''), reverse=True) - - html = BASE_TEMPLATE.replace('__TITLE__', "Облачное хранилище").replace('__CONTENT__', CLOUD_CONTENT).replace('__SCRIPTS__', CLOUD_SCRIPTS) - return render_template_string(html, files=filtered_files, search_query=search_query) - -@app.route('/download_file/') -def download_file(filename): - try: - return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True) - except FileNotFoundError: - flash("Файл не найден.", "danger") - return redirect(url_for('cloud_storage')) - except Exception as e: - logging.error(f"Error downloading file {filename}: {e}", exc_info=True) - flash(f"Ошибка при скачивании файла: {e}", "danger") - return redirect(url_for('cloud_storage')) - -@app.route('/thumbnail/') -def get_thumbnail(filename): - try: - return send_from_directory(app.config['THUMBNAIL_FOLDER'], filename) - except FileNotFoundError: - return "Thumbnail not found", 404 - except Exception as e: - logging.error(f"Error serving thumbnail {filename}: {e}") - return "Error getting thumbnail", 500 - -@app.route('/cloud/delete/', methods=['POST']) -def delete_cloud_file(file_id): - data = load_data() - cloud_files = data.get('cloud_files', []) - file_to_delete = None - file_index = -1 - - for i, f in enumerate(cloud_files): - if isinstance(f, dict) and f.get('file_id') == file_id: - file_to_delete = f - file_index = i - break - - if file_to_delete: - stored_filename = file_to_delete.get('stored_filename') - thumb_filename = file_to_delete.get('thumbnail_filename') - file_path = os.path.join(app.config['UPLOAD_FOLDER'], stored_filename) if stored_filename else None - thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'], thumb_filename) if thumb_filename else None - - try: - del cloud_files[file_index] - data['cloud_files'] = cloud_files - save_data(data) - - if file_path and os.path.exists(file_path): - os.remove(file_path) - logging.info(f"Deleted file: {file_path}") - if thumb_path and os.path.exists(thumb_path): - os.remove(thumb_path) - logging.info(f"Deleted thumbnail: {thumb_path}") - - flash(f"Файл '{file_to_delete.get('original_filename', 'N/A')}' успешно удален.", 'success') - upload_db_to_hf(DATA_FILE) - - except Exception as e: - logging.error(f"Error deleting file {file_id}: {e}", exc_info=True) - flash(f"Ошибка при удалении файла: {e}", 'danger') - else: - flash('Файл для удаления не найден.', 'warning') - return redirect(url_for('cloud_storage')) - -ORDERS_CONTENT = """ -
-
Создание заказа
-
-
-
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
-
-
Фурнитура: (Введите название и количество)
-
-
-
- -
-
- -
-
- -
-
-
- -
-
- -
-
-
-
-
Список заказов
-
- -
- - - - - - - - - - - - - - - - - - - {% for order in orders %} - - - - - - - - - - - - - - - {% else %} - - - - {% endfor %} - - -
ID Клиент Модель Ткань Кол-во тканиФурнитураКол-во изделий Размерный рядАванс (сом) Статус Создан Действия
{{ order.id[:8] }}...{{ order.client_name }}{{ order.model_name }}{{ order.fabric_name }}{{ order.fabric_quantity }} -
    - {% for f in order.fittings %} -
  • {{ f.fitting_name }}: {{ f.quantity }} шт.
  • - {% else %} - - - {% endfor %} -
-
{{ order.items_quantity }}{{ order.size_range }}{{ format_currency_py(order.prepayment) }}{{ getStatusText(order.status) }}{{ order.timestamp_created[:16]|replace('T', ' ') }} -
- - {% if order.status != 'completed' %} -
- -
- {% endif %} -
-
Заказы отсутствуют.
-
-
-
-{% for order in orders %} - -{% endfor %} -""" - -ORDERS_SCRIPTS = """ - -""" - -BASE_TEMPLATE = """ - - - - - - __TITLE__ - КШП - - - - - - - -
- {% with messages = get_flashed_messages(with_categories=true) %} - {% if messages %} -
- {% for category, message in messages %} - {% set alert_class = 'alert-' + category if category in ['danger', 'success', 'warning', 'info'] else 'alert-info' %} - - {% endfor %} -
- {% endif %} - {% endwith %} - __CONTENT__ -
-
-
-

© {{ get_current_time().year }} КШП. Все права защищены. ({{ get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z') }})

-
-
- - - - -__SCRIPTS__ - - -""" - -BASE_TEMPLATE_OPERATIONAL = """ - - - - - - __TITLE__ - КШП - - - - - - -
-

__TITLE__

- {% with messages = get_flashed_messages(with_categories=true) %} - {% if messages %} -
- {% for category, message in messages %} - {% set alert_class = 'alert-' + category if category in ['danger', 'success', 'warning', 'info'] else 'alert-info' %} - - {% endfor %} -
- {% endif %} - {% endwith %} - __CONTENT__ -
-
-
-

© {{ get_current_time().year }} КШП. Все права защищены. ({{ get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z') }})

-
-
- - - - -__SCRIPTS__ - - -""" - -PROCUREMENT_CONTENT = """ -
-
Активные заказы (Ожидают закупа)
-
-
- - - - - - - - {% for order in orders %} - - - - - - - {% else %} - - {% endfor %} - -
IDКлиентИзделиеТканьКол-во тканиКол-во изделийРазмерный рядФурнитураСозданДействия
{{ order.id[:8] }}...{{ order.client_name }}{{ order.model_name }}{{ order.fabric_name }}{{ order.fabric_quantity }}{{ order.items_quantity }}{{ order.size_range }} - {% if order.fittings %} -
    - {% for f in order.fittings %}
  • {{ f.fitting_name }}: {{ f.quantity }} шт.
  • {% endfor %} -
- {% else %}Нет фурнитуры{% endif %} -
{{ order.timestamp_created[:16]|replace('T', ' ') }} -
- - -
-
Нет заказов, ожидающих закупа.
-
-
-
-
-
Добавить закупленные материалы
-
-
-
-
-
-
-
-
-
-
-
- -
-
- - -
-
-
-""" - -PROCUREMENT_SCRIPTS = """ - -""" - -CUTTING_CONTENT = """ -
-
Регистрация раскроя
-
-
-
-
- - -
-
-
-
- - -
-
- - -
-
- -
-
-
-
-
-""" - -CUTTING_SCRIPTS = """ - -""" - -NEW_SEWING_CONTENT = """ -
-
Задания на раскрой (Ожидают пошива)
-
- {% if cutting_tasks %} -
- - - - {% for task in cutting_tasks %} - - - - - - - - - {% endfor %} - -
ID ЗаданияТканьОсталось сшить (шт)Всего раскроеноДата раскрояДействие
{{ task.id[:8] }}...{{ task.fabric_name }}{{ task.remaining_quantity }}{{ format_integer_py(task.cut_items_quantity) }}{{ task.timestamp_created[:16] | replace('T', ' ') if task.timestamp_created else 'N/A' }}
-
- {% else %} - - {% endif %} -
-
-
-
Доступная фурнитура на складе
-
- - {% if available_fittings %} -
- - - - {% for fitting in available_fittings %} - - - - {% endfor %} - - -
ID Название Категория В наличии Ед. изм.
{{ fitting.id[:8] }}...{{ fitting.name }}{{ fitting.category | default('Без категории') }}{{ fitting.quantity_str }}{{ fitting.unit }}
-
- {% else %} - - {% endif %} -
-
- -""" - -NEW_SEWING_SCRIPTS = """ - -""" - - -QC_PACKING_CONTENT = """ -
-
ОТК и Упаковка готовых изделий
-
- {% if sewing_tasks %} -
-
-
- - -
-
-
-
- - -
-
- - -
-
- - -
-
-
- -
- {% else %} - - {% endif %} -
-
-""" - -QC_PACKING_SCRIPTS = """ - -""" - -CLIENTS_CONTENT = """ -
-

База клиентов

-
-
-
Добавить нового клиента
-
-
-
-
- - -
-
- - -
-
- - -
-
- -
-
-
-
-
-
-
Список клиентов
-
-
- -
-
- - - - {% for client in clients %} - - - - - {% else %}{% endfor %} - - -
ID Имя / Организация Телефон Адрес Действия
{{ client.id[:8] }}...{{ client.name }}{{ client.phone }}{{ client.address | default('-') | safe }} -
- - - {% if not client.history %} -
- - -
- {% endif %} -
-
Клиенты еще не добавлены.
-
-
-
- -{% for client in clients %} - -{% endfor %} -""" - -CLIENTS_SCRIPTS = """ - -""" - -ADMIN_CONTENT = """ -

Админ-панель

-

Обзор состояния производства и настройки

-
-
Материалы

{{ materials_count }}

позиций на складе (>0)
-
Ожидают пошива

{{ pending_cutting_count }}

заданий раскроя
-
Ожидают ОТК

{{ pending_qc_count }}

заданий пошива ({{ format_integer_py(pending_qc_quantity) }} шт. осталось обработать)
-
Упаковано

{{ format_integer_py(total_packed_count) }}

готовых изделий (ожидают отправки)
-
Готово к отправке

{{ format_integer_py(items_ready_ship_qty) }}

шт. в {{ items_ready_ship_count }} партиях
-
Брак (Всего)

Ткань: {{ total_defect_fabric_m }} м

Фурнитура: {{ total_defect_fittings_pcs }} шт.

Готовые изд.: {{ total_defect_finished_pcs }} шт.

Стоимость: {{ total_defect_cost }} сом

за все время
-
-
-
Настройки зарплат и маржи
-
-
-
-
-
-
-
-
- -
-
-
-
-
Управление категориями материалов
-
-
Добавить
Удалить
{% if categories and categories|reject('equalto', 'Без категории')|list %}
{% else %}

Нет категорий для удаления.

{% endif %}

Существующие:
{% if categories %}
    {% for category in categories %}
  • {{ category }}
  • {% endfor %}
{% else %}

Нет категорий.

{% endif %} -
-
-
-
Дополнительные расходы
-
-
-
-
-
-
-
Журнал доп. расходов:
-
- {% for expense in expenses|sort(attribute='timestamp', reverse=True) %} - - - - {% else %}{% endfor %} -
IDОписаниеСумма (сом)ДатаДействия
{{ expense.id[:8] }}...{{ expense.description }}{{ format_currency_py(expense.amount) }}{{ expense.timestamp[:16]|replace('T',' ') if expense.timestamp else 'N/A' }}
Дополнительные расходы еще не добавлялись.
-
-
- -
-
-
Список материалов
- -
- - - {% for m in materials|sort(attribute='name') %} - - - {% else %}{% endfor %} - -
ID Название Категория Тип Кол-во Ед.изм.Цена/ед Расход/ед Добавлен Обновлен
{{ m.id[:8] }}...{{ m.name }}{{ m.category | default('Без категории') }}{{ 'Ткань' if m.type == 'fabric' else 'Фурнитура' }}{{ format_currency_py(m.quantity) if m.type == 'fabric' else format_integer_py(m.quantity) }}{{ m.unit }}{{ format_currency_py(m.price_per_unit) }}{{ format_currency_py(m.material_per_unit) }}{{ m.timestamp_added[:16] | replace('T', ' ') if m.timestamp_added else 'N/A' }}{{ m.timestamp_last_updated[:16] | replace('T', ' ') if m.timestamp_last_updated else 'N/A' }}
Нет материалов в наличии.
-
-
-
Задания на раскрой
-
- - - {% for task in cutting_tasks|sort(attribute='timestamp_created', reverse=True) %} - - - {% else %}{% endfor %} -
IDТканьРаскроеноСшитоРасход тканиСтатусСозданоЗавершено
{{ task.id[:8] }}...{{ task.fabric_name }}({{ task.fabric_id[:6] }}...){{ format_integer_py(task.cut_items_quantity) }}{{ format_integer_py(task.sewn_quantity) }}{{ format_currency_py(task.fabric_used) }} {{ task.fabric_unit }}{{ getStatusText(task.status) }}{{ task.timestamp_created[:16] | replace('T', ' ') if task.timestamp_created else 'N/A' }}{{ task.timestamp_completed[:16] | replace('T', ' ') if task.timestamp_completed else '-' }}
Нет заданий на раскрой.
-
-
-
Задания на пошив
-
- - - {% for task in sewing_tasks|sort(attribute='timestamp_created', reverse=True) %} - - - - - - {% else %}{% endfor %} -
IDИзделиеСшитоИсп. фурн. (Стоимость)Брак пошиваСтатусУпак./Брак ОТКСозданоЗавершеноРаскрой ID
{{ task.id[:8] }}...{{ task.product_name }}{{ format_integer_py(task.sewn_quantity) }} - {% if task.fittings_consumed is iterable and task.fittings_consumed is not string %} -
    {% for f in task.fittings_consumed %}{% if f is mapping %}
  • {{ f.get('fitting_name','?') }}: {{ format_integer_py(f.get('quantity_used',0)) }} шт.
  • {% endif %}{% endfor %}{% if task.fittings_cost and to_decimal(task.fittings_cost) != 0 %}
  • Итого: {{format_currency_py(task.fittings_cost)}} сом
  • {% endif %}
- {% else %}-{% endif %} -
- {% if task.defects_reported is iterable and task.defects_reported is not string %} -
    {% for d in task.defects_reported %}{% if d is mapping %}
  • {{ d.get('material_name','?') }}: {% set dtype = d.get('type') %}{% set dqty = d.get('quantity',0) %}{% if dtype == 'fabric' %}{{ format_currency_py(dqty) }}{% else %}{{ format_integer_py(dqty) }}{% endif %} {{ d.get('unit','?') }}
  • {% endif %}{% endfor %}
- {% else %}-{% endif %} -
{{ getStatusText(task.status) }}{{ format_integer_py(task.qc_packed_quantity) }} / {{ format_integer_py(task.qc_defective_quantity) }}{{ task.timestamp_created[:16] | replace('T', ' ') if task.timestamp_created else 'N/A' }}{{ task.timestamp_completed[:16] | replace('T', ' ') if task.timestamp_completed else '-' }}{{ task.cutting_task_id[:8] }}...
Нет заданий на пошив.
-
-
-
Упакованные изделия (все)
-
- - - {% for item in packed_items|sort(attribute='timestamp_packed', reverse=True) %} - {% set qty = item.quantity if item.quantity > 0 else 1 %} - {% set cost_per_item = item.packed_total_cost / qty if qty > 0 else 0 %} - {% set price_per_item = item.packed_final_price / qty if qty > 0 else 0 %} - - - - - {% else %}{% endfor %} -
IDНазваниеКол-воСебест. (ед.)Цена (ед.)Общая себест.Общая ценаСтатусДата упак.Детали отправкиПошив ID
{{ item.id[:8] }}...{{ item.product_name }}{{ format_integer_py(item.quantity) }}{{ format_currency_py(cost_per_item) }}{{ format_currency_py(price_per_item) }}{{ format_currency_py(item.packed_total_cost) }}{{ format_currency_py(item.packed_final_price) }}{{ getStatusText(item.status) }}{{ item.timestamp_packed[:16] | replace('T', ' ') if item.timestamp_packed else 'N/A' }} - {% set details = item.shipment_details %}{% if details is mapping %}{{ details.get('timestamp')[:16] | replace('T',' ') if details.get('timestamp') else '' }}{% if details.get('type') == 'client' %}
Клиент: {{ details.get('client_name', 'N/A')}}{% elif details.get('type') == 'dor_doi_point' %}
Назначение: {{ details.get('destination', 'Дордой') }}{% endif %}
{% else %}-{% endif %} -
{{ item.sewing_task_id[:8] }}...
Нет упакованных изделий.
-
-
-
Готово к отправке
- {% if items_ready_to_ship %} -
- - - {% for item in items_ready_to_ship|sort(attribute='timestamp_packed', reverse=True) %} - - - - {% endfor %} -
IDИзделиеВ наличииСебест.(общ)Цена (общ)Дата упак.Действия
{{ item.id[:8] }}...{{ item.product_name }}{{ format_integer_py(item.quantity) }}{{ format_currency_py(item.packed_total_cost) }}{{ format_currency_py(item.packed_final_price) }}{{ item.timestamp_packed[:16] | replace('T', ' ') if item.timestamp_packed else 'N/A' }} -
- -
-
-
- -
-
-
-
- {% else %}{% endif %} -
-
-
-
История отправок на Дордой
- {% if dordoi_shipments %} -
- {% for shipment in dordoi_shipments %} - - - - - {% endfor %} -
ID ОтправкиДатаТоварыИсходный ID уп.
{{ shipment.shipment_id[:8] }}...{{ shipment.timestamp_dt.strftime('%Y-%m-%d %H:%M') if shipment.timestamp_dt else shipment.timestamp[:16]|replace('T',' ') }}{% if shipment.items is iterable and shipment.items is not string and shipment.items %}
    {% for item in shipment.items %}
  • {{ item.get('product_name', '?') }}: {{ item.get('quantity', '?') }} шт.
  • {% endfor %}
{% else %}-{% endif %}
{{ shipment.packed_item_id[:8] }}...
- {% else %}{% endif %} -
-
-
-
Журнал брака
-
- {% for defect in defect_log|sort(attribute='timestamp', reverse=True) %} - - - {% else %}{% endfor %} -
IDМатериал/ИзделиеТипКол-воЕд.СтоимостьЭтапПричинаДатаПошив ID
{{ defect.log_id[:8] }}...{{ defect.material_name }} {% if defect.material_id %}({{ defect.material_id[:6] }}...){% endif %}{{ defect.type|replace('_', ' ')|title }}{{ defect.quantity_view }}{{ defect.unit }}{{ format_currency_py(defect.cost_dec) }}{{ defect.stage|replace('_', ' ')|title }}{{ defect.reason | default('-') }}{{ defect.timestamp[:16] | replace('T', ' ') if defect.timestamp else 'N/A' }}{{ defect.sewing_task_id[:8] if defect.sewing_task_id else 'N/A' }}...
Записи о браке отсутствуют.
-
-
-""" - -ADMIN_SCRIPTS = """ - -""" - -REPORTS_CONTENT = """ -
-

Отчеты

-
-
-
Фильтр периода
-
-
-
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- -
-
-
-
-
-

Отчет за период: {{ report.start_date }} - {{ report.end_date }}

-
-
-
-
Выручка

{{ format_currency_py(report.total_revenue) }}

сом ({{ format_integer_py(report.total_packed_qty) }} шт. упаковано в период)
-
-
-
-
-
Прибыль

{{ format_currency_py(report.total_profit) }}

сом (Выручка - Затраты)
-
-
-
-
-
Затраты (Общие)

{{ format_currency_py(report.total_overall_cost) }}

сом (Себест.Упак.+Брак+Доп.) (Нажмите для деталей)
-
-
-
-
-
Затраты на брак

{{ format_currency_py(report.total_defect_cost) }}

сом ({{ report.filtered_defects|length }} записей)
-
-
-
-
-
Себестоимость (Упак.)

Материалы: {{ format_currency_py(report.total_material_cost) }} сом

Зарплаты: {{ format_currency_py(report.total_salary_cost) }} сом

Итого: {{ format_currency_py(report.total_cost_packed) }} сом

За {{ format_integer_py(report.total_packed_qty) }} шт. (Нажмите для деталей ЗП)
-
-
-
-
-
Доп. расходы

{{ format_currency_py(report.total_expenses) }}

сом ({{ report.filtered_expenses|length }} записей)
-
-
-
- -
-
-
Сводка по продуктам за период (по дате упаковки)
-
- - - {% for name, summary in report.production_summary.items() %} - {% set avg_profit = (summary.profit / summary.quantity) if summary.quantity > 0 else 0 %} - - - {% else %}{% endfor %} -
ПродуктУпаковано (шт)Выручка (сом)Себестоимость (сом)Прибыль (сом)Средняя прибыль/шт
{{ name }}{{ format_integer_py(summary.quantity) }}{{ format_currency_py(summary.revenue) }}{{ format_currency_py(summary.cost) }}{{ format_currency_py(summary.profit) }}{{ format_currency_py(avg_profit) }}
Нет данных об упакованных товарах за этот период.
-
-
-
Упакованные изделия за период
-
- - - {% for item in report.filtered_packed_items|sort(attribute='timestamp_packed', reverse=True) %} - {% set qty = item.quantity if item.quantity > 0 else 1 %} - {% set cost_per_item = item.packed_total_cost / qty if qty > 0 else 0 %} - {% set price_per_item = item.packed_final_price / qty if qty > 0 else 0 %} - - - - - {% else %}{% endfor %} -
IDНазваниеКол-воСебест. (ед.)Цена (ед.)Общ. себест.Общ. ценаДата упак.СтатусДетали отправкиПошив ID
{{ item.id[:8] }}...{{ item.product_name }}{{ format_integer_py(item.quantity) }}{{ format_currency_py(cost_per_item) }}{{ format_currency_py(price_per_item) }}{{ format_currency_py(item.packed_total_cost) }}{{ format_currency_py(item.packed_final_price) }}{{ item.timestamp_packed[:16] | replace('T', ' ') if item.timestamp_packed else 'N/A' }}{{ getStatusText(item.status) }} - {% set details = item.shipment_details %}{% if details is mapping %}{{ item.shipment_time_dt.strftime('%Y-%m-%d %H:%M') if item.shipment_time_dt else details.get('timestamp', '')[:16]|replace('T',' ') }}{% if details.get('type') == 'client' %}
Клиент: {{ details.get('client_name', 'N/A')}}{% elif details.get('type') == 'dor_doi_point' %}
Назначение: {{ details.get('destination', 'Дордой') }}{% endif %}
{% elif item.status == 'packed_ready_to_ship' %} -{% else %} -{% endif %} -
{{ item.sewing_task_id[:8] }}...
Нет упакованных изделий за этот период.
-
-
-
Брак за период
-
- - - {% for defect in report.filtered_defects|sort(attribute='timestamp', reverse=True) %} - - - {% else %}{% endfor %} -
IDМатериал/ИзделиеТипКол-воЕд.СтоимостьЭтапПричинаДатаПошив ID
{{ defect.log_id[:8] }}...{{ defect.material_name }} {% if defect.material_id %}({{ defect.material_id[:6] }}...){% endif %}{{ defect.type|replace('_', ' ')|title }}{{ defect.quantity_view }}{{ defect.unit }}{{ format_currency_py(defect.cost_dec) }}{{ defect.stage|replace('_', ' ')|title }}{{ defect.reason | default('-') }}{{ defect.timestamp[:16] | replace('T', ' ') if defect.timestamp else 'N/A' }}{{ defect.sewing_task_id[:8] if defect.sewing_task_id else 'N/A' }}...
Нет записей о браке за этот период.
-
-
-
Доп. расходы за период
-
- - - {% for expense in report.filtered_expenses|sort(attribute='timestamp', reverse=True) %} - - - - {% else %}{% endfor %} -
IDОписаниеСумма (сом)ДатаДействия
{{ expense.id[:8] }}...{{ expense.description }}{{ format_currency_py(expense.amount) }}{{ expense.timestamp[:16]|replace('T',' ') if expense.timestamp else 'N/A' }}
Нет доп. расходов за этот период.
-
-
- - -""" - -REPORTS_SCRIPTS = """ - -""" - -CLOUD_CONTENT = """ -
-

Облачное хранилище

-
-
-
Загрузить файл
-
-
-
-
Допустимые форматы: png, jpg, jpeg, gif, pdf, txt, doc, docx, xls, xlsx. Макс. размер: 16MB.
- -
-
-
-
-
Список файлов
-
-
- {% if files %} -
- {% for file in files %} -
-
- {% if file.thumbnail_filename %} - Миниатюра - {% else %}
{% endif %} -
-
{{ file.original_filename }}
- {% if file.description %}

{{ file.description }}

{% endif %} -

Размер: {{ (file.size/1024)|round(1) }} КБ

-

Загружен: {{ file.timestamp[:10] }}

-
-
-
-
- {% endfor %} - -
- {% else %}{% endif %} -
-
-""" - -CLOUD_SCRIPTS = """ - -""" - -ADVANCES_CONTENT = """ -
-
Выдача аванса
-
-
-
-
- - -
-
- - -
-
- - -
-
- -
-
-
-
-
История авансов
-
-
- - - - {% for advance in advances %} - - - - - - - - {% else %}{% endfor %} - -
Дата выдачиСотрудникДолжностьСуммаСтатусДействия
{{ advance.timestamp[:16]|replace('T', ' ') }}{{ advance.employee_name }}{% if advance.role == 'cutter' %}Раскройщик{% elif advance.role == 'sewer' %}Швея{% elif advance.role == 'packer' %}Упаковщик{% else %}{{ advance.role }}{% endif %}{{ format_currency_py(advance.amount) }}{% if advance.is_processed %}Вычтено из ЗП{% else %}Не вычтено{% endif %}
История авансов пуста
-
-
-
-""" - -ADVANCES_SCRIPTS = """ - -""" - -@app.context_processor -def inject_utils(): - return { - 'get_current_time': get_current_time, - 'getStatusText': getStatusText, - 'getStatusClass': getStatusClass, - 'format_currency_py': format_currency_py, - 'format_integer_py': format_integer_py, - 'to_decimal': to_decimal - } - -if __name__ == '__main__': - backup_thread = threading.Thread(target=periodic_backup, daemon=True) - backup_thread.start() - - try: - logging.info("Initial data loading...") - load_data() - load_client_data() - logging.info("Data loaded/initialized successfully.") - except Exception as e: - logging.critical(f"Failed to load databases on startup: {e}", exc_info=True) - - logging.info("Starting Flask application on http://0.0.0.0:7860") - app.run(debug=False, host='0.0.0.0', port=7860, use_reloader=False) - -# --- END OF FILE app.py --- \ No newline at end of file