diff --git "a/app.py" "b/app.py" deleted file mode 100644--- "a/app.py" +++ /dev/null @@ -1,5318 +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 # Для генерации уникальных ID -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) # Необходим для flash сообщений -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 # Ограничение 16MB на загрузку файла - -# --- Настройки Hugging Face --- -# !!! ВАЖНО: Установите переменные окружения HF_TOKEN_WRITE и HF_TOKEN_READ !!! -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" # !!! Обновленный REPO_ID !!! - -# --- Часовой пояс --- -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() - -# --- Новые статусы заказа --- -STATUS_PENDING_PROCUREMENT = 'pending_procurement' # Ожидает закупа -STATUS_PENDING_CUTTING = 'pending_cutting' # Ожидает раскроя (после закупа) -STATUS_PENDING_SEWING = 'pending_sewing' # Ожидает пошива (после раскроя) -STATUS_PENDING_QC = 'pending_qc' # Ожидает ОТК (после пошива) -STATUS_PACKED_READY = 'packed_ready_to_ship' # Упаковано, готово к отправке -STATUS_SHIPPED_CLIENT = 'shipped_client' # Отправлено клиенту -STATUS_SHIPPED_DORDOI = 'shipped_dordoi' # Отправлено на Дордой -STATUS_COMPLETED = 'completed' # Завершено (возможно, объединить с shipped?) -STATUS_CANCELLED = 'cancelled' # Отменен - -# --- Вспомогательные функции для работы с данными --- - -def get_current_time(): - """Возвращает текущее время в Бишкекском часовом поясе.""" - return datetime.now(BISHKEK_TZ) - -def load_data(): - """Загружает основные данные из JSON файла, скачивая с Hugging Face при необходимости.""" - with data_lock: - # Попытка скачивания основного файла данных - try: - logging.info(f"Попытка скачивания {DATA_FILE} из репозитория {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} успешно скачан из Hugging Face.") - except RepositoryNotFoundError: - logging.warning(f"Репозиторий {REPO_ID} не найден. Проверяем локальный {DATA_FILE}.") - except HfHubHTTPError as e: - if e.response.status_code == 404: - logging.warning(f"Файл {DATA_FILE} не найден в репозитории {REPO_ID}. Проверяем локальный файл.") - else: - logging.error(f"Ошибка HTTP при скачивании {DATA_FILE} из Hugging Face: {e}") - except Exception as e: - logging.error(f"Неизвестная ошибка при скачивании {DATA_FILE} из Hugging Face: {e}") - - # Загрузка из локального файла - try: - with open(DATA_FILE, 'r', encoding='utf-8') as file: - data = json.load(file) - logging.info("Основные данные успешно загружены из локального JSON.") - if not isinstance(data, dict): - logging.warning(f"{DATA_FILE} не является словарем, инициализация пустой структурой.") - 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"В {DATA_FILE} отсутствует ключ '{key}'. Инициализация значением по умолчанию.") - data[key] = default_data[key] - changed = True - elif not isinstance(data[key], type(default_data[key])): - logging.warning(f"В {DATA_FILE} ключ '{key}' имеет неверный тип ({type(data[key])} вместо {type(default_data[key])}). Инициализация значением по умолчанию.") - data[key] = default_data[key] - changed = True - - # Дополнительно проверяем config - if 'config' not in data or not isinstance(data['config'], dict): - logging.warning(f"В {DATA_FILE} отсутствует или некорректен ключ 'config'. Инициализация значением по умолчанию.") - 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"В {DATA_FILE}['config'] отсутствует ключ '{config_key}'. Инициализация значением по умолчанию.") - data['config'][config_key] = default_value - changed = True - elif not isinstance(data['config'][config_key], str): # В конфиге храним строки - logging.warning(f"В {DATA_FILE}['config'] ключ '{config_key}' имеет неверный тип ({type(data['config'][config_key])} вместо str). Попытка преобразования в строку.") - try: - data['config'][config_key] = str(data['config'][config_key]) - changed = True # Изменили тип - except Exception: - logging.error(f"Не удалось преобразовать значение config '{config_key}' в строку. Установка значения по умолчанию.") - data['config'][config_key] = default_value - changed = True - - # Проверка и преобразование данных заказов (если они есть) - if 'orders' in data and isinstance(data['orders'], list): - valid_orders = [] - orders_changed = False - for order in data['orders']: - if isinstance(order, dict) and 'id' in order: - # TODO: Добавить здесь более строгую валидацию структуры заказа - # при загрузке, если это необходимо, аналогично проверке клиентов - valid_orders.append(order) - else: - logging.warning(f"Обнаружен некорректный элемент в списке 'orders'. Пропущен: {order}") - orders_changed = True - if orders_changed: - data['orders'] = valid_orders - changed = True - - - # Сохраняем, если структура была изменена при загрузке - if changed: - logging.info(f"Структура файла {DATA_FILE} была обновлена при загрузке. Сохранение изменений...") - save_data(data) # Вызываем save_data здесь же, внутри lock - - return data - except FileNotFoundError: - logging.warning(f"Локальный файл {DATA_FILE} не найден. Инициализация пустой структурой.") - return initialize_data_structure() - except json.JSONDecodeError: - logging.error(f"Ошибка декодирования JSON в файле {DATA_FILE}. Инициализация пустой структурой.") - 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"Поврежденный файл {DATA_FILE} переименован в {bad_file_path}") - except Exception as backup_err: - logging.error(f"Не удалось создать бэкап поврежденного файла {DATA_FILE}: {backup_err}") - return initialize_data_structure() - except Exception as e: - logging.error(f"Неизвестная ошибка при загрузке локальных основных данных: {e}", exc_info=True) - return initialize_data_structure() - -def save_data(data): - """Сохраняет основные данные в JSON файл.""" - # Эта функция вызывается из load_data или маршрутов, уже под data_lock - 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"Основные данные успешно сохранены в локальный файл {DATA_FILE}.") - except Exception as e: - logging.error(f"Критическая ошибка при сохранении основных данных: {e}", exc_info=True) - if os.path.exists(temp_file): - try: os.remove(temp_file) - except OSError as rm_err: logging.error(f"Не удалось удалить временный файл {temp_file}: {rm_err}") - -def load_client_data(): - """Загружает данные клиентов из JSON файла, скачивая с Hugging Face при необходимости.""" - with client_data_lock: - try: - logging.info(f"Попытка скачивания {CLIENT_DATA_FILE} из репозитория {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} успешно скачан из Hugging Face.") - except RepositoryNotFoundError: logging.warning(f"Репозиторий {REPO_ID} не найден. Проверяем локальный {CLIENT_DATA_FILE}.") - except HfHubHTTPError as e: - if e.response.status_code == 404: logging.warning(f"Файл {CLIENT_DATA_FILE} не найден в репозитории {REPO_ID}. Проверяем локальный файл.") - else: logging.error(f"Ошибка HTTP при скачивании {CLIENT_DATA_FILE} из Hugging Face: {e}") - except Exception as e: logging.error(f"Неизвестная ошибка при скачивании {CLIENT_DATA_FILE} из Hugging Face: {e}") - - try: - with open(CLIENT_DATA_FILE, 'r', encoding='utf-8') as file: - clients = json.load(file) - logging.info("Данные клиентов успешно загружены из локального JSON.") - if not isinstance(clients, list): - logging.warning(f"{CLIENT_DATA_FILE} не является списком, инициализация пустым списком.") - return [] - # Проверка структуры каждого клиента - valid_clients = [] - changed = False - for client in clients: - if isinstance(client, dict) and 'id' in client and 'name' in client: - client_changed = False - # Проверка и исправление history, если необходимо - if 'history' not in client or not isinstance(client.get('history'), list): - logging.warning(f"Обнаружен некорректный формат 'history' для клиента {client.get('id')} при загрузке. Инициализировано пустым списком.") - client['history'] = [] - client_changed = True - else: - # Дополнительная проверка элементов внутри history - valid_history = [] - history_changed = False - for record in client['history']: - if isinstance(record, dict) and 'timestamp' in record: - record_changed = False - # Проверка и исправление items - if 'items' not in record or not isinstance(record.get('items'), list): - logging.warning(f"Обнаружен некорректный формат 'items' в записи истории клиента {client.get('id')}, shipment {record.get('shipment_id', 'N/A')}. Инициализировано пустым списком.") - record['items'] = [] - record_changed = True - valid_history.append(record) - if record_changed: history_changed = True - else: - logging.warning(f"Обнаружена некорректная запись в истории клиента {client.get('id')}. Пропущена: {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"Обнаружена некорректная запись клиента в {CLIENT_DATA_FILE}. Пропущена: {client}") - changed = True # Считаем изменением, т.к. запись удалена - - # Сохраняем, если структура была изменена при загрузке - if changed: - logging.info(f"Структура файла {CLIENT_DATA_FILE} была обновлена при загрузке. Сохранение изменений...") - save_client_data(valid_clients) # Вызываем save_client_data здесь же, внутри lock - - return valid_clients - except FileNotFoundError: logging.warning(f"Локальный файл {CLIENT_DATA_FILE} не найден. Инициализация пустым списком."); return [] - except json.JSONDecodeError: - logging.error(f"Ошибка декодирования JSON в файле {CLIENT_DATA_FILE}. Инициализация пустым списком.") - 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"Поврежденный файл {CLIENT_DATA_FILE} переименован в {bad_file_path}") - except Exception as backup_err: - logging.error(f"Не удалось создать бэкап поврежденного файла {CLIENT_DATA_FILE}: {backup_err}") - return [] - except Exception as e: logging.error(f"Неизвестная ошибка при загрузке локальных данных клиентов: {e}", exc_info=True); return [] - -def save_client_data(clients): - """Сохраняет данные клиентов в JSON файл.""" - # Эта функция вызывается из load_client_data или маршрутов, уже под client_data_lock - if not isinstance(clients, list): - logging.error(f"Попытка сохранить не-список как {CLIENT_DATA_FILE}. Операция отменена.") - return - for i, client in enumerate(clients): - if not isinstance(client, dict) or 'id' not in client: - logging.error(f"Попытка сохранить некорректный объект клиента на позиции {i} в {CLIENT_DATA_FILE}. Операция отменена.") - return - if 'history' in client and not isinstance(client['history'], list): - logging.error(f"Попытка сохранить некорректный history (не список) для клиента {client.get('id')} в {CLIENT_DATA_FILE}. Операция отменена.") - 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"Попытка сохранить некорректную запись history (не словарь) на позиции {j} для клиента {client.get('id')} в {CLIENT_DATA_FILE}. Операция отменена.") - return - if 'items' in record and not isinstance(record['items'], list): - logging.error(f"Попытка сохранить некорректные items (не список) в записи history {j} для клиента {client.get('id')} в {CLIENT_DATA_FILE}. Операция отменена.") - 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) # Не используем DecimalEncoder здесь - os.replace(temp_file, CLIENT_DATA_FILE) - logging.info(f"Данные клиентов успешно сохранены в локальный файл {CLIENT_DATA_FILE}.") - except Exception as e: - logging.error(f"Критическая ошибка при сохранении данных клиентов: {e}", exc_info=True) - if os.path.exists(temp_file): - try: os.remove(temp_file) - except OSError as rm_err: logging.error(f"Не удалось удалить временный файл {temp_file}: {rm_err}") - -def initialize_data_structure(): - """Возвращает пустую структуру основных данных по умолчанию.""" - return { - 'materials': [], - 'categories': [], - 'orders': [], # Основной список заказов, которые проходят этапы - 'defect_log': [], - 'expenses': [], - 'dordoi_shipments': [], - 'cloud_files': [], - '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(): - """Возвращает инициализированный объект HfApi.""" - if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE": - logging.warning("Токен HF_TOKEN_WRITE не установлен. Загрузка на Hugging Face будет недоступна.") - return None - try: return HfApi() - except Exception as e: logging.error(f"Ошибка инициализации HfApi: {e}"); return None - -def upload_db_to_hf(filepath=DATA_FILE): - """Загружает указанный локальный файл данных на Hugging Face.""" - api = get_hf_api() - if not api: logging.warning(f"HfApi не инициализирован. Загрузка {filepath} на Hugging Face пропущена."); return - if not os.path.exists(filepath): logging.warning(f"Локальный файл {filepath} не найден. Загрузка на Hugging Face пропущена."); return - try: - filename = os.path.basename(filepath) - commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z') - logging.info(f"Начало загрузки файла {filename} на Hugging Face...") - # Используем run_as_future=True для асинхронной загрузки, чтобы не блокировать основной поток - 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"Автоматическое резервное копирование {filename} {commit_time}", - run_as_future=True - ) - -# This should be part of an HTML template string, not directly in Python code - # Example of how this should appear in a template: - ''' - {# Use .get() method for safe access or check if attribute exists #} - {% if order.fabric_details is defined %} - {# Access fabric_details attributes safely #} - {{ order.fabric_details.get('name', 'Не указано') }} - {% else %} - Информация о ткани отсутствует - {% endif %} - ''' - logging.info(f"Загрузка файла {filename} на Hugging Face инициирована.") - except RepositoryNotFoundError: logging.error(f"Ошибка загрузки: Репозиторий {REPO_ID} не найден на Hugging Face.") - except Exception as e: logging.error(f"Ошибка при инициации загрузки {filepath} на Hugging Face: {e}") - -def periodic_backup(): - """Периодически вызывает upload_db_to_hf для обоих файл��в.""" - logging.info("Запуск потока периодического резервного копирования.") - while True: - backup_interval = 1800 # 30 минут - logging.debug(f"Периодический бэкап спит {backup_interval} секунд...") - time.sleep(backup_interval) - logging.info("Запуск планового резервного копирования...") - try: - # Блокировка не обязательна, так как upload_db_to_hf читает существующий файл - if os.path.exists(DATA_FILE): - upload_db_to_hf(DATA_FILE) - else: - logging.warning(f"Файл {DATA_FILE} не найден для планового бэкапа.") - - if os.path.exists(CLIENT_DATA_FILE): - upload_db_to_hf(CLIENT_DATA_FILE) - else: - logging.warning(f"Файл {CLIENT_DATA_FILE} не найден для планового бэкапа.") - logging.info("Плановое резервное копирование завершено.") - except Exception as e: - logging.error(f"Ошибка во время планового резервного копирования: {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'): - """Безопасно преобразует строку в Decimal.""" - if value_str is None or value_str == '': return Decimal(default) - try: return Decimal(str(value_str).replace(',', '.')) - except InvalidOperation: logging.warning(f"Не удалось преобразовать '{value_str}' в Decimal. Возвращено {default}."); return Decimal(default) - -def parse_iso_datetime(timestamp_str): - """Преобразует строку ISO в объект datetime со знанием часового пояса.""" - 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: - # Если зона не указана, считаем UTC и конвертируем в Бишкек - return pytz.utc.localize(dt).astimezone(BISHKEK_TZ) - else: - # Если зона указана, просто конвертируем в Бишкек - return dt.astimezone(BISHKEK_TZ) - except (ValueError, TypeError) as e: - logging.warning(f"Не удалось разобрать дату: '{timestamp_str}'. Ошибка: {e}") - return None - -def find_order_by_id(order_id): - """Ищет заказ по ID.""" - data = load_data() - orders = data.get('orders', []) - for order in orders: - if isinstance(order, dict) and order.get('id') == order_id: - # Преобразование числовых полей в Decimal/int при необходимости - order_copy = order.copy() - # Пример преобразования (добавьте другие поля по мере необходимости) - order_copy['items_quantity'] = int(to_decimal(order_copy.get('items_quantity', '0'))) - order_copy['prepayment'] = to_decimal(order_copy.get('prepayment', '0.00')) - # Преобразование деталей этапов - if 'cutting_details' in order_copy and order_copy['cutting_details']: - order_copy['cutting_details']['fabric_used'] = to_decimal(order_copy['cutting_details'].get('fabric_used', '0.00')) - order_copy['cutting_details']['cut_quantity'] = int(to_decimal(order_copy['cutting_details'].get('cut_quantity', '0'))) - order_copy['cutting_details']['material_cost'] = to_decimal(order_copy['cutting_details'].get('material_cost', '0.00')) - order_copy['cutting_details']['cutter_salary_cost'] = to_decimal(order_copy['cutting_details'].get('cutter_salary_cost', '0.00')) - if 'sewing_details' in order_copy and order_copy['sewing_details']: - order_copy['sewing_details']['sewn_quantity'] = int(to_decimal(order_copy['sewing_details'].get('sewn_quantity', '0'))) - order_copy['sewing_details']['fittings_cost'] = to_decimal(order_copy['sewing_details'].get('fittings_cost', '0.00')) - order_copy['sewing_details']['sewer_salary_cost'] = to_decimal(order_copy['sewing_details'].get('sewer_salary_cost', '0.00')) - # Обработка вложенных fitting_consumed и sewing_defects если нужно - if 'qc_packing_details' in order_copy and order_copy['qc_packing_details']: - order_copy['qc_packing_details']['packed_quantity'] = int(to_decimal(order_copy['qc_packing_details'].get('packed_quantity', '0'))) - order_copy['qc_packing_details']['qc_defective_quantity'] = int(to_decimal(order_copy['qc_packing_details'].get('qc_defective_quantity', '0'))) - order_copy['qc_packing_details']['packer_salary_cost'] = to_decimal(order_copy['qc_packing_details'].get('packer_salary_cost', '0.00')) - order_copy['qc_packing_details']['total_material_cost'] = to_decimal(order_copy['qc_packing_details'].get('total_material_cost', '0.00')) - order_copy['qc_packing_details']['total_salary_cost'] = to_decimal(order_copy['qc_packing_details'].get('total_salary_cost', '0.00')) - order_copy['qc_packing_details']['total_cost'] = to_decimal(order_copy['qc_packing_details'].get('total_cost', '0.00')) - order_copy['qc_packing_details']['margin'] = to_decimal(order_copy['qc_packing_details'].get('margin', '0.00')) - order_copy['qc_packing_details']['final_price'] = to_decimal(order_copy['qc_packing_details'].get('final_price', '0.00')) - if 'shipment_details' in order_copy and order_copy['shipment_details']: - order_copy['shipment_details']['quantity_shipped'] = int(to_decimal(order_copy['shipment_details'].get('quantity_shipped', '0'))) - order_copy['shipment_details']['quantity_remaining'] = int(to_decimal(order_copy['shipment_details'].get('quantity_remaining', '0'))) - - - return order_copy - return None - -def find_item_by_id(item_id, item_list_name): - """Обобщенная функция для поиска элемента по ID в НЕ-заказах (материалы, брак и т.д.).""" - data = load_data() # Загружаем свежие данные при каждом поиске - items = data.get(item_list_name, []) - if not isinstance(items, list): # Доп. проверка - logging.error(f"Ожидался список для '{item_list_name}', но получен {type(items)}. Возврат None.") - return None - - for item in items: - if not isinstance(item, dict): # Пропускаем не-словари в списке - logging.warning(f"Обнаружен не-словарь в списке '{item_list_name}': {item}. Пропущен.") - continue - - # Проверяем разные возможные ключи ID - 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'] - int_fields = ['items_per_unit'] - # Удалены cutting_tasks, sewing_tasks, qc_packing_items - elif item_list_name == 'expenses': - decimal_fields = ['amount'] - elif item_list_name == 'defect_log': - decimal_fields = ['cost'] # Основное поле 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 # Decimal для расчетов - 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 # 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 - # Для cloud_files преобразование не требуется - - # Применяем преобразования - 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}' отсутствует в {item_list_name} ID {item_id}. Установлено '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}' отсутствует в {item_list_name} ID {item_id}. Установлено 0.") - - except Exception as conversion_error: - logging.error(f"Ошибка преобразования типов для {item_list_name} ID {item_id}: {conversion_error}", exc_info=True) - return None # Возвращаем None при ошибке преобразования - - return item_copy - return None # Элемент не найден - -def find_client_by_id(client_id): - """Ищет клиента по ID в базе клиентов.""" - clients = load_client_data() # Загружаем свежие и проверенные данные - for client in clients: # clients уже проверен на list в load_client_data - # client уже проверен на dict в load_client_data - if client.get('id') == client_id: - client_copy = client.copy() - # Преобразуем таймстемпы истории для удобства - # history уже проверен на list и его содержимое на dict в load_client_data - if 'history' in client_copy: - for record in client_copy['history']: - # items уже проверен на list в load_client_data - 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) - # Сохраняем в JPEG для экономии места, игнорируем ошибки если формат не поддерживается - try: - img.save(thumb_path, "JPEG") - logging.info(f"Создана миниатюра: {thumb_path}") - return os.path.basename(thumb_path) # Возвращаем имя файла миниатюры - except OSError as e: - # Если JPEG не поддерживается (например, для GIF), пытаемся сохранить в PNG - try: - img.save(thumb_path, "PNG") - logging.info(f"Создана миниатюра (PNG): {thumb_path}") - return os.path.basename(thumb_path) - except Exception as png_e: - logging.error(f"Не удалось сохранить миниатюру как PNG для {image_path}: {png_e}") - return None - except Exception as e: - logging.error(f"Не удалось сохранить миниатюру как JPEG для {image_path}: {e}") - return None - - except Exception as e: - logging.error(f"Ошибка при создании миниатюры для {image_path}: {e}") - return None - -# --- Python Helper Functions for Formatting Numbers --- -def format_currency_py(value): - """Formats a Decimal or string representation as currency (Python side).""" - 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): - """Formats a Decimal or string representation as an integer string (Python side).""" - try: - # Преобразуем в Decimal, затем в целое с округлением - number = to_decimal(value).to_integral_value(rounding=ROUND_HALF_UP) - # Формат с пробелом как разделителем тысяч - return f"{number:,}".replace(",", " ") - except (InvalidOperation, TypeError, ValueError): - return "0" # Возвращаем строку по умолчанию - -# --- Python Helper Functions for Status Display --- -def getStatusText(statusKey): - """Возвращает текстовое представление статуса на русском.""" - statusMap = { - STATUS_PENDING_PROCUREMENT: 'Ожидает закупа', - STATUS_PENDING_CUTTING: 'Ожидает раскроя', - STATUS_PENDING_SEWING: 'Ожидает пошива', - STATUS_PENDING_QC: 'Ожидает ОТК', - STATUS_PACKED_READY: 'Готово к отправке', - STATUS_SHIPPED_CLIENT: 'Отправлено клиенту', - STATUS_SHIPPED_DORDOI: 'Отправлено на Дордой', - STATUS_COMPLETED: 'Завершено', # Возможно, объединить с shipped? - STATUS_CANCELLED: 'Отменен' - } - return statusMap.get(statusKey, statusKey) # Возвращаем ключ, если статус неизвестен - -def getStatusClass(statusKey): - """Возвращает CSS классы для стилизации статуса.""" - classMap = { - STATUS_PENDING_PROCUREMENT: 'status-pending_procurement text-secondary', # Новый цвет - STATUS_PENDING_CUTTING: 'status-pending_cutting text-info', # Новый цвет - STATUS_PENDING_SEWING: 'status-pending_sewing text-primary', # Новый цвет - STATUS_PENDING_QC: 'status-pending_qc text-warning', - STATUS_PACKED_READY: 'status-packed_ready_to_ship text-ready', # Использует .text-ready - STATUS_SHIPPED_CLIENT: 'status-shipped_client text-shipped-client', # Использует .text-shipped-client - STATUS_SHIPPED_DORDOI: 'status-shipped_dor_doi text-shipped-dordoi', # Использует .text-shipped-dordoi - STATUS_COMPLETED: 'status-completed text-success', - STATUS_CANCELLED: 'status-cancelled text-danger fst-italic' # Новый стиль - } - return classMap.get(statusKey, '') # Возвращаем пустую строку, если статус неизвестен - -# --- Маршруты Flask --- - -@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() - # Получаем все материалы для справки - all_materials = data.get('materials', []) - - 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', '').strip() - fabric_unit = request.form.get('fabric_unit', 'м').strip() # Ед. изм. ткани - size_range = request.form.get('size_range', '').strip() - items_quantity_str = request.form.get('items_quantity') - prepayment_str = request.form.get('prepayment', '0') - - if not all([client_id, model_name, fabric_name, fabric_quantity, items_quantity_str]): - flash("Заполните все обязательные поля заказа (Клиент, Модель, Ткань, Кол-во ткани, Кол-во изделий).", "danger") - return redirect(url_for('orders')) - - # Валидация чисел - try: - items_quantity = int(to_decimal(items_quantity_str).to_integral_value()) - if items_quantity <= 0: raise ValueError("Кол-во изделий > 0") - except (InvalidOperation, ValueError): - flash("Некорректное количество изделий.", "danger") - return redirect(url_for('orders')) - - try: - fabric_qty_dec = to_decimal(fabric_quantity) - if fabric_qty_dec <= 0: raise ValueError("Кол-во ткани > 0") - except (InvalidOperation, ValueError): - flash("Некорректное количество ткани.", "danger") - return redirect(url_for('orders')) - - prepayment = to_decimal(prepayment_str) - - # Find client - client = find_client_by_id(client_id) - if not client: - flash("Выбранный клиент не найден.", "danger") - return redirect(url_for('orders')) - - # Create new order - 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_details': { # Детали ткани - 'name': fabric_name, - 'quantity_ordered': str(fabric_qty_dec), - 'unit': fabric_unit, - }, - 'size_range': size_range, - 'items_quantity': items_quantity, # int - 'prepayment': str(prepayment), # string - 'status': STATUS_PENDING_PROCUREMENT, # Начальный статус - 'timestamp_created': creation_time, - 'timestamp_last_updated': creation_time, - 'fittings_ordered': [], # Список заказанной фурнитуры - # Поля для этапов будут добавляться по мере прохождения - 'procurement_timestamp': None, - 'cutting_details': None, - 'sewing_details': None, - 'qc_packing_details': None, - 'shipment_details': None, - } - - # Add ordered fittings (text based) - fitting_names = request.form.getlist('fitting_names[]') - fitting_quantities = request.form.getlist('fitting_quantities[]') - fitting_units = request.form.getlist('fitting_units[]') # Единицы фурнитуры - - for i in range(len(fitting_names)): - name = fitting_names[i].strip() - qty_str = fitting_quantities[i].strip() - unit = fitting_units[i].strip() if i < len(fitting_units) else 'шт' # Единица по умолчанию 'шт' - - if name and qty_str: - try: - qty_int = int(to_decimal(qty_str).to_integral_value()) - if qty_int <= 0: continue # Пропускаем некорректное кол-во - new_order['fittings_ordered'].append({ - 'name': name, - 'quantity': qty_int, # int - 'unit': unit - }) - except (InvalidOperation, ValueError): - flash(f"Некорректное количество для фурнитуры '{name}'. Строка пропущена.", "warning") - - - # Add new order and save - 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')) - - # GET запрос - отображаем форму и список ВСЕХ заказов - orders_list_raw = data.get('orders', []) - orders_list_display = [] - for order_raw in orders_list_raw: - if isinstance(order_raw, dict) and 'id' in order_raw: - order_data = find_order_by_id(order_raw['id']) # Получаем с преобразованными типами - if order_data: - orders_list_display.append(order_data) - - # Сортируем заказы по дате создания (новые сверху) - orders_list_display.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, - orders=orders_list_display, - all_materials=all_materials) # Передаем материалы для справки - - -# Маршрут редактирования заказа (ОСТАВЛЕН, но нужно аккуратно использовать, чтобы не сломать статусы) -@app.route('/orders/edit/', methods=['POST']) -def edit_order(order_id): - # ВНИМАНИЕ: Редактирование активного заказа может нарушить логику статусов! - # Лучше разрешать редактирование только на начальных стадиях или для отмененных. - data = load_data() - orders = data.get('orders', []) - order_to_edit = None - order_index = -1 - - for i, order in enumerate(orders): - if isinstance(order, dict) and order.get('id') == order_id: - # Допустим, редактировать можно только если статус <= pending_cutting - allowed_statuses = [STATUS_PENDING_PROCUREMENT, STATUS_PENDING_CUTTING, STATUS_CANCELLED] - if order.get('status') not in allowed_statuses: - flash(f"Заказ в статусе '{getStatusText(order.get('status'))}' редактировать нельзя.", "warning") - return redirect(url_for('orders')) - order_to_edit = order - order_index = i - break - - if order_index == -1: - flash("Заказ не найден.", "danger") - return redirect(url_for('orders')) - - try: - # Получаем новые данные из формы - new_model_name = request.form.get('model_name', '').strip() - new_fabric_name = request.form.get('fabric_name', '').strip() - new_fabric_quantity = request.form.get('fabric_quantity', '').strip() - new_fabric_unit = request.form.get('fabric_unit', 'м').strip() - new_size_range = request.form.get('size_range', '').strip() - new_items_quantity_str = request.form.get('items_quantity') - new_prepayment_str = request.form.get('prepayment', '0') - - # Валидация - if not all([new_model_name, new_fabric_name, new_fabric_quantity, new_items_quantity_str]): - flash("Заполните все обязательные поля.", "danger") - # Не редирект, а остаемся на странице редактирования (пока не реализовано) - return redirect(url_for('orders')) # Пока редирект - - new_items_quantity = int(to_decimal(new_items_quantity_str).to_integral_value()) - new_fabric_qty_dec = to_decimal(new_fabric_quantity) - new_prepayment = to_decimal(new_prepayment_str) - - # Обновляем данные заказа - orders[order_index].update({ - 'model_name': new_model_name, - 'fabric_details': { - 'name': new_fabric_name, - 'quantity_ordered': str(new_fabric_qty_dec), - 'unit': new_fabric_unit, - }, - 'size_range': new_size_range, - 'items_quantity': new_items_quantity, - 'prepayment': str(new_prepayment), - 'timestamp_last_updated': get_current_time().isoformat() - }) - - # Обновляем фурнитуру - fitting_names = request.form.getlist('fitting_names[]') - fitting_quantities = request.form.getlist('fitting_quantities[]') - fitting_units = request.form.getlist('fitting_units[]') - orders[order_index]['fittings_ordered'] = [] - for i in range(len(fitting_names)): - name = fitting_names[i].strip() - qty_str = fitting_quantities[i].strip() - unit = fitting_units[i].strip() if i < len(fitting_units) else 'шт' - if name and qty_str: - try: - qty_int = int(to_decimal(qty_str).to_integral_value()) - if qty_int > 0: - orders[order_index]['fittings_ordered'].append({ - 'name': name, 'quantity': qty_int, 'unit': unit - }) - except (InvalidOperation, ValueError): pass # Игнорируем невалидные строки - - save_data(data) - flash("Заказ успешно обновлен.", "success") - upload_db_to_hf(DATA_FILE) - - except (InvalidOperation, ValueError): - flash("Ошибка в числовых данных при редактировании.", "danger") - 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', []) - order_found = False - - # Находим и удаляем/отменяем заказ - for i, order in enumerate(orders): - if isinstance(order, dict) and order.get('id') == order_id: - order_found = True - current_status = order.get('status') - # Реально удалять можно только на самых ранних стадиях или отмененные - if current_status in [STATUS_PENDING_PROCUREMENT, STATUS_CANCELLED]: - del orders[i] - action_text = "удален" - # Для заказов в процессе - только отмена - elif current_status not in [STATUS_SHIPPED_CLIENT, STATUS_SHIPPED_DORDOI, STATUS_COMPLETED]: - orders[i]['status'] = STATUS_CANCELLED - orders[i]['timestamp_last_updated'] = get_current_time().isoformat() - action_text = "отменен" - else: # Уже отправленные/завершенные не трогаем - flash("Нельзя удалить или отменить уже отправленный/завершенный заказ.", "danger") - return redirect(url_for('orders')) - - data['orders'] = orders - save_data(data) - flash(f"Заказ успешно {action_text}.", "success") - upload_db_to_hf(DATA_FILE) - break - if not order_found: - flash("Заказ не найден.", "warning") - - return redirect(url_for('orders')) - -# 1. Маршрут "Закуп" - ТЕПЕРЬ ПОКАЗЫВАЕТ ЗАКАЗЫ ДЛЯ ЗАКУПА -@app.route('/procurement', methods=['GET', 'POST']) -def procurement(): - data = load_data() - categories = data.get('categories', []) - all_materials = data.get('materials', []) # Для формы закупки - - # Получаем заказы, ожидающие закупа - pending_procurement_orders_raw = [ - order for order in data.get('orders', []) - if isinstance(order, dict) and order.get('status') == STATUS_PENDING_PROCUREMENT - ] - pending_procurement_orders = [] - for order_raw in pending_procurement_orders_raw: - order_data = find_order_by_id(order_raw['id']) - if order_data: - pending_procurement_orders.append(order_data) - pending_procurement_orders.sort(key=lambda x: x.get('timestamp_created', '')) - - - if request.method == 'POST': - action = request.form.get('action') - - # --- Действие: Отметить заказ как закупленный --- - if action == 'mark_procured': - order_id = request.form.get('order_id') - if not order_id: - flash("Не указан ID заказа для отметки о закупе.", "warning") - return redirect(url_for('procurement')) - - orders = data.get('orders', []) - order_updated = False - for i, order in enumerate(orders): - if isinstance(order, dict) and order.get('id') == order_id and order.get('status') == STATUS_PENDING_PROCUREMENT: - orders[i]['status'] = STATUS_PENDING_CUTTING # Меняем статус - orders[i]['procurement_timestamp'] = get_current_time().isoformat() - orders[i]['timestamp_last_updated'] = orders[i]['procurement_timestamp'] - order_updated = True - break - - if order_updated: - save_data(data) - flash(f"Заказ ID {order_id[:8]}... отмечен как закупленный и переведен в статус 'Ожидает раскроя'.", "success") - upload_db_to_hf(DATA_FILE) - else: - flash(f"Не удалось найти заказ {order_id[:8]}... в статусе 'Ожидает закупа' для обновления.", "warning") - return redirect(url_for('procurement')) - - # --- Действие: Зарегистрировать закуп материалов (как раньше) --- - elif action == 'register_procurement': - try: - materials_to_add = [] - valid_items_processed = 0 # Счетчик успешно обработанных строк - - item_names = request.form.getlist('item_name[]') - # Проверка, что хотя бы одна строка была отправлена и не пуста - if not item_names or all(not name.strip() for name in item_names): - flash("Не добавлено ни одного товара. Заполните хотя бы одну строку.", "warning") - return redirect(url_for('procurement')) - - item_quantities = request.form.getlist('item_quantity[]') - item_units = request.form.getlist('item_unit[]') - item_prices = request.form.getlist('item_price_per_unit[]') - item_per_unit = request.form.getlist('item_per_unit[]') # Количество изделий на единицу (для фурнитуры) - item_types = request.form.getlist('item_type[]') - item_categories = request.form.getlist('item_category[]') - item_new_categories = request.form.getlist('item_new_category[]') - - procurement_time = get_current_time().isoformat() - current_materials = data.get('materials', []) # Получаем текущий список материалов - - for i in range(len(item_names)): - name = item_names[i].strip() - quantity_str = item_quantities[i] - unit = item_units[i] - price_str = item_prices[i] - items_per_unit_str = item_per_unit[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 - - # Обработка "На ед." (items_per_unit) - items_per_unit = 0 - if items_per_unit_str: - try: items_per_unit = int(to_decimal(items_per_unit_str).to_integral_value()) - except (InvalidOperation, ValueError): flash(f"Предупреждение в строке {i+1}: Некорректное значение 'На ед.', установлено 0.", "warning"); items_per_unit = 0 - if items_per_unit < 0: items_per_unit = 0 - - # Определение категории - 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): - # Сравниваем lowercase для имени и учитываем тип и категорию - 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 - # Обновляем items_per_unit - existing_material['items_per_unit'] = items_per_unit - # Обновляем время последнего обновления - existing_material['timestamp_last_updated'] = procurement_time - logging.info(f"Материал '{name}' обновлен. Новое количество: {new_quantity}, Цена: {price}, Категория: {final_category}") - valid_items_processed += 1 - else: - # --- Добавляем новый материал --- - new_material = { - 'id': uuid.uuid4().hex, - 'name': name, - 'quantity': str(quantity), - 'unit': unit, - 'price_per_unit': str(price), - 'items_per_unit': items_per_unit, # Добавляем поле - 'type': item_type, - 'category': final_category, - 'timestamp_added': procurement_time, - 'timestamp_last_updated': procurement_time - } - materials_to_add.append(new_material) - logging.info(f"Новый материал '{name}' добавлен. Количество: {quantity}, Цена: {price}, Категория: {final_category}") - valid_items_processed += 1 - - # Сохраняем данные, если хотя бы одна позиция была успешно обработана - if valid_items_processed > 0 : - if materials_to_add: - data['materials'].extend(materials_to_add) # Добавляем новые - # data['materials'] уже содержит обновленные элементы, если были только обновления - - # Обновляем и сортируем список категорий (только строки) - 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')) - else: - flash("Неизвестное действие.", "danger") - return redirect(url_for('procurement')) - - - # GET запрос: отображаем страницу - # Форматируем материалы для отображения в таблице остатков (если нужно) - materials_display = [] - for m_raw in all_materials: - if isinstance(m_raw, dict) and 'id' in m_raw: # Доп. проверка - m_data = find_item_by_id(m_raw['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)] - - 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_to_procure=pending_procurement_orders) # Заказы для закупа - -# 2. Маршрут "Раскрой" - ТЕПЕРЬ РАБОТАЕТ С ЗАКАЗАМИ -@app.route('/cutting', methods=['GET', 'POST']) -def cutting(): - data = load_data() - config = data.get('config', {}) - - # Получаем заказы, ожидающие раскроя - pending_cutting_orders_raw = [ - order for order in data.get('orders', []) - if isinstance(order, dict) and order.get('status') == STATUS_PENDING_CUTTING - ] - pending_cutting_orders = [] - for order_raw in pending_cutting_orders_raw: - order_data = find_order_by_id(order_raw['id']) - if order_data: - pending_cutting_orders.append(order_data) - pending_cutting_orders.sort(key=lambda x: x.get('procurement_timestamp', '') or x.get('timestamp_created', '')) - - # Получаем ткани для справки (хотя выбор ткани теперь идет из заказа) - fabrics_on_stock = [] - for m in data.get('materials', []): - if isinstance(m, dict) and m.get('type') == 'fabric': - if to_decimal(m.get('quantity', '0')) > 0: - m_data = find_item_by_id(m['id'], 'materials') - if m_data: - m_data['quantity_str'] = format_currency_py(m_data.get('quantity', '0.00')) - fabrics_on_stock.append(m_data) - - - if request.method == 'POST': - try: - order_id = request.form.get('order_id') - fabric_used_str = request.form.get('fabric_used') - # Количество раскроенных теперь берем из заказа, оно не вводится здесь - # cut_items_quantity_str = request.form.get('cut_items_quantity') - УБРАНО - - # Валидация входных данных - if not order_id or not fabric_used_str: - flash("Необходимо выбрать заказ и указать расход ткани.", "danger") - return redirect(url_for('cutting')) - - # Ищем выбранный заказ - target_order = find_order_by_id(order_id) - if not target_order or target_order.get('status') != STATUS_PENDING_CUTTING: - 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')) - - # Ищем ткань из заказа на складе для списания и расчета стоимости - order_fabric_name = target_order.get('fabric_details', {}).get('name') - order_fabric_unit = target_order.get('fabric_details', {}).get('unit', 'м') - fabric_material_on_stock = None - current_materials = data.get('materials', []) # Получаем актуальный список - - # Ищем материал по имени (может быть не идеально, лучше ID, но в заказе сейчас имя) - for i, mat in enumerate(current_materials): - if isinstance(mat, dict) and mat.get('type') == 'fabric' and mat.get('name', '').lower() == order_fabric_name.lower(): - # Проверяем доступное количество - available_quantity = to_decimal(mat.get('quantity', '0')) - if fabric_used > available_quantity: - flash(f"Недостаточно ткани '{order_fabric_name}' на складе. " - f"В наличии: {format_currency_py(available_quantity)} {mat.get('unit')}, " - f"требуется: {format_currency_py(fabric_used)} {mat.get('unit')}.", "danger") - return redirect(url_for('cutting')) - fabric_material_on_stock = mat # Нашли подходящий материал - fabric_material_index = i - break # Берем первый найденный - - if not fabric_material_on_stock: - flash(f"Ткань '{order_fabric_name}', указанная в заказе, не найдена на складе или ее недостаточно.", "danger") - return redirect(url_for('cutting')) - - # Расчет стоимостей - price_per_unit = to_decimal(fabric_material_on_stock.get('price_per_unit', '0.00')) - material_cost = fabric_used * price_per_unit - - cut_items_quantity = target_order.get('items_quantity', 0) # Берем из заказа - 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 - - # Формирование деталей раскроя для заказа - cutting_time = get_current_time().isoformat() - cutting_details_data = { - 'fabric_id_used': fabric_material_on_stock.get('id'), # ID фактически использованной ткани - 'fabric_name_used': fabric_material_on_stock.get('name'), - 'fabric_unit': fabric_material_on_stock.get('unit'), - 'fabric_used': str(fabric_used), # string - 'cut_quantity': cut_items_quantity, # int (из заказа) - 'material_cost': str(material_cost), # string - 'cutter_salary_cost': str(cutting_salary_cost), # string - 'cutting_timestamp': cutting_time - } - - # --- Обновление заказа --- - orders = data.get('orders', []) - order_updated = False - for i, order in enumerate(orders): - if isinstance(order, dict) and order.get('id') == order_id: - orders[i]['cutting_details'] = cutting_details_data - orders[i]['status'] = STATUS_PENDING_SEWING # Новый статус - orders[i]['timestamp_last_updated'] = cutting_time - order_updated = True - break - - if not order_updated: - flash(f"Критическая ошибка: не удалось обновить заказ {order_id} после раскроя.", "danger") - return redirect(url_for('cutting')) - - # --- Обновление остатка ткани --- - new_available_quantity = available_quantity - fabric_used - current_materials[fabric_material_index]['quantity'] = str(new_available_quantity.quantize(Decimal('0.01'))) - current_materials[fabric_material_index]['timestamp_last_updated'] = cutting_time - - # Сохранение данных - save_data(data) - - flash(f"Раскрой для заказа ID {order_id[:8]}... ({cut_items_quantity} ед.) успешно зарегистрирован. Статус: Ожидает пошива.", "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')) - - # GET запрос: отображаем страницу - html = BASE_TEMPLATE_OPERATIONAL.replace('__TITLE__', "Раскрой").replace('__CONTENT__', CUTTING_CONTENT).replace('__SCRIPTS__', CUTTING_SCRIPTS) - return render_template_string(html, - orders_to_cut=pending_cutting_orders, - fabrics_on_stock=fabrics_on_stock) # Ткани для справки - -# 3. Маршрут "Пошив" - ТЕПЕРЬ РАБОТАЕТ С ЗАКАЗАМИ -@app.route('/sewing', methods=['GET', 'POST']) -def sewing(): - data = load_data() - config = data.get('config', {}) - - # Получаем заказы, ожидающие пошива - pending_sewing_orders_raw = [ - order for order in data.get('orders', []) - if isinstance(order, dict) and order.get('status') == STATUS_PENDING_SEWING - ] - pending_sewing_orders = [] - for order_raw in pending_sewing_orders_raw: - order_data = find_order_by_id(order_raw['id']) - if order_data: - pending_sewing_orders.append(order_data) - pending_sewing_orders.sort(key=lambda x: x.get('cutting_details', {}).get('cutting_timestamp', '') or x.get('timestamp_created', '')) - - # Находим доступную фурнитуру и все материалы для брака - available_fittings = [] - all_materials = [] - for m_raw in data.get('materials', []): - if isinstance(m_raw, dict): - m_data = find_item_by_id(m_raw['id'], 'materials') - if m_data: - all_materials.append(m_data) - if m_data.get('type') == 'fittings' and m_data.get('quantity', Decimal('0')) > 0: - m_data['quantity_str'] = format_integer_py(m_data['quantity']) - available_fittings.append(m_data) - elif m_data.get('type') == 'fabric': # Для брака ткани - m_data['quantity_str'] = format_currency_py(m_data['quantity']) - - - if request.method == 'POST': - try: - order_id = request.form.get('order_id') - sewn_product_name = request.form.get('sewn_product_name', '').strip() - sewn_quantity_str = request.form.get('sewn_quantity') - - # Фурнитура - fitting_ids = request.form.getlist('fitting_ids[]') - fitting_quantities = request.form.getlist('fitting_quantities[]') - - # Брак - defect_material_ids = request.form.getlist('defect_material_id[]') - defect_quantities = request.form.getlist('defect_quantity[]') - - # Валидация основных полей - if not order_id or not sewn_product_name or not sewn_quantity_str: - flash("Необходимо выбрать заказ, указать название изделия и количество сшитых.", "danger") - return redirect(url_for('sewing')) - - # Находим заказ - target_order = find_order_by_id(order_id) - if not target_order or target_order.get('status') != STATUS_PENDING_SEWING: - flash("Выбранный заказ не найден или не ожидает пошива.", "danger") - return redirect(url_for('sewing')) - - # Количество раскроенных из деталей заказа - cut_quantity = target_order.get('cutting_details', {}).get('cut_quantity', 0) - - # Валидация количества сшитых - try: - sewn_quantity = int(to_decimal(sewn_quantity_str).to_integral_value()) - if sewn_quantity <= 0: raise ValueError("Кол-во > 0") - if sewn_quantity > cut_quantity: - flash(f"Количество сшитых ({sewn_quantity}) не может превышать количество раскроенных ({cut_quantity}).", "danger") - return redirect(url_for('sewing')) - except (InvalidOperation, ValueError): - flash("Некорректное количество сшитых изделий.", "danger") - return redirect(url_for('sewing')) - - # --- Обработка фурнитуры --- - fittings_consumed_list = [] - fittings_total_cost = Decimal('0') - materials_to_update = {} # Словарь {material_id: quantity_to_deduct} для атомарного списания - sewing_time = get_current_time().isoformat() - is_valid = True - current_materials_sewing = data.get('materials', []) # Актуальный список материалов - - if fitting_ids and fitting_quantities and len(fitting_ids) == len(fitting_quantities): - for i in range(len(fitting_ids)): - fitting_id = fitting_ids[i] - quantity_str = fitting_quantities[i] - - if not fitting_id or not quantity_str: continue # Пропускаем пустые строки - - fitting_material = find_item_by_id(fitting_id, 'materials') # Получаем актуальные данные - if not fitting_material or fitting_material.get('type') != 'fittings': - flash(f"Ошибка: Фурнитура с ID {fitting_id} не найдена или не является фурнитурой.", "danger") - is_valid = False; break - - try: - quantity_used = int(to_decimal(quantity_str).to_integral_value()) - if quantity_used <= 0: raise ValueError("Кол-во > 0") - except (InvalidOperation, ValueError): - flash(f"Некорректное количество для фурнитуры '{fitting_material['name']}'.", "danger") - is_valid = False; break - - # Проверка доступности с учетом уже запланированного списания - available_qty_dec = fitting_material.get('quantity', Decimal('0')) - planned_deduction = materials_to_update.get(fitting_id, Decimal('0')) - if available_qty_dec < planned_deduction + Decimal(quantity_used): - flash(f"Недостаточно фурнитуры '{fitting_material['name']}'. " - f"Доступно с учетом плана: {format_integer_py(available_qty_dec - planned_deduction)}, " - f"требуется еще: {format_integer_py(quantity_used)}.", "danger") - is_valid = False; break - - materials_to_update[fitting_id] = planned_deduction + Decimal(quantity_used) - price = fitting_material.get('price_per_unit', Decimal('0.00')) - cost = price * Decimal(quantity_used) - fittings_total_cost += cost - - fittings_consumed_list.append({ - 'fitting_id': fitting_id, - 'fitting_name': fitting_material['name'], - 'quantity_used': quantity_used, # int - 'cost': str(cost) # string - }) - - if not is_valid: return redirect(url_for('sewing')) - - # --- Обработка брака --- - sewing_defects_list = [] - if defect_material_ids and defect_quantities and len(defect_material_ids) == len(defect_material_ids): - for i in range(len(defect_material_ids)): - material_id = defect_material_ids[i] - quantity_str = defect_quantities[i] - - if not material_id or not quantity_str: continue # Пропускаем пустые строки - - defect_material = find_item_by_id(material_id, 'materials') # Актуальные данные - if not defect_material: - flash(f"Предупреждение: Материал для брака ID {material_id} не найден.", "warning") - continue - - material_type = defect_material.get('type') - quantity_deduct = Decimal('0') - quantity_log_value = 0 - is_fabric = material_type == 'fabric' - - try: - if is_fabric: - quantity_deduct = to_decimal(quantity_str) - if quantity_deduct <= 0: raise ValueError("Кол-во ткани > 0") - quantity_log_value = str(quantity_deduct) # string для лога - else: # fittings - quantity_int = int(to_decimal(quantity_str).to_integral_value()) - if quantity_int <= 0: raise ValueError("Кол-во фурн. > 0") - quantity_deduct = Decimal(quantity_int) - quantity_log_value = quantity_int # int для лога - except (InvalidOperation, ValueError): - flash(f"Некорректное количество брака для '{defect_material['name']}'.", "warning") - continue - - # Проверка доступности с учетом уже запланированного - available_qty = defect_material.get('quantity', Decimal('0')) - planned_deduction = materials_to_update.get(material_id, Decimal('0')) - effective_available = available_qty - planned_deduction - - if effective_available < quantity_deduct: - available_str = format_currency_py(effective_available) if is_fabric else format_integer_py(effective_available) - deduct_str = format_currency_py(quantity_deduct) if is_fabric else format_integer_py(quantity_deduct) - flash(f"Недостаточно '{defect_material['name']}' для списания в брак ({deduct_str} {defect_material['unit']}). " - f"Доступно с учетом других списаний: {available_str} {defect_material['unit']}.", "danger") - is_valid = False; break - - materials_to_update[material_id] = planned_deduction + quantity_deduct - price = defect_material.get('price_per_unit', Decimal('0.00')) - defect_cost = price * quantity_deduct - - # Готовим запись для общего лога брака - defect_log_entry = { - 'log_id': uuid.uuid4().hex, - 'material_id': material_id, - 'material_name': defect_material['name'], - 'quantity': quantity_log_value, # string (Dec) or int - 'unit': defect_material['unit'], - 'type': material_type, - 'stage': 'sewing', - 'reason': 'Брак при пошиве', - 'cost': str(defect_cost), # string - 'order_id': order_id, # Ссылка на заказ - 'timestamp': sewing_time - } - # Добавляем в список брака ДЛЯ ЭТОГО ПОШИВА (сохраним в заказе) - sewing_defects_list.append(defect_log_entry) # Сохраняем полную инфу лога - - if not is_valid: return redirect(url_for('sewing')) - - # --- Списание материалов (фурнитура + брак) --- - # current_materials_sewing уже содержит актуальные данные - for material_id, quantity_to_deduct in materials_to_update.items(): - material_updated_sewing = False - for i, mat in enumerate(current_materials_sewing): - if isinstance(mat, dict) and mat.get('id') == material_id: - current_qty = to_decimal(mat.get('quantity', '0')) - new_qty = (current_qty - quantity_to_deduct).quantize(Decimal('0.01') if mat.get('type') == 'fabric' else Decimal('0'), rounding=ROUND_HALF_UP) - if new_qty < 0: new_qty = Decimal('0') - current_materials_sewing[i]['quantity'] = str(new_qty) - current_materials_sewing[i]['timestamp_last_updated'] = sewing_time - material_updated_sewing = True - break - if not material_updated_sewing: - flash(f"Критическая ошибка: Не удалось списать материал ID {material_id}.", "danger") - return redirect(url_for('sewing')) - # Обновляем основной список материалов в data - data['materials'] = current_materials_sewing - - - # --- Расчет зарплаты швеи --- - salary_sewer_per_unit = to_decimal(config.get('salary_sewer_per_unit', '0.00')) - sewing_salary_cost = Decimal(sewn_quantity) * salary_sewer_per_unit - - # --- Формирование деталей пошива для заказа --- - sewing_details_data = { - 'sewn_product_name': sewn_product_name, - 'sewn_quantity': sewn_quantity, # int - 'fittings_consumed': fittings_consumed_list, # Список словарей - 'sewing_defects': sewing_defects_list, # Список словарей (из лога брака) - 'fittings_cost': str(fittings_total_cost), # string - 'sewer_salary_cost': str(sewing_salary_cost), # string - 'sewing_timestamp': sewing_time - } - - # --- Обновление заказа --- - orders = data.get('orders', []) - order_updated_sewing = False - for i, order in enumerate(orders): - if isinstance(order, dict) and order.get('id') == order_id: - orders[i]['sewing_details'] = sewing_details_data - orders[i]['status'] = STATUS_PENDING_QC # Новый статус - orders[i]['timestamp_last_updated'] = sewing_time - order_updated_sewing = True - break - - if not order_updated_sewing: - flash(f"Критическая ошибка: не удалось обновить заказ {order_id} после пошива.", "danger") - return redirect(url_for('sewing')) - - # --- Добавление брака в общий лог --- - if sewing_defects_list: - if 'defect_log' not in data: data['defect_log'] = [] - data['defect_log'].extend(sewing_defects_list) - - # --- Сохранение всех изменений --- - save_data(data) - flash(f"Пошив {sewn_quantity} ед. '{sewn_product_name}' для заказа ID {order_id[:8]}... успешно зарегистрирован. Статус: Ожидает ОТК.", "success") - if fittings_consumed_list: - flash(f"Использовано {len(fittings_consumed_list)} поз. фурнитуры (стоимость: {format_currency_py(fittings_total_cost)} сом).", "info") - if sewing_defects_list: - flash(f"Зарегистрировано {len(sewing_defects_list)} поз. брака при пошиве.", "warning") - - 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')) - - # GET запрос: отображаем страницу - html = BASE_TEMPLATE_OPERATIONAL.replace('__TITLE__', "Пошив").replace('__CONTENT__', SEWING_CONTENT).replace('__SCRIPTS__', SEWING_SCRIPTS) - return render_template_string(html, - orders_to_sew=pending_sewing_orders, - available_fittings=available_fittings, # Доступная фурнитура для выбора - all_materials=all_materials) # Все материалы для выбора брака - - -# 4. Маршрут "ОТК и Упаковка" - ТЕПЕРЬ РАБОТАЕТ С ЗАКАЗАМИ -@app.route('/qc_packing', methods=['GET', 'POST']) -def qc_packing(): - data = load_data() - config = data.get('config', {}) - - # Получаем заказы, ожидающие ОТК - pending_qc_orders_raw = [ - order for order in data.get('orders', []) - if isinstance(order, dict) and order.get('status') == STATUS_PENDING_QC - ] - pending_qc_orders = [] - for order_raw in pending_qc_orders_raw: - order_data = find_order_by_id(order_raw['id']) - if order_data: - pending_qc_orders.append(order_data) - pending_qc_orders.sort(key=lambda x: x.get('sewing_details', {}).get('sewing_timestamp', '') or x.get('timestamp_created', '')) - - - if request.method == 'POST': - try: - order_id = request.form.get('order_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 order_id: - flash("Необходимо выбрать заказ для ОТК.", "danger") - return redirect(url_for('qc_packing')) - - # Находим заказ - target_order = find_order_by_id(order_id) - if not target_order or target_order.get('status') != STATUS_PENDING_QC: - flash("Выбранный заказ не найден или не ожидает ОТК.", "danger") - return redirect(url_for('qc_packing')) - - # Количество сшитых из деталей заказа - sewn_quantity = target_order.get('sewing_details', {}).get('sewn_quantity', 0) - - # Валидация количества упакованных и брака - try: - quantity_packed = int(to_decimal(quantity_packed_str).to_integral_value()) - quantity_defective = int(to_decimal(quantity_defective_str).to_integral_value()) - - if quantity_packed < 0 or quantity_defective < 0: - raise ValueError("Количество не может быть отрицательным") - - total_processed_qc = quantity_packed + quantity_defective - if total_processed_qc <= 0: - flash("Необходимо указать количество упакованных или бракованных изделий (сумма должна быть > 0).", "warning") - return redirect(url_for('qc_packing')) - - # Проверяем, соответствует ли общее количество сшитому - if total_processed_qc != sewn_quantity: - flash(f"Ошибка: Сумма упакованных ({quantity_packed}) и брака ОТК ({quantity_defective}) = {total_processed_qc}, " - f"что НЕ совпадает с количеством сшитых изделий ({sewn_quantity}) в заказе. Обработайте все изделия за раз.", "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_defect_log_entry = None - - # --- Расчет себестоимости и цены --- - # Получаем стоимости с предыдущих этапов из заказа - cutting_details = target_order.get('cutting_details', {}) - sewing_details = target_order.get('sewing_details', {}) - - material_cost_cut = cutting_details.get('material_cost', Decimal('0.00')) - fittings_cost_sew = sewing_details.get('fittings_cost', Decimal('0.00')) - total_material_cost = material_cost_cut + fittings_cost_sew - - cutter_salary = cutting_details.get('cutter_salary_cost', Decimal('0.00')) - sewer_salary = sewing_details.get('sewer_salary_cost', Decimal('0.00')) - packer_salary_per_unit = to_decimal(config.get('salary_packer_per_unit', '0.00')) - # ЗП упаковщика считаем только за успешно упакованные - packer_salary_total = Decimal(quantity_packed) * packer_salary_per_unit - total_salary_cost = cutter_salary + sewer_salary + packer_salary_total - - # Полная себестоимость успешно упакованной партии - total_cost = total_material_cost + total_salary_cost - - # Расчет цены продажи - margin_per_item = to_decimal(config.get('margin_per_item', '0.00')) - margin_total = Decimal(quantity_packed) * margin_per_item - final_price = total_cost + margin_total # Цена продажи всей партии - - # --- Обработка брака на этапе ОТК --- - if quantity_defective > 0: - # Себестоимость одного бракованного изделия (без ЗП упаковщика и маржи) - cost_per_defective_item = Decimal('0') - if sewn_quantity > 0: # Избегаем деления на ноль - # Общая стоимость материалов и ЗП кроя/шитья делим на общее кол-во сшитых - cost_per_defective_item = (material_cost_cut + fittings_cost_sew + cutter_salary + sewer_salary) / Decimal(sewn_quantity) - - 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_details.get('sewn_product_name', target_order.get('model_name', '?'))} (Готовое изделие)", - 'quantity': quantity_defective, # int - 'unit': 'шт', - 'type': 'finished_product', - 'stage': 'qc_packing', - 'reason': defect_reason, - 'cost': str(total_defect_cost.quantize(Decimal('0.01'))), # string - 'order_id': order_id, # Ссылка на заказ - 'timestamp': qc_time - } - if 'defect_log' not in data: data['defect_log'] = [] - data['defect_log'].append(new_defect_log_entry) - logging.info(f"Зарегистрирован брак ОТК для заказа {order_id}: {quantity_defective} ед. (Общая стоимость: {format_currency_py(total_defect_cost)})") - - - # --- Формирование деталей ОТК для заказа --- - qc_packing_details_data = { - 'packed_quantity': quantity_packed, # int - 'qc_defective_quantity': quantity_defective, # int - 'packer_salary_cost': str(packer_salary_total), # string (ЗП только за упакованные) - 'total_material_cost': str(total_material_cost), # string - 'total_salary_cost': str(total_salary_cost), # string (Включая пакерскую ЗП) - 'total_cost': str(total_cost), # string (Себестоимость упакованных) - 'margin': str(margin_total), # string - 'final_price': str(final_price), # string (Цена продажи упакованных) - 'qc_timestamp': qc_time, - # Добавляем детали брака ОТК сюда же для справки - 'qc_defect_details': new_defect_log_entry if new_defect_log_entry else None - } - - # --- Обновление заказа --- - orders = data.get('orders', []) - order_updated_qc = False - new_status = STATUS_PACKED_READY if quantity_packed > 0 else STATUS_COMPLETED # Если только брак, то сразу завершаем - - for i, order in enumerate(orders): - if isinstance(order, dict) and order.get('id') == order_id: - orders[i]['qc_packing_details'] = qc_packing_details_data - orders[i]['status'] = new_status # Новый статус - orders[i]['timestamp_last_updated'] = qc_time - order_updated_qc = True - break - - if not order_updated_qc: - flash(f"Критическая ошибка: Не удалось найти и обновить заказ {order_id} после ОТК.", "danger") - return redirect(url_for('qc_packing')) - - # --- Сохранение данных --- - save_data(data) - - flash_message = f"ОТК/Упаковка для заказа ID {order_id[:8]}... завершена: упаковано {quantity_packed} ед., брак {quantity_defective} ед. " - if quantity_packed > 0: - flash_message += f"Статус: Готово к отправке." - elif quantity_defective > 0: - 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')) - - # GET запрос: отображаем страницу - html = BASE_TEMPLATE_OPERATIONAL.replace('__TITLE__', "ОТК и Упаковка").replace('__CONTENT__', QC_PACKING_CONTENT).replace('__SCRIPTS__', QC_PACKING_SCRIPTS) - return render_template_string(html, orders_to_qc=pending_qc_orders) - - -# 5. Маршрут "База клиентов" (без изменений) -@app.route('/clients', methods=['GET', 'POST']) -def clients_panel(): - if request.method == 'POST': - # Добавление нового клиента - 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')) - - clients = load_client_data() # Загружает проверенные данные - # Проверка на дубликат по номеру телефона (очищенному от нецифровых символов) - 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, # Сохраняем 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')) - - # --- GET запрос: отображение списка клиентов --- - try: - clients_data = load_client_data() # Загружаем проверенные данные - clients_data.sort(key=lambda x: x.get('name','').lower()) # Сортировка по имени - - # Подготовка данных для шаблона: обработка истории - # load_client_data УЖЕ гарантирует, что history и items являются списками - for client in clients_data: - # Сортировка истории (теперь безопасно) и парсинг дат - if 'history' in client: # Проверка типа уже не нужна, т.к. load_client_data ее сделал - # Сортируем исходный список (не создаем копию для сортировки тут) - client['history'].sort(key=lambda x: x.get('timestamp',''), reverse=True) - # Добавляем datetime объекты для удобного отображения в шаблоне - for record in client['history']: # record - точно словарь - record['timestamp_dt'] = parse_iso_datetime(record.get('timestamp')) - # Проверка record['items'] уже не нужна - - 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"Неожиданная ошибка в GET /clients: {e}", exc_info=True) - flash("Произошла ошибка при отображении страницы клиентов.", "danger") - # Можно перенаправить на главную или показать пустую страницу - return redirect(url_for('admin_panel')) - -# 6. Маршрут "Админ-панель" - Обновлен для отображения ЗАКАЗОВ вместо qc_items -@app.route('/admin') -def admin_panel(): - data = load_data() - clients_data = load_client_data() # Загружаем проверенных клиентов - config = data.get('config', {}) - - # Получаем актуальные данные материалов, брака, расходов - all_materials_raw = data.get('materials', []) - all_materials = [m for m_id in [m.get('id') for m in all_materials_raw if isinstance(m, dict)] - if (m := find_item_by_id(m_id, 'materials')) is not None and m.get('quantity', Decimal('0')) > 0] - materials_count = len(all_materials) - - all_orders_raw = data.get('orders', []) - all_orders = [o for o_id in [o.get('id') for o in all_orders_raw if isinstance(o, dict)] if (o := find_order_by_id(o_id)) is not None] - - all_defect_log_raw = data.get('defect_log', []) - all_defect_log = [d for d_id in [d.get('log_id') for d in all_defect_log_raw if isinstance(d, dict)] if (d := find_item_by_id(d_id, 'defect_log')) is not None] - - all_expenses_raw = data.get('expenses', []) - all_expenses = [e for e_id in [e.get('id') for e in all_expenses_raw 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', []) - - # --- Расчет сводных данных --- - orders_ready_to_ship = [o for o in all_orders if o.get('status') == STATUS_PACKED_READY] - items_ready_ship_count = len(orders_ready_to_ship) # Количество заказов/партий - items_ready_ship_qty = sum(o.get('qc_packing_details', {}).get('packed_quantity', 0) for o in orders_ready_to_ship) # Общее кол-во изделий - - # Считаем заказы на разных стадиях - pending_procurement_count = len([o for o in all_orders if o.get('status') == STATUS_PENDING_PROCUREMENT]) - pending_cutting_count = len([o for o in all_orders if o.get('status') == STATUS_PENDING_CUTTING]) - pending_sewing_count = len([o for o in all_orders if o.get('status') == STATUS_PENDING_SEWING]) - pending_qc_count = len([o for o in all_orders if o.get('status') == STATUS_PENDING_QC]) - # Количество изделий в ожидании ОТК - pending_qc_quantity = sum(o.get('sewing_details', {}).get('sewn_quantity', 0) for o in all_orders if o.get('status') == STATUS_PENDING_QC) - - - 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, - all_orders=all_orders, # Передаем все заказы для разных вкладок - orders_ready_to_ship=orders_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_procurement_count=pending_procurement_count, - pending_cutting_count=pending_cutting_count, - pending_sewing_count=pending_sewing_count, - pending_qc_count=pending_qc_count, - pending_qc_quantity=pending_qc_quantity, - 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('/admin_dashboard', methods=['GET', 'POST']) -def admin_dashboard(): - data = load_data() - # Get your data and other variables - - # Before rendering the template, make sure all orders have fabric_details - orders = data.get('orders', []) - for order in orders: - # Initialize fabric_details if it doesn't exist - if isinstance(order, dict) and 'fabric_details' not in order: - order['fabric_details'] = {} - - # Render your template - html = BASE_TEMPLATE_OPERATIONAL.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_PANEL_CONTENT).replace('__SCRIPTS__', ADMIN_PANEL_SCRIPTS) - return render_template_string(html, orders=orders) - - # Передача данных в шаблон - html = BASE_TEMPLATE.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_CONTENT).replace('__SCRIPTS__', ADMIN_SCRIPTS) - return render_template_string(html, - materials=all_materials, - all_orders=all_orders, # Передаем все заказы для разных вкладок - orders_ready_to_ship=orders_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_procurement_count=pending_procurement_count, - pending_cutting_count=pending_cutting_count, - pending_sewing_count=pending_sewing_count, - pending_qc_count=pending_qc_count, - pending_qc_quantity=pending_qc_quantity, - 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) - ) - -# 7. Маршрут для выполнения отправки - ТЕПЕРЬ РАБОТАЕТ С ЗАКАЗАМИ -@app.route('/dispatch_item', methods=['POST']) -def dispatch_item(): - order_id = request.form.get('item_id') # Получаем ID заказа - destination_type = request.form.get('destination_type') - client_id = request.form.get('client_id') # Может быть None - quantity_to_dispatch_str = request.form.get('quantity_to_dispatch') - - redirect_target = url_for('admin_panel') + '#dispatch-content' - - if not order_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() - orders = data.get('orders', []) - - order_to_update = None - order_index = -1 - - for i, order in enumerate(orders): - if isinstance(order, dict) and order.get('id') == order_id and order.get('status') == STATUS_PACKED_READY: - order_to_update = order # Работаем с оригинальным словарем - order_index = i - break - - if not order_to_update: - flash(f"Ошибка: Заказ с ID {order_id}, готовый к отправке, не найден.", "danger") - return redirect(redirect_target) - - # Получаем количество упакованных из деталей заказа - packed_quantity = int(to_decimal(order_to_update.get('qc_packing_details', {}).get('packed_quantity', '0'))) - if packed_quantity <= 0: - flash(f"Ошибка: В заказе ID {order_id} нет упакованных изделий для отправки (кол-во = 0).", "warning") - return redirect(redirect_target) - - # Валидация количества к отправке - try: - quantity_to_dispatch = int(to_decimal(quantity_to_dispatch_str).to_integral_value()) - if quantity_to_dispatch <= 0: - raise ValueError("Количество должно быть положительным") - if quantity_to_dispatch > packed_quantity: - flash(f"Ошибка: Нельзя отправить {quantity_to_dispatch} шт., так как в заказе упаковано только {packed_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 = order_to_update.get('sewing_details', {}).get('sewn_product_name', order_to_update.get('model_name', 'N/A')) - destination_display_text = '' - - # Определяем, полная или частичная отправка - is_full_dispatch = (quantity_to_dispatch == packed_quantity) - - # --- Общие действия для обоих типов отправки --- - history_items = [{'product_name': product_name, 'quantity': quantity_to_dispatch}] # Предметы для записи в историю - - shipment_details_data = { - 'type': destination_type, - 'timestamp': dispatch_time_iso, - 'quantity_shipped': quantity_to_dispatch, - 'quantity_remaining': packed_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, # ID самой отправки - 'order_id': order_id, # Ссылка на заказ - 'timestamp': dispatch_time_iso, - 'items': history_items, # Что отправили - } - 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}'" - shipment_details_data.update({'client_id': client_id, 'client_name': client_name}) - - elif destination_type == 'dor_doi_point': - # Запись в историю Дордоя - dordoi_entry = { - 'shipment_id': uuid.uuid4().hex, - 'order_id': order_id, - 'timestamp': dispatch_time_iso, - 'items': history_items, - } - 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 # Так как dordoi_shipments в основном файле - shipment_details_data.update({'destination': 'Торговая точка Дордой'}) - - else: - flash("Ошибка: Неверный тип назначения.", "danger") - return redirect(redirect_target) - - # --- Обновление заказа --- - orders[order_index]['shipment_details'] = shipment_details_data - orders[order_index]['timestamp_last_updated'] = dispatch_time_iso - # Меняем статус только при полной отправке - if is_full_dispatch: - orders[order_index]['status'] = STATUS_SHIPPED_CLIENT if destination_type == 'client' else STATUS_SHIPPED_DORDOI - # Можно добавить статус COMPLETED, если нужно - else: - # При частичной отправке статус остается 'packed_ready_to_ship', - # но нужно обновить количество упакованных в qc_packing_details - # Это усложняет логику, так как qc_packing_details содержит расчеты на ВСЮ партию. - # УПРОЩЕНИЕ: Пока считаем, что отправка всегда полная. - # Если нужна частичная, нужно будет пересчитывать qc_packing_details для остатка - # или изменить структуру хране��ия отправленных/оставшихся. - # => Отправляем все сразу. Убираем логику частичной отправки для простоты. - if not is_full_dispatch: - flash("Ошибка: Частичная отправка пока не поддерживается. Отправляйте всю партию.", "warning") - return redirect(redirect_target) - # Если дошли сюда, значит is_full_dispatch = True - orders[order_index]['status'] = STATUS_SHIPPED_CLIENT if destination_type == 'client' else STATUS_SHIPPED_DORDOI - - - main_data_changed = True - - # --- Сохранение изменений --- - if main_data_changed: - save_data(data) - upload_db_to_hf(DATA_FILE) - logging.info(f"Основные данные сохранены после отправки заказа {order_id}.") - - if client_data_changed: - save_client_data(clients) - upload_db_to_hf(CLIENT_DATA_FILE) - logging.info(f"Данные клиента {client_id} сохранены.") - - flash(f"{quantity_to_dispatch} шт. товара '{product_name}' (Заказ ID {order_id[:8]}...) успешно отправлено {destination_display_text}.", "success") - return redirect(redirect_target) - - -# --- Маршрут для работы с авансами --- (без изменений) -@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') - - # Initialize monthly salary tracking if not exists - 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: - # Получаем значения из формы, преобразуем в Decimal, затем в строку - 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 - - # data['materials'] уже обновлен, если были изменения - 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(): - """Инициирует ручное резервное копирование обоих файлов на Hugging Face.""" - files_uploaded_count = 0 - try: - logging.info("Запуск ручного резервного копирования на Hugging Face...") - # Бэкап основного файла данных - with data_lock: # Используем блокировку на всякий случай - if os.path.exists(DATA_FILE): - upload_db_to_hf(DATA_FILE) - files_uploaded_count += 1 - else: - flash(f"Локальный файл '{DATA_FILE}' не найден для бэкапа.", "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"Локальный файл '{CLIENT_DATA_FILE}' не найден для бэкапа.", "warning") - - if files_uploaded_count > 0: - flash(f"Резервное копирование {files_uploaded_count} файлов на Hugging Face инициировано.", "success") - else: - flash("Не найдено локальных файлов для инициации резервного копирования.", "warning") - - except Exception as e: - logging.error(f"Ошибка во время ручного резервного копирования: {e}", exc_info=True) - flash(f"Произошла ошибка во время резервного копирования: {e}", "danger") - - return redirect(url_for('admin_panel')) - -@app.route('/download', methods=['GET']) -def download_hf(): - """Скачивает оба файла данных с Hugging Face, перезаписывая локальные.""" - downloaded_files = [] - errors = [] - - logging.info("Запуск скачивания данных с Hugging Face...") - # Скачивание основного файла данных - try: - logging.info(f"Попытка скачивания {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} успешно скачан.") - except RepositoryNotFoundError: - msg = f"Репозиторий '{REPO_ID}' не найден на Hugging Face." - logging.error(msg) - errors.append(msg) - except HfHubHTTPError as e: - if e.response.status_code == 404: - msg = f"Файл '{DATA_FILE}' не найден в репозитории '{REPO_ID}'." - logging.warning(msg) - errors.append(msg) - else: - msg = f"Ошибка HTTP ({e.response.status_code}) при скачивании {DATA_FILE}: {e}" - logging.error(msg) - errors.append(msg) - except Exception as e: - msg = f"Неизвестная ошибка при скачивании {DATA_FILE}: {e}" - logging.error(msg, exc_info=True) - errors.append(msg) - - # Скачивание файла клиентов (даже если первый файл не скачался) - try: - logging.info(f"Попытка скачивания {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} успешно скачан.") - except RepositoryNotFoundError: - # Ошибка репозитория уже должна была быть залогирована выше - if not any(f"Репозиторий '{REPO_ID}' не найден" in err for err in errors): - msg = f"Репозиторий '{REPO_ID}' не найден на Hugging Face." - logging.error(msg) - errors.append(msg) - except HfHubHTTPError as e: - if e.response.status_code == 404: - msg = f"Файл '{CLIENT_DATA_FILE}' не найден в репозитории '{REPO_ID}'." - logging.warning(msg) - errors.append(msg) - else: - msg = f"Ошибка HTTP ({e.response.status_code}) при скачивании {CLIENT_DATA_FILE}: {e}" - logging.error(msg) - errors.append(msg) - except Exception as e: - msg = f"Неизвестная ошибка при скачивании {CLIENT_DATA_FILE}: {e}" - logging.error(msg, exc_info=True) - errors.append(msg) - - # Вывод сообщений пользователю - if downloaded_files: - flash(f"Файлы ({', '.join(downloaded_files)}) успешно скачаны и перезаписаны локально.", "success") - if errors: - flash("Во время скачивания произошли ошибки: " + "; ".join(errors), "danger") - if not downloaded_files and not errors: - # Странная ситуация, возможно, нет файлов или другая проблема - flash("Не удалось инициировать скачивание файлов.", "warning") - - # Перезагрузка данных в память после скачивания - try: - logging.info("Перезагрузка данных в память после скачивания...") - load_data() - load_client_data() - logging.info("Данные в памяти обновлены.") - except Exception as e: - logging.error(f"Ошибка при перезагрузке данных после скачивания: {e}", exc_info=True) - flash("Внимание: Файлы скачаны, но произошла ошибка при обновлении данных в приложении. Может потребоваться перезапуск.", "warning") - - - return redirect(url_for('admin_panel')) - -# 8. Маршрут "Отчеты" - Обновлен для работы с данными из ЗАКАЗОВ -@app.route('/reports', methods=['GET']) -def reports(): - # Загружаем основные данные и конфиг - data = load_data() - config = data.get('config', {}) - now = get_current_time() # Текущее время в Бишкеке - - # Получение параметров фильтрации из URL - 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' - 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("Некорректный временной диапазон.") - - except (ValueError, TypeError) as e: - flash(f"Ошибка в задании периода: {e}. Отображен отчет за текущий месяц.", "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) - - # --- Фильтрация данных по дате --- - # Фильтруем ЗАКАЗЫ, завершившие этап QC/Packing в данном периоде - completed_qc_orders = [] - all_orders_raw = data.get('orders', []) - for order_raw in all_orders_raw: - if isinstance(order_raw, dict) and 'id' in order_raw: - order_data = find_order_by_id(order_raw['id']) # Получаем с распарсенными числами - if not order_data: continue - # Фильтруем по дате завершения ОТК - qc_details = order_data.get('qc_packing_details') - if qc_details and qc_details.get('qc_timestamp'): - qc_time = parse_iso_datetime(qc_details['qc_timestamp']) - if qc_time and start_date_dt <= qc_time <= end_date_dt: - # Добавляем время отправки для отображения - shipment_time = None - ship_details = order_data.get('shipment_details') - if ship_details and ship_details.get('timestamp'): - shipment_time = parse_iso_datetime(ship_details.get('timestamp')) - order_data['shipment_time_dt'] = shipment_time - completed_qc_orders.append(order_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(o.get('qc_packing_details', {}).get('packed_quantity', 0) for o in completed_qc_orders) - total_revenue = sum(o.get('qc_packing_details', {}).get('final_price', Decimal('0')) for o in completed_qc_orders) - total_material_cost_packed = sum(o.get('qc_packing_details', {}).get('total_material_cost', Decimal('0')) for o in completed_qc_orders) - total_salary_cost_packed = sum(o.get('qc_packing_details', {}).get('total_salary_cost', Decimal('0')) for o in completed_qc_orders) - 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 = sum(o.get('cutting_details', {}).get('cutter_salary_cost', Decimal('0')) for o in completed_qc_orders) - total_sewer_salary = sum(o.get('sewing_details', {}).get('sewer_salary_cost', Decimal('0')) for o in completed_qc_orders) - total_packer_salary = sum(o.get('qc_packing_details', {}).get('packer_salary_cost', Decimal('0')) for o in completed_qc_orders) - - calculated_total_salary = total_cutter_salary + total_sewer_salary + total_packer_salary - if abs(calculated_total_salary - total_salary_cost_packed) > Decimal('0.01'): # Допускаем небольшое расхождение из-за округления - logging.warning(f"Расчетная детализация ЗП ({calculated_total_salary}) не совпадает с общей ЗП из упаковок ({total_salary_cost_packed}). Возможны расхождения.") - # Используем общую сумму из qc_packing_details как более надежную - total_salary_cost_packed = calculated_total_salary - - - # --- Сводка по продуктам --- - production_summary = {} - for order in completed_qc_orders: - qc_details = order.get('qc_packing_details', {}) - product_name = order.get('sewing_details', {}).get('sewn_product_name', order.get('model_name', 'Неизвестно')) - quantity = qc_details.get('packed_quantity', 0) - revenue = qc_details.get('final_price', Decimal('0')) - cost = qc_details.get('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, - 'completed_qc_orders': completed_qc_orders, # Передаем отфильтрованные заказы - '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) # Передаем весь словарь report_data - -# 9. Маршрут "Облако" (без изменений) -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"Файл '{original_filename}' сохранен как '{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) # Вернет имя файла или None - - # Сохраняем метаданные - file_meta = { - 'file_id': uuid.uuid4().hex, # ID для управления записью - 'original_filename': original_filename, - 'stored_filename': stored_filename, - 'thumbnail_filename': thumbnail_filename, # Имя файла миниатюры или None - '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"Ошибка при сохранении файла или создании миниатюры: {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')) - - # GET запрос - search_query = request.args.get('search', '').lower() - if search_query: - filtered_files = [ - f for f in cloud_files - if isinstance(f, dict) and ( # Добавлена проверка isinstance - 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) - - -# 10. Маршрут для скачивания файла из облака (без изменений) -@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"Ошибка при скачивании файла {filename}: {e}", exc_info=True) - flash(f"Ошибка при скачивании файла: {e}", "danger") - return redirect(url_for('cloud_storage')) - -# 11. Маршрут для отображения миниатюр (без изменений) -@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"Ошибка при отдаче миниатюры {filename}: {e}") - return "Error getting thumbnail", 500 - -# 12. Маршрут для удаления файла из облака (без изменений) -@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: # Добавлена проверка на dict - 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) # Сохраняем изменения в JSON - - # Удаляем физический файл - if file_path and os.path.exists(file_path): - os.remove(file_path) - logging.info(f"Удален файл: {file_path}") - # Удаляем миниатюру - if thumb_path and os.path.exists(thumb_path): - os.remove(thumb_path) - logging.info(f"Удалена миниатюра: {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"Ошибка при удалении файла {file_id}: {e}", exc_info=True) - flash(f"Ошибка при удалении файла: {e}", 'danger') - # Важно: Не откатываем удаление записи из JSON, если файл не удалился, - # чтобы избежать рассинхронизации. Лучше иметь запись без файла, чем файл без записи. - else: - flash('Файл для удаления не найден.', 'warning') - - return redirect(url_for('cloud_storage')) - - -# --- HTML Шаблоны --- - -# Контент заказов - ИЗМЕНЕН: Форма создания и таблица отображения ВСЕХ заказов -ORDERS_CONTENT = """ -
-
Создание нового заказа
-
-
- {# --- Клиент и Модель --- #} -
-
- - -
-
- - -
-
- - {# --- Ткань --- #} -
Ткань: *
-
-
- - -
-
- - -
-
- - -
-
- - {# --- Изделия и размерный ряд --- #} -
-
- - -
-
- - -
-
- - {# --- Фурнитура (опционально) --- #} -
Заказ фурнитуры: (опционально, укажите что нужно закупить)
-
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
- -
- - {# --- Предоплата --- #} -
-
- - -
-
- - -
- -
-
-
- -{# --- Список ВСЕХ заказов --- #} -
-
Список всех заказов
-
- -
- - - - - - - - - - - - - - - - - {% for order in orders %} - - - - - - - - - - - - - {% else %} - - {% endfor %} - {# Строка для "не найдено" при поиске #} - -
ID Клиент Модель Ткань (заказ)Фурнитура (заказ)Кол-во Статус Создан Обновлен Действия
{{ order.id[:8] }}...{{ order.client_name }}{{ order.model_name }} - - {{ order.fabric_details.name }} - ({{ order.fabric_details.quantity_ordered }} {{ order.fabric_details.unit }}) - - - {% if order.fittings_ordered %} -
    - {% for f in order.fittings_ordered %} -
  • {{ f.name }}: {{ f.quantity }} {{ f.unit }}
  • - {% endfor %} -
- {% else %}-{% endif %} -
{{ format_integer_py(order.items_quantity) }}{{ getStatusText(order.status) }}{{ order.timestamp_created[:16]|replace('T', ' ') if order.timestamp_created else '-' }}{{ order.timestamp_last_updated[:16]|replace('T', ' ') if order.timestamp_last_updated else '-' }} -
- {# TODO: Кнопка редактирования (возможно, модальное окно) #} - {# #} - {% if order.status in [STATUS_PENDING_PROCUREMENT, STATUS_CANCELLED] or order.status not in [STATUS_SHIPPED_CLIENT, STATUS_SHIPPED_DORDOI, STATUS_COMPLETED] %} -
- -
- {% endif %} -
-
Заказы отсутствуют.
-
-
-
-""" - -# Скрипты заказов - ИЗМЕНЕН: Логика для добавления/удаления строк фурнитуры, поиск -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 = """ - -
-
Заказы, ожидающие закупа
-
- {% if orders_to_procure %} -
- - - - - - - - - - - - - - - {% for order in orders_to_procure %} - - - - - - - - - - - {% endfor %} - -
ID ЗаказаКлиентМодельТкань (заказ)Кол-во изделийФурнитура (заказ)СозданДействие
{{ order.id[:8] }}...{{ order.client_name }}{{ order.model_name }}{{ order.fabric_details.name }} ({{ order.fabric_details.quantity_ordered }} {{ order.fabric_details.unit }}){{ format_integer_py(order.items_quantity) }} - {% if order.fittings_ordered %} -
    - {% for f in order.fittings_ordered %} -
  • {{ f.name }}: {{ f.quantity }} {{ f.unit }}
  • - {% endfor %} -
- {% else %}-{% endif %} -
{{ order.timestamp_created[:16]|replace('T', ' ') }} -
- {# Указываем действие #} - - -
-
-
- {% else %} - - {% endif %} -
-
- - -
-
Регистрация закупленных материалов на склад
-
-
- {# Указываем действие #} -
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - - На ск-ко изд. -
-
- - -
-
- - - -
- -
- -
- - -
-
-
-""" - -# Скрипты закупки (без изменений, т.к. форма регистрации материалов осталась) -PROCUREMENT_SCRIPTS = """ - -""" - -# Контент раскроя - ИЗМЕНЕН: Выбор ЗАКАЗА вместо ткани -CUTTING_CONTENT = """ - -
-
Заказы, ожидающие раскроя
-
- {% if orders_to_cut %} - -
- - - - - - - - - - - - - - {% for order in orders_to_cut %} - - - - - - - - - - {% endfor %} - - -
ID ЗаказаКлиентМодельТкань (заказ)Кол-во изделийДата закупаДействие
{{ order.id[:8] }}...{{ order.client_name }}{{ order.model_name }}{{ order.fabric_details.name }} ({{ order.fabric_details.quantity_ordered }} {{ order.fabric_details.unit }}){{ format_integer_py(order.items_quantity) }}{{ order.procurement_timestamp[:16]|replace('T', ' ') if order.procurement_timestamp else '-' }} - {# Кнопка для выбора заказа и открытия формы ниже #} - -
-
- {% else %} - - {% endif %} -
-
- - - - - -
-
Справка: Остатки ткани на складе
-
- {% if fabrics_on_stock %} -
- - - - {% for fabric in fabrics_on_stock %} - - - - - - - - {% endfor %} - -
НазваниеКатегорияОстатокЕд.Цена/ед
{{ fabric.name }}{{ fabric.category|default('Без кат.')}}{{ fabric.quantity_str }}{{ fabric.unit }}{{ format_currency_py(fabric.price_per_unit) }}
-
- {% else %} -

Нет тканей на складе.

- {% endif %} -
-
-""" - -# Скрипты раскроя - ИЗМЕНЕН: Логика для выбора заказа и отображения формы, поиск -CUTTING_SCRIPTS = """ - -""" - -# Контент пошива - ИЗМЕНЕН: Выбор ЗАКАЗА -SEWING_CONTENT = """ - -
-
Заказы, ожидающие пошива
-
- {% if orders_to_sew %} - -
- - - - - - - - - - - - {% for order in orders_to_sew %} - - - - - - - - - - - - {% for order in orders_to_sew %} - - - - - - - - - - {% endfor %} - - -
ID ЗаказаКлиентМодельТкань (исп.)Действия
{{ order.id[:8] }}...{{ order.client_name }}{{ order.product_name }}{{ order.get('fabric_details', {}).get('name', 'Не указана') }}Раскроено (шт)Дата раскрояДействие
{{ order.id[:8] }}...{{ order.client_name }}{{ order.model_name }}{{ order.cutting_details.fabric_name_used }} ({{ format_currency_py(order.cutting_details.fabric_used) }} {{ order.cutting_details.fabric_unit }}){{ format_integer_py(order.cutting_details.cut_quantity) }}{{ order.cutting_details.cutting_timestamp[:16]|replace('T', ' ') if order.cutting_details else '-' }} - -
-
- {% else %} - - {% endif %} -
-
- - - - -""" - -# Скрипты пошива - ИЗМЕНЕН: Логика выбора заказа, валидации кол-ва, поиск -SEWING_SCRIPTS = """ - -""" - -# Контент ОТК - ИЗМЕНЕН: Выбор ЗАКАЗА -QC_PACKING_CONTENT = """ - -
-
Заказы, ожидающие ОТК и упаковки
-
- {% if orders_to_qc %} - -
- - - - - - - - - - - - - {% for order in orders_to_qc %} - - - - - - - - - {% endfor %} - - -
ID ЗаказаКлиентИзделие (пошив)Сшито (шт)Дата пошиваДействие
{{ order.id[:8] }}...{{ order.client_name }}{{ order.sewing_details.sewn_product_name if order.sewing_details else order.model_name }}{{ format_integer_py(order.sewing_details.sewn_quantity) if order.sewing_details else '-'}}{{ order.sewing_details.sewing_timestamp[:16]|replace('T', ' ') if order.sewing_details else '-' }} - -
-
- {% 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 }} - - {# TODO: Добавить кнопку редактирования клиента #} -
Клиенты еще не добавлены.
-
-
-
- - -{% for client in clients %} {# Цикл п�� клиентам для создания модальных окон #} - -{% endfor %} {# Конец цикла по клиентам для модальных окон #} -""" - -# Скрипты Базы Клиентов (без изменений) -CLIENTS_SCRIPTS = """ - -""" - -# Контент Админ-панели - ИЗМЕНЕН: Отображение заказов по статусам, статистика по заказам -ADMIN_CONTENT = """ -

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

-

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

- - -
-
Ждут закупа

{{ pending_procurement_count }}

заказов
-
Ждут раскроя

{{ pending_cutting_count }}

заказов
-
Ждут пошива

{{ pending_sewing_count }}

заказов
-
Ждут ОТК

{{ pending_qc_count }}

заказов ({{ format_integer_py(pending_qc_quantity) }} шт.)
-
Готово к отправке

{{ items_ready_ship_qty }}

шт. в {{ items_ready_ship_count }} заказах
-
Материалы

{{ materials_count }}

позиций на складе (>0)
-
Брак (Всего)

Ткань: {{ 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' }}
Дополнительные расходы еще не добавлялись.
-
-
-
- - - - - -
- -
-
Готово к отправке
- {% if orders_ready_to_ship %} -
- - - - {% for order in orders_ready_to_ship|sort(attribute='qc_packing_details.qc_timestamp', reverse=True) %} - - - - - - - - - - {% endfor %} - -
ID ЗаказаИзделиеКол-во (шт)Себест.(общ)Цена (общ)Дата упак.Действия
{{ order.id[:8] }}...{{ order.sewing_details.sewn_product_name if order.sewing_details else order.model_name }}{{ format_integer_py(order.qc_packing_details.packed_quantity) if order.qc_packing_details else '?' }}{{ format_currency_py(order.qc_packing_details.total_cost) if order.qc_packing_details else '?' }}{{ format_currency_py(order.qc_packing_details.final_price) if order.qc_packing_details else '?' }}{{ order.qc_packing_details.qc_timestamp[:16] | replace('T', ' ') if order.qc_packing_details else 'N/A' }} - {# Форма отправки (отправляем всю партию) #} -
- {# ID Заказа #} - {# Скрытое поле с количеством, т.к. отправляем все #} - -
-
- - -
- -
- {# Текст кнопки зависит от количества #} - {% set qty_to_ship = order.qc_packing_details.packed_quantity if order.qc_packing_details else 0 %} - -
-
-
-
- {% else %} - - {% endif %} -
-
- -
-
Все Заказы
- {# Скопировано из orders.html, но без формы создания #} - -
- - - - - - - - - - - - - - - - - {% for order in all_orders|sort(attribute='timestamp_created', reverse=True) %} - - - - - - - - - - - - - {% else %} - - {% endfor %} - {# Строка для "не найдено" при поиске #} - -
ID Клиент Модель Ткань (заказ)Фурнитура (заказ)Кол-во Статус Создан Обновлен Действия
{{ order.id[:8] }}...{{ order.client_name }}{{ order.model_name }} - - {{ order.fabric_details.name }} - ({{ order.fabric_details.quantity_ordered }} {{ order.fabric_details.unit }}) - - - {% if order.fittings_ordered %} -
    - {% for f in order.fittings_ordered %} -
  • {{ f.name }}: {{ f.quantity }} {{ f.unit }}
  • - {% endfor %} -
- {% else %}-{% endif %} -
{{ format_integer_py(order.items_quantity) }}{{ getStatusText(order.status) }}{{ order.timestamp_created[:16]|replace('T', ' ') if order.timestamp_created else '-' }}{{ order.timestamp_last_updated[:16]|replace('T', ' ') if order.timestamp_last_updated else '-' }} -
- {% if order.status in [STATUS_PENDING_PROCUREMENT, STATUS_CANCELLED] or order.status not in [STATUS_SHIPPED_CLIENT, STATUS_SHIPPED_DORDOI, STATUS_COMPLETED] %} -
- -
- {% endif %} - {# Кнопка просмотра деталей заказа (если нужна) #} - -
-
Заказы отсутствуют.
-
-
-
- -
-
Список материалов на складе
- -
- - - - - - - - - - - - {% for m in materials|sort(attribute='name') %} {# Фильтрация > 0 уже в Python #} - - - - - - - - - - - {% 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_integer_py(m.items_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' }}
Нет материалов в наличии.
-
- -
-
История отправок на Дордой
- {% if dordoi_shipments %} -
- - - {% for shipment in dordoi_shipments %} {# Уже отсортировано в Python #} - - - - {# Добавлен ID Заказа #} - - - {% 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',' ') }}{{ shipment.order_id[:8] }}... - {% 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 %} -
- {% else %} - - {% endif %} -
-
- -
-
Журнал брака
-
- - - - {% for defect in defect_log|sort(attribute='timestamp', reverse=True) %} {# Сортировка по дате брака #} - - - - - {# Используем поле _view #} - - {# Используем поле _dec #} - - - - {# Используем order_id #} - {% 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.order_id[:8] if defect.order_id else 'N/A' }}...
Записи о браке отсутствуют.
-
-
- -{# Модальное окно для просмотра деталей заказа (пример) #} - -""" - -# Скрипты Админ-панели - ИЗМЕНЕН: Логика для вкладок, поиск по разным таблицам, отправка, просмотр деталей -ADMIN_SCRIPTS = """ - -""" - -# Контент Отчетов - ИЗМЕНЕН: Использует completed_qc_orders -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 order in report.completed_qc_orders|sort(attribute='qc_packing_details.qc_timestamp', reverse=True) %} - {% set qc_details = order.qc_packing_details %} {# Сокращение для удобства #} - - - - - - - - - - - {% else %}{% endfor %} -
ID ЗаказаИзделиеУпак.(шт)Брак ОТК(шт)Себест. (общ)Цена (общ)Дата ОТКСтатусДетали отправки
{{ order.id[:8] }}...{{ order.sewing_details.sewn_product_name if order.sewing_details else order.model_name }}{{ format_integer_py(qc_details.packed_quantity) if qc_details else '-'}}{{ format_integer_py(qc_details.qc_defective_quantity) if qc_details else '-'}}{{ format_currency_py(qc_details.total_cost) if qc_details else '-' }}{{ format_currency_py(qc_details.final_price) if qc_details else '-' }}{{ qc_details.qc_timestamp[:16] | replace('T', ' ') if qc_details else 'N/A' }}{{ getStatusText(order.status) }} - {% set details = order.shipment_details %} - {% if details is mapping %} {# Проверка что details это словарь #} - - {{ order.shipment_time_dt.strftime('%Y-%m-%d %H:%M') if order.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 %} -
Отпр: {{ format_integer_py(details.get('quantity_shipped', '?')) }} шт. -
- {% elif order.status == STATUS_PACKED_READY %} - {# Готово, но не отправлено #} - {% else %} - {# Другой статус или нет данных #} {% endif %} -
Нет заказов, завершивших ОТК за этот период.
-
- -
-
Брак за период
-
- - - {% 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.order_id[:8] if defect.order_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 %} -
{# Добавлен ID #} - {% for file in files %} -
{# Добавлен класс и data-search #} -
- {% 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|title }}{% endif %} - {{ format_currency_py(advance.amount) }} - - {% if advance.is_processed %}Учтено{% else %}Не учтено{% endif %} - -
История авансов пуста
-
-
-
-""" - -ADVANCES_SCRIPTS = """ - -""" - -# --- Конец HTML Шаблонов --- - -# Добавляем утилиты в контекст Jinja -@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 - } - -if __name__ == '__main__': - # Запускаем поток для периодического бэкапа - backup_thread = threading.Thread(target=periodic_backup, daemon=True) - backup_thread.start() - - try: - logging.info("Первоначальная загрузка данных...") - load_data() - load_client_data() - logging.info("Данные успешно загружены/инициализированы.") - except Exception as e: - logging.critical(f"Не удалось загрузить базы данных при запуске: {e}", exc_info=True) - # В критической ситуации, возможно, стоит прервать запуск? - # exit(1) # Раскомментировать, если нужно прервать - - logging.info("Запуск Flask приложения на http://0.0.0.0:7860") - # use_reloader=False важен при использовании фоновых потоков - app.run(debug=True, host='0.0.0.0', port=7860, use_reloader=False) \ No newline at end of file