Delete app.py
Browse files
app.py
DELETED
|
@@ -1,1160 +0,0 @@
|
|
| 1 |
-
from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, send_from_directory
|
| 2 |
-
import json
|
| 3 |
-
import os
|
| 4 |
-
import logging
|
| 5 |
-
import threading
|
| 6 |
-
import time
|
| 7 |
-
from datetime import datetime, timedelta, date
|
| 8 |
-
import pytz
|
| 9 |
-
from huggingface_hub import HfApi, hf_hub_download
|
| 10 |
-
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
|
| 11 |
-
from werkzeug.utils import secure_filename
|
| 12 |
-
import uuid
|
| 13 |
-
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
| 14 |
-
import functools
|
| 15 |
-
from PIL import Image
|
| 16 |
-
import io
|
| 17 |
-
|
| 18 |
-
# Настройки приложения
|
| 19 |
-
app = Flask(__name__)
|
| 20 |
-
app.secret_key = os.urandom(24)
|
| 21 |
-
DATA_FILE = 'data.json'
|
| 22 |
-
CLIENT_DATA_FILE = 'clients.json'
|
| 23 |
-
UPLOAD_FOLDER = 'uploads'
|
| 24 |
-
THUMBNAIL_FOLDER = os.path.join(UPLOAD_FOLDER, 'thumbnails')
|
| 25 |
-
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 26 |
-
os.makedirs(THUMBNAIL_FOLDER, exist_ok=True)
|
| 27 |
-
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
| 28 |
-
app.config['THUMBNAIL_FOLDER'] = THUMBNAIL_FOLDER
|
| 29 |
-
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
|
| 30 |
-
|
| 31 |
-
HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE")
|
| 32 |
-
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", "YOUR_READ_TOKEN_HERE")
|
| 33 |
-
REPO_ID = "Kgshop/testbasebase"
|
| 34 |
-
BISHKEK_TZ = pytz.timezone('Asia/Bishkek')
|
| 35 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 36 |
-
data_lock = threading.Lock()
|
| 37 |
-
client_data_lock = threading.Lock()
|
| 38 |
-
|
| 39 |
-
# Вспомогательные функции
|
| 40 |
-
def get_current_time():
|
| 41 |
-
return datetime.now(BISHKEK_TZ)
|
| 42 |
-
|
| 43 |
-
def load_data():
|
| 44 |
-
with data_lock:
|
| 45 |
-
try:
|
| 46 |
-
logging.info(f"Попытка скачивания {DATA_FILE} из репозитория {REPO_ID}...")
|
| 47 |
-
hf_hub_download(
|
| 48 |
-
repo_id=REPO_ID, filename=DATA_FILE, repo_type="dataset", token=HF_TOKEN_READ,
|
| 49 |
-
local_dir=".", local_dir_use_symlinks=False, force_download=True,
|
| 50 |
-
)
|
| 51 |
-
logging.info(f"{DATA_FILE} успешно скачан из Hugging Face.")
|
| 52 |
-
except RepositoryNotFoundError:
|
| 53 |
-
logging.warning(f"Репозиторий {REPO_ID} не найден.")
|
| 54 |
-
except HfHubHTTPError as e:
|
| 55 |
-
if e.response.status_code == 404:
|
| 56 |
-
logging.warning(f"Файл {DATA_FILE} не найден в репозитории {REPO_ID}.")
|
| 57 |
-
else:
|
| 58 |
-
logging.error(f"Ошибка HTTP при скачивании {DATA_FILE}: {e}")
|
| 59 |
-
except Exception as e:
|
| 60 |
-
logging.error(f"Неизвестная ошибка при скачивании {DATA_FILE}: {e}")
|
| 61 |
-
|
| 62 |
-
try:
|
| 63 |
-
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 64 |
-
data = json.load(file)
|
| 65 |
-
if not isinstance(data, dict):
|
| 66 |
-
return initialize_data_structure()
|
| 67 |
-
default_data = initialize_data_structure()
|
| 68 |
-
changed = False
|
| 69 |
-
for key in default_data.keys():
|
| 70 |
-
if key not in data:
|
| 71 |
-
data[key] = default_data[key]
|
| 72 |
-
changed = True
|
| 73 |
-
if changed:
|
| 74 |
-
save_data(data)
|
| 75 |
-
return data
|
| 76 |
-
except FileNotFoundError:
|
| 77 |
-
logging.warning(f"Локальный файл {DATA_FILE} не найден.")
|
| 78 |
-
return initialize_data_structure()
|
| 79 |
-
except json.JSONDecodeError:
|
| 80 |
-
logging.error(f"Ошибка декодирования JSON в {DATA_FILE}.")
|
| 81 |
-
return initialize_data_structure()
|
| 82 |
-
except Exception as e:
|
| 83 |
-
logging.error(f"Неизвестная ошибка при загрузке данных: {e}")
|
| 84 |
-
return initialize_data_structure()
|
| 85 |
-
|
| 86 |
-
def save_data(data):
|
| 87 |
-
try:
|
| 88 |
-
temp_file = DATA_FILE + ".tmp"
|
| 89 |
-
with open(temp_file, 'w', encoding='utf-8') as file:
|
| 90 |
-
json.dump(data, file, ensure_ascii=False, indent=4, cls=DecimalEncoder)
|
| 91 |
-
os.replace(temp_file, DATA_FILE)
|
| 92 |
-
logging.info(f"Данные сохранены в {DATA_FILE}.")
|
| 93 |
-
except Exception as e:
|
| 94 |
-
logging.error(f"Ошибка при сохранении данных: {e}")
|
| 95 |
-
|
| 96 |
-
def load_client_data():
|
| 97 |
-
with client_data_lock:
|
| 98 |
-
try:
|
| 99 |
-
hf_hub_download(
|
| 100 |
-
repo_id=REPO_ID, filename=CLIENT_DATA_FILE, repo_type="dataset", token=HF_TOKEN_READ,
|
| 101 |
-
local_dir=".", local_dir_use_symlinks=False, force_download=True,
|
| 102 |
-
)
|
| 103 |
-
except Exception as e:
|
| 104 |
-
logging.error(f"Ошибка при скачивании {CLIENT_DATA_FILE}: {e}")
|
| 105 |
-
|
| 106 |
-
try:
|
| 107 |
-
with open(CLIENT_DATA_FILE, 'r', encoding='utf-8') as file:
|
| 108 |
-
return json.load(file)
|
| 109 |
-
except FileNotFoundError:
|
| 110 |
-
return []
|
| 111 |
-
except json.JSONDecodeError:
|
| 112 |
-
return []
|
| 113 |
-
|
| 114 |
-
def save_client_data(clients):
|
| 115 |
-
try:
|
| 116 |
-
temp_file = CLIENT_DATA_FILE + ".tmp"
|
| 117 |
-
with open(temp_file, 'w', encoding='utf-8') as file:
|
| 118 |
-
json.dump(clients, file, ensure_ascii=False, indent=4)
|
| 119 |
-
os.replace(temp_file, CLIENT_DATA_FILE)
|
| 120 |
-
logging.info(f"Данные клиентов сохранены в {CLIENT_DATA_FILE}.")
|
| 121 |
-
except Exception as e:
|
| 122 |
-
logging.error(f"Ошибка при сохранении данных клиентов: {e}")
|
| 123 |
-
|
| 124 |
-
def initialize_data_structure():
|
| 125 |
-
return {
|
| 126 |
-
'materials': [], 'categories': [], 'cutting_tasks': [], 'sewing_tasks': [],
|
| 127 |
-
'qc_packing_items': [], 'defect_log': [], 'expenses': [], 'dordoi_shipments': [],
|
| 128 |
-
'cloud_files': [], 'orders': [],
|
| 129 |
-
'config': {
|
| 130 |
-
'salary_cutter_per_unit': '0.00',
|
| 131 |
-
'salary_sewer_per_unit': '0.00',
|
| 132 |
-
'salary_packer_per_unit': '0.00',
|
| 133 |
-
'margin_per_item': '0.00',
|
| 134 |
-
'advances': {'cutters': {}, 'sewers': {}, 'packers': {}}
|
| 135 |
-
}
|
| 136 |
-
}
|
| 137 |
-
|
| 138 |
-
@functools.lru_cache(maxsize=1)
|
| 139 |
-
def get_hf_api():
|
| 140 |
-
if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE":
|
| 141 |
-
logging.warning("Токен HF_TOKEN_WRITE не установлен.")
|
| 142 |
-
return None
|
| 143 |
-
return HfApi()
|
| 144 |
-
|
| 145 |
-
def upload_db_to_hf(filepath=DATA_FILE):
|
| 146 |
-
api = get_hf_api()
|
| 147 |
-
if not api or not os.path.exists(filepath):
|
| 148 |
-
return
|
| 149 |
-
try:
|
| 150 |
-
filename = os.path.basename(filepath)
|
| 151 |
-
commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z')
|
| 152 |
-
api.upload_file(
|
| 153 |
-
path_or_fileobj=filepath, path_in_repo=filename, repo_id=REPO_ID, repo_type="dataset",
|
| 154 |
-
token=HF_TOKEN_WRITE, commit_message=f"Backup {filename} {commit_time}",
|
| 155 |
-
run_as_future=True
|
| 156 |
-
)
|
| 157 |
-
logging.info(f"Загрузка {filename} инициирована.")
|
| 158 |
-
except Exception as e:
|
| 159 |
-
logging.error(f"Ошибка при загрузке {filepath}: {e}")
|
| 160 |
-
|
| 161 |
-
def periodic_backup():
|
| 162 |
-
while True:
|
| 163 |
-
time.sleep(1800)
|
| 164 |
-
if os.path.exists(DATA_FILE):
|
| 165 |
-
upload_db_to_hf(DATA_FILE)
|
| 166 |
-
if os.path.exists(CLIENT_DATA_FILE):
|
| 167 |
-
upload_db_to_hf(CLIENT_DATA_FILE)
|
| 168 |
-
|
| 169 |
-
class DecimalEncoder(json.JSONEncoder):
|
| 170 |
-
def default(self, obj):
|
| 171 |
-
if isinstance(obj, Decimal):
|
| 172 |
-
return str(obj)
|
| 173 |
-
return json.JSONEncoder.default(self, obj)
|
| 174 |
-
|
| 175 |
-
def to_decimal(value_str, default='0.00'):
|
| 176 |
-
if value_str is None or value_str == '':
|
| 177 |
-
return Decimal(default)
|
| 178 |
-
try:
|
| 179 |
-
return Decimal(str(value_str).replace(',', '.'))
|
| 180 |
-
except InvalidOperation:
|
| 181 |
-
return Decimal(default)
|
| 182 |
-
|
| 183 |
-
def parse_iso_datetime(timestamp_str):
|
| 184 |
-
if not timestamp_str:
|
| 185 |
-
return None
|
| 186 |
-
try:
|
| 187 |
-
dt = datetime.fromisoformat(timestamp_str)
|
| 188 |
-
if dt.tzinfo is None:
|
| 189 |
-
return pytz.utc.localize(dt).astimezone(BISHKEK_TZ)
|
| 190 |
-
return dt.astimezone(BISHKEK_TZ)
|
| 191 |
-
except ValueError:
|
| 192 |
-
return None
|
| 193 |
-
|
| 194 |
-
def find_item_by_id(item_id, item_list_name):
|
| 195 |
-
data = load_data()
|
| 196 |
-
items = data.get(item_list_name, [])
|
| 197 |
-
for item in items:
|
| 198 |
-
if item.get('id') == item_id:
|
| 199 |
-
return item.copy()
|
| 200 |
-
return None
|
| 201 |
-
|
| 202 |
-
def find_client_by_id(client_id):
|
| 203 |
-
clients = load_client_data()
|
| 204 |
-
for client in clients:
|
| 205 |
-
if client.get('id') == client_id:
|
| 206 |
-
return client.copy()
|
| 207 |
-
return None
|
| 208 |
-
|
| 209 |
-
def format_currency_py(value):
|
| 210 |
-
try:
|
| 211 |
-
number = to_decimal(value)
|
| 212 |
-
return f"{number:,.2f}".replace(",", " ").replace(".", ",")
|
| 213 |
-
except:
|
| 214 |
-
return "0,00"
|
| 215 |
-
|
| 216 |
-
def format_integer_py(value):
|
| 217 |
-
try:
|
| 218 |
-
number = to_decimal(value).to_integral_value(rounding=ROUND_HALF_UP)
|
| 219 |
-
return f"{number:,}".replace(",", " ")
|
| 220 |
-
except:
|
| 221 |
-
return "0"
|
| 222 |
-
|
| 223 |
-
def getStatusText(statusKey):
|
| 224 |
-
statusMap = {
|
| 225 |
-
'pending': 'Ожидает пошива',
|
| 226 |
-
'in_procurement': 'В закупке',
|
| 227 |
-
'completed': 'Завершено',
|
| 228 |
-
'pending_qc': 'Ожидает ОТК',
|
| 229 |
-
'packed_ready_to_ship': 'Готово к отправке',
|
| 230 |
-
'shipped_client': 'Отправлено клиенту',
|
| 231 |
-
'shipped_dor_doi': 'Отправлено на Дордой'
|
| 232 |
-
}
|
| 233 |
-
return statusMap.get(statusKey, statusKey)
|
| 234 |
-
|
| 235 |
-
def getStatusClass(statusKey):
|
| 236 |
-
classMap = {
|
| 237 |
-
'pending': 'status-pending text-info',
|
| 238 |
-
'in_procurement': 'status-in-procurement text-primary',
|
| 239 |
-
'completed': 'status-completed text-success',
|
| 240 |
-
'pending_qc': 'status-pending_qc text-warning',
|
| 241 |
-
'packed_ready_to_ship': 'status-packed_ready_to_ship text-ready',
|
| 242 |
-
'shipped_client': 'status-shipped_client text-shipped-client',
|
| 243 |
-
'shipped_dor_doi': 'status-shipped_dor_doi text-shipped-dordoi'
|
| 244 |
-
}
|
| 245 |
-
return classMap.get(statusKey, '')
|
| 246 |
-
|
| 247 |
-
# Маршруты
|
| 248 |
-
@app.route('/')
|
| 249 |
-
def index():
|
| 250 |
-
return redirect(url_for('admin_panel'))
|
| 251 |
-
|
| 252 |
-
@app.route('/order', methods=['GET', 'POST'])
|
| 253 |
-
def order():
|
| 254 |
-
data = load_data()
|
| 255 |
-
clients = load_client_data()
|
| 256 |
-
|
| 257 |
-
if request.method == 'POST':
|
| 258 |
-
client_id = request.form.get('client_id')
|
| 259 |
-
model = request.form.get('model').strip()
|
| 260 |
-
fabric_quantity = request.form.get('fabric_quantity')
|
| 261 |
-
fittings_quantity = request.form.get('fittings_quantity')
|
| 262 |
-
item_quantity = request.form.get('item_quantity')
|
| 263 |
-
size_range = request.form.get('size_range').strip()
|
| 264 |
-
|
| 265 |
-
if not all([client_id, model, fabric_quantity, item_quantity]):
|
| 266 |
-
flash("Заполните все обязательные поля.", "danger")
|
| 267 |
-
return redirect(url_for('order'))
|
| 268 |
-
|
| 269 |
-
try:
|
| 270 |
-
fabric_qty = to_decimal(fabric_quantity)
|
| 271 |
-
fittings_qty = to_decimal(fittings_quantity) if fittings_quantity else Decimal('0')
|
| 272 |
-
items_qty = int(to_decimal(item_quantity))
|
| 273 |
-
if fabric_qty <= 0 or items_qty <= 0:
|
| 274 |
-
raise ValueError
|
| 275 |
-
except:
|
| 276 |
-
flash("Некорректные числовые значения.", "danger")
|
| 277 |
-
return redirect(url_for('order'))
|
| 278 |
-
|
| 279 |
-
order_data = {
|
| 280 |
-
'id': uuid.uuid4().hex,
|
| 281 |
-
'client_id': client_id,
|
| 282 |
-
'model': model,
|
| 283 |
-
'fabric_quantity': str(fabric_qty),
|
| 284 |
-
'fittings_quantity': str(fittings_qty),
|
| 285 |
-
'item_quantity': items_qty,
|
| 286 |
-
'size_range': size_range,
|
| 287 |
-
'timestamp': get_current_time().isoformat(),
|
| 288 |
-
'status': 'pending'
|
| 289 |
-
}
|
| 290 |
-
|
| 291 |
-
data['orders'] = data.get('orders', []) + [order_data]
|
| 292 |
-
save_data(data)
|
| 293 |
-
flash("Заказ успешно добавлен.", "success")
|
| 294 |
-
upload_db_to_hf(DATA_FILE)
|
| 295 |
-
return redirect(url_for('order'))
|
| 296 |
-
|
| 297 |
-
orders = data.get('orders', [])
|
| 298 |
-
for order in orders:
|
| 299 |
-
client = find_client_by_id(order['client_id'])
|
| 300 |
-
order['client_name'] = client['name'] if client else "Неизвестный клиент"
|
| 301 |
-
order['fabric_quantity_str'] = format_currency_py(order['fabric_quantity'])
|
| 302 |
-
order['fittings_quantity_str'] = format_integer_py(order['fittings_quantity'])
|
| 303 |
-
order['item_quantity_str'] = format_integer_py(order['item_quantity'])
|
| 304 |
-
order['status_text'] = getStatusText(order['status'])
|
| 305 |
-
order['status_class'] = getStatusClass(order['status'])
|
| 306 |
-
|
| 307 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Создание заказа").replace('__CONTENT__', ORDER_CONTENT).replace('__SCRIPTS__', ORDER_SCRIPTS)
|
| 308 |
-
return render_template_string(html, clients=clients, orders=orders)
|
| 309 |
-
|
| 310 |
-
@app.route('/order/edit/<order_id>', methods=['GET', 'POST'])
|
| 311 |
-
def edit_order(order_id):
|
| 312 |
-
data = load_data()
|
| 313 |
-
clients = load_client_data()
|
| 314 |
-
order = find_item_by_id(order_id, 'orders')
|
| 315 |
-
|
| 316 |
-
if not order:
|
| 317 |
-
flash("Заказ не найден.", "danger")
|
| 318 |
-
return redirect(url_for('order'))
|
| 319 |
-
|
| 320 |
-
if request.method == 'POST':
|
| 321 |
-
client_id = request.form.get('client_id')
|
| 322 |
-
model = request.form.get('model').strip()
|
| 323 |
-
fabric_quantity = request.form.get('fabric_quantity')
|
| 324 |
-
fittings_quantity = request.form.get('fittings_quantity')
|
| 325 |
-
item_quantity = request.form.get('item_quantity')
|
| 326 |
-
size_range = request.form.get('size_range').strip()
|
| 327 |
-
|
| 328 |
-
try:
|
| 329 |
-
fabric_qty = to_decimal(fabric_quantity)
|
| 330 |
-
fittings_qty = to_decimal(fittings_quantity) if fittings_quantity else Decimal('0')
|
| 331 |
-
items_qty = int(to_decimal(item_quantity))
|
| 332 |
-
if fabric_qty <= 0 or items_qty <= 0:
|
| 333 |
-
raise ValueError
|
| 334 |
-
except:
|
| 335 |
-
flash("Некорректные числовые значения.", "danger")
|
| 336 |
-
return redirect(url_for('edit_order', order_id=order_id))
|
| 337 |
-
|
| 338 |
-
for i, o in enumerate(data['orders']):
|
| 339 |
-
if o['id'] == order_id:
|
| 340 |
-
data['orders'][i].update({
|
| 341 |
-
'client_id': client_id,
|
| 342 |
-
'model': model,
|
| 343 |
-
'fabric_quantity': str(fabric_qty),
|
| 344 |
-
'fittings_quantity': str(fittings_qty),
|
| 345 |
-
'item_quantity': items_qty,
|
| 346 |
-
'size_range': size_range,
|
| 347 |
-
'timestamp': get_current_time().isoformat()
|
| 348 |
-
})
|
| 349 |
-
save_data(data)
|
| 350 |
-
flash("Заказ обновлен.", "success")
|
| 351 |
-
upload_db_to_hf(DATA_FILE)
|
| 352 |
-
return redirect(url_for('order'))
|
| 353 |
-
|
| 354 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Редактирование заказа").replace('__CONTENT__', ORDER_EDIT_CONTENT).replace('__SCRIPTS__', ORDER_SCRIPTS)
|
| 355 |
-
return render_template_string(html, order=order, clients=clients)
|
| 356 |
-
|
| 357 |
-
@app.route('/order/delete/<order_id>', methods=['POST'])
|
| 358 |
-
def delete_order(order_id):
|
| 359 |
-
data = load_data()
|
| 360 |
-
data['orders'] = [o for o in data['orders'] if o['id'] != order_id]
|
| 361 |
-
save_data(data)
|
| 362 |
-
flash("Заказ удален.", "success")
|
| 363 |
-
upload_db_to_hf(DATA_FILE)
|
| 364 |
-
return redirect(url_for('order'))
|
| 365 |
-
|
| 366 |
-
@app.route('/procurement', methods=['GET', 'POST'])
|
| 367 |
-
def procurement():
|
| 368 |
-
data = load_data()
|
| 369 |
-
categories = data.get('categories', [])
|
| 370 |
-
orders = data.get('orders', [])
|
| 371 |
-
|
| 372 |
-
if request.method == 'POST':
|
| 373 |
-
order_id = request.form.get('order_id')
|
| 374 |
-
item_names = request.form.getlist('item_name[]')
|
| 375 |
-
item_quantities = request.form.getlist('item_quantity[]')
|
| 376 |
-
item_units = request.form.getlist('item_unit[]')
|
| 377 |
-
item_prices = request.form.getlist('item_price_per_unit[]')
|
| 378 |
-
item_per_unit = request.form.getlist('item_per_unit[]')
|
| 379 |
-
item_types = request.form.getlist('item_type[]')
|
| 380 |
-
item_categories = request.form.getlist('item_category[]')
|
| 381 |
-
item_new_categories = request.form.getlist('item_new_category[]')
|
| 382 |
-
|
| 383 |
-
if not item_names or all(not name.strip() for name in item_names):
|
| 384 |
-
flash("Заполните хотя бы одну строку.", "warning")
|
| 385 |
-
return redirect(url_for('procurement'))
|
| 386 |
-
|
| 387 |
-
procurement_time = get_current_time().isoformat()
|
| 388 |
-
current_materials = data.get('materials', [])
|
| 389 |
-
valid_items_processed = 0
|
| 390 |
-
|
| 391 |
-
for i in range(len(item_names)):
|
| 392 |
-
name = item_names[i].strip()
|
| 393 |
-
if not name:
|
| 394 |
-
continue
|
| 395 |
-
|
| 396 |
-
quantity = to_decimal(item_quantities[i])
|
| 397 |
-
unit = item_units[i]
|
| 398 |
-
price = to_decimal(item_prices[i])
|
| 399 |
-
items_per_unit = int(to_decimal(item_per_unit[i] or '0'))
|
| 400 |
-
item_type = item_types[i]
|
| 401 |
-
category = item_new_categories[i].strip() or item_categories[i] or "Без категории"
|
| 402 |
-
|
| 403 |
-
if not all([name, quantity, unit, price, item_type]):
|
| 404 |
-
flash(f"Ошибка в строке {i+1}: заполните все поля.", "danger")
|
| 405 |
-
continue
|
| 406 |
-
|
| 407 |
-
if category not in categories and category != "Без категории":
|
| 408 |
-
categories.append(category)
|
| 409 |
-
|
| 410 |
-
existing_material = next((m for m in current_materials if m.get('name', '').lower() == name.lower() and m.get('type') == item_type and m.get('category') == category), None)
|
| 411 |
-
if existing_material:
|
| 412 |
-
existing_material['quantity'] = str(to_decimal(existing_material.get('quantity', '0')) + quantity)
|
| 413 |
-
existing_material['price_per_unit'] = str(price)
|
| 414 |
-
existing_material['unit'] = unit
|
| 415 |
-
existing_material['items_per_unit'] = items_per_unit
|
| 416 |
-
existing_material['timestamp_last_updated'] = procurement_time
|
| 417 |
-
else:
|
| 418 |
-
new_material = {
|
| 419 |
-
'id': uuid.uuid4().hex,
|
| 420 |
-
'name': name,
|
| 421 |
-
'quantity': str(quantity),
|
| 422 |
-
'unit': unit,
|
| 423 |
-
'price_per_unit': str(price),
|
| 424 |
-
'items_per_unit': items_per_unit,
|
| 425 |
-
'type': item_type,
|
| 426 |
-
'category': category,
|
| 427 |
-
'timestamp_added': procurement_time,
|
| 428 |
-
'timestamp_last_updated': procurement_time
|
| 429 |
-
}
|
| 430 |
-
current_materials.append(new_material)
|
| 431 |
-
|
| 432 |
-
valid_items_processed += 1
|
| 433 |
-
|
| 434 |
-
if valid_items_processed:
|
| 435 |
-
data['materials'] = current_materials
|
| 436 |
-
data['categories'] = sorted(list(set(categories)))
|
| 437 |
-
if order_id:
|
| 438 |
-
for order in data['orders']:
|
| 439 |
-
if order['id'] == order_id:
|
| 440 |
-
order['status'] = 'in_procurement'
|
| 441 |
-
break
|
| 442 |
-
save_data(data)
|
| 443 |
-
flash(f"Закуп обработан: {valid_items_processed} позиций.", "success")
|
| 444 |
-
upload_db_to_hf(DATA_FILE)
|
| 445 |
-
else:
|
| 446 |
-
flash("Не обработано ни одной позиции.", "warning")
|
| 447 |
-
|
| 448 |
-
return redirect(url_for('procurement'))
|
| 449 |
-
|
| 450 |
-
materials_display = [find_item_by_id(m['id'], 'materials') for m in data.get('materials', []) if isinstance(m, dict) and 'id' in m]
|
| 451 |
-
for m in materials_display:
|
| 452 |
-
if m:
|
| 453 |
-
m['quantity_str'] = format_currency_py(m['quantity']) if m['type'] == 'fabric' else format_integer_py(m['quantity'])
|
| 454 |
-
m['price_str'] = format_currency_py(m['price_per_unit'])
|
| 455 |
-
|
| 456 |
-
for order in orders:
|
| 457 |
-
client = find_client_by_id(order['client_id'])
|
| 458 |
-
order['client_name'] = client['name'] if client else "Неизвестный клиент"
|
| 459 |
-
order['fabric_quantity_str'] = format_currency_py(order['fabric_quantity'])
|
| 460 |
-
order['fittings_quantity_str'] = format_integer_py(order['fittings_quantity'])
|
| 461 |
-
order['item_quantity_str'] = format_integer_py(order['item_quantity'])
|
| 462 |
-
|
| 463 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Закуп материалов").replace('__CONTENT__', PROCUREMENT_CONTENT).replace('__SCRIPTS__', PROCUREMENT_SCRIPTS)
|
| 464 |
-
return render_template_string(html, categories=categories, materials_display=materials_display, orders=orders)
|
| 465 |
-
|
| 466 |
-
@app.route('/cutting', methods=['GET', 'POST'])
|
| 467 |
-
def cutting():
|
| 468 |
-
data = load_data()
|
| 469 |
-
orders = data.get('orders', [])
|
| 470 |
-
|
| 471 |
-
if request.method == 'POST':
|
| 472 |
-
order_id = request.form.get('order_id')
|
| 473 |
-
cutter_id = request.form.get('cutter_id', 'unknown')
|
| 474 |
-
items_cut = int(to_decimal(request.form.get('items_cut', '0')))
|
| 475 |
-
|
| 476 |
-
if items_cut <= 0 or not order_id:
|
| 477 |
-
flash("Введите корректное количество изделий.", "danger")
|
| 478 |
-
return redirect(url_for('cutting'))
|
| 479 |
-
|
| 480 |
-
order = find_item_by_id(order_id, 'orders')
|
| 481 |
-
if not order or order['item_quantity'] < items_cut:
|
| 482 |
-
flash("Заказ не найден или количество превышает заказанное.", "danger")
|
| 483 |
-
return redirect(url_for('cutting'))
|
| 484 |
-
|
| 485 |
-
task = {
|
| 486 |
-
'id': uuid.uuid4().hex,
|
| 487 |
-
'order_id': order_id,
|
| 488 |
-
'cutter_id': cutter_id,
|
| 489 |
-
'items_cut': items_cut,
|
| 490 |
-
'timestamp': get_current_time().isoformat(),
|
| 491 |
-
'status': 'completed'
|
| 492 |
-
}
|
| 493 |
-
data['cutting_tasks'] = data.get('cutting_tasks', []) + [task]
|
| 494 |
-
save_data(data)
|
| 495 |
-
flash("Задача раскроя добавлена.", "success")
|
| 496 |
-
upload_db_to_hf(DATA_FILE)
|
| 497 |
-
return redirect(url_for('cutting'))
|
| 498 |
-
|
| 499 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Раскрой").replace('__CONTENT__', CUTTING_CONTENT).replace('__SCRIPTS__', '')
|
| 500 |
-
return render_template_string(html, orders=orders)
|
| 501 |
-
|
| 502 |
-
@app.route('/sewing', methods=['GET', 'POST'])
|
| 503 |
-
def sewing():
|
| 504 |
-
data = load_data()
|
| 505 |
-
orders = data.get('orders', [])
|
| 506 |
-
|
| 507 |
-
if request.method == 'POST':
|
| 508 |
-
order_id = request.form.get('order_id')
|
| 509 |
-
sewer_id = request.form.get('sewer_id', 'unknown')
|
| 510 |
-
items_sewn = int(to_decimal(request.form.get('items_sewn', '0')))
|
| 511 |
-
|
| 512 |
-
if items_sewn <= 0 or not order_id:
|
| 513 |
-
flash("Введите корректное количество изделий.", "danger")
|
| 514 |
-
return redirect(url_for('sewing'))
|
| 515 |
-
|
| 516 |
-
order = find_item_by_id(order_id, 'orders')
|
| 517 |
-
if not order or order['item_quantity'] < items_sewn:
|
| 518 |
-
flash("Заказ не найден или количество превышает заказанное.", "danger")
|
| 519 |
-
return redirect(url_for('sewing'))
|
| 520 |
-
|
| 521 |
-
task = {
|
| 522 |
-
'id': uuid.uuid4().hex,
|
| 523 |
-
'order_id': order_id,
|
| 524 |
-
'sewer_id': sewer_id,
|
| 525 |
-
'items_sewn': items_sewn,
|
| 526 |
-
'timestamp': get_current_time().isoformat(),
|
| 527 |
-
'status': 'completed'
|
| 528 |
-
}
|
| 529 |
-
data['sewing_tasks'] = data.get('sewing_tasks', []) + [task]
|
| 530 |
-
save_data(data)
|
| 531 |
-
flash("Задача пошива добавлена.", "success")
|
| 532 |
-
upload_db_to_hf(DATA_FILE)
|
| 533 |
-
return redirect(url_for('sewing'))
|
| 534 |
-
|
| 535 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Пошив").replace('__CONTENT__', SEWING_CONTENT).replace('__SCRIPTS__', '')
|
| 536 |
-
return render_template_string(html, orders=orders)
|
| 537 |
-
|
| 538 |
-
@app.route('/admin_panel')
|
| 539 |
-
def admin_panel():
|
| 540 |
-
data = load_data()
|
| 541 |
-
clients = load_client_data()
|
| 542 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_CONTENT).replace('__SCRIPTS__', ADMIN_SCRIPTS)
|
| 543 |
-
return render_template_string(html, data=data, clients=clients)
|
| 544 |
-
|
| 545 |
-
@app.route('/reports', methods=['GET', 'POST'])
|
| 546 |
-
def reports():
|
| 547 |
-
data = load_data()
|
| 548 |
-
config = data.get('config', {})
|
| 549 |
-
advances = config.get('advances', {'cutters': {}, 'sewers': {}, 'packers': {}})
|
| 550 |
-
|
| 551 |
-
if request.method == 'POST' and 'advance' in request.form:
|
| 552 |
-
worker_type = request.form.get('worker_type')
|
| 553 |
-
worker_id = request.form.get('worker_id', 'general')
|
| 554 |
-
amount = to_decimal(request.form.get('advance_amount'))
|
| 555 |
-
|
| 556 |
-
if worker_type in ['cutters', 'sewers', 'packers'] and amount > 0:
|
| 557 |
-
if worker_id not in advances[worker_type]:
|
| 558 |
-
advances[worker_type][worker_id] = Decimal('0')
|
| 559 |
-
advances[worker_type][worker_id] += amount
|
| 560 |
-
data['config']['advances'] = advances
|
| 561 |
-
save_data(data)
|
| 562 |
-
flash(f"Аванс {format_currency_py(amount)} добавлен для {worker_type}.", "success")
|
| 563 |
-
upload_db_to_hf(DATA_FILE)
|
| 564 |
-
|
| 565 |
-
total_cutter_salary = sum(to_decimal(task['items_cut']) * to_decimal(config.get('salary_cutter_per_unit', '0')) for task in data.get('cutting_tasks', []))
|
| 566 |
-
total_sewer_salary = sum(to_decimal(task['items_sewn']) * to_decimal(config.get('salary_sewer_per_unit', '0')) for task in data.get('sewing_tasks', []))
|
| 567 |
-
total_packer_salary = sum(to_decimal(item.get('quantity', '0')) * to_decimal(config.get('salary_packer_per_unit', '0')) for item in data.get('qc_packing_items', []))
|
| 568 |
-
|
| 569 |
-
report_data = {
|
| 570 |
-
'total_cutter_salary': total_cutter_salary,
|
| 571 |
-
'total_sewer_salary': total_sewer_salary,
|
| 572 |
-
'total_packer_salary': total_packer_salary,
|
| 573 |
-
'advances': {
|
| 574 |
-
'cutters': sum(advances['cutters'].values()),
|
| 575 |
-
'sewers': sum(advances['sewers'].values()),
|
| 576 |
-
'packers': sum(advances['packers'].values())
|
| 577 |
-
}
|
| 578 |
-
}
|
| 579 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
|
| 580 |
-
return render_template_string(html, report=report_data, format_currency_py=format_currency_py)
|
| 581 |
-
|
| 582 |
-
@app.route('/cloud_storage', methods=['GET', 'POST'])
|
| 583 |
-
def cloud_storage():
|
| 584 |
-
data = load_data()
|
| 585 |
-
if request.method == 'POST':
|
| 586 |
-
file = request.files.get('file')
|
| 587 |
-
if file and file.filename:
|
| 588 |
-
filename = secure_filename(file.filename)
|
| 589 |
-
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
| 590 |
-
file.save(filepath)
|
| 591 |
-
file_data = {
|
| 592 |
-
'id': uuid.uuid4().hex,
|
| 593 |
-
'filename': filename,
|
| 594 |
-
'timestamp': get_current_time().isoformat()
|
| 595 |
-
}
|
| 596 |
-
data['cloud_files'] = data.get('cloud_files', []) + [file_data]
|
| 597 |
-
save_data(data)
|
| 598 |
-
upload_db_to_hf(DATA_FILE)
|
| 599 |
-
flash("Файл загружен.", "success")
|
| 600 |
-
return redirect(url_for('cloud_storage'))
|
| 601 |
-
|
| 602 |
-
files = data.get('cloud_files', [])
|
| 603 |
-
html = BASE_TEMPLATE.replace('__TITLE__', "Облако").replace('__CONTENT__', CLOUD_CONTENT).replace('__SCRIPTS__', '')
|
| 604 |
-
return render_template_string(html, files=files)
|
| 605 |
-
|
| 606 |
-
@app.route('/uploads/<filename>')
|
| 607 |
-
def uploaded_file(filename):
|
| 608 |
-
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
|
| 609 |
-
|
| 610 |
-
# Шаблоны HTML
|
| 611 |
-
BASE_TEMPLATE = """
|
| 612 |
-
<!DOCTYPE html>
|
| 613 |
-
<html lang="ru">
|
| 614 |
-
<head>
|
| 615 |
-
<meta charset="UTF-8">
|
| 616 |
-
<title>__TITLE__</title>
|
| 617 |
-
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
| 618 |
-
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
|
| 619 |
-
<style>
|
| 620 |
-
.clickable-card { cursor: pointer; }
|
| 621 |
-
.status-pending { font-weight: bold; }
|
| 622 |
-
.status-in-procurement { font-weight: bold; }
|
| 623 |
-
.status-completed { font-weight: bold; }
|
| 624 |
-
.text-info { color: #0dcaf0; }
|
| 625 |
-
.text-primary { color: #0d6efd; }
|
| 626 |
-
.text-success { color: #198754; }
|
| 627 |
-
.text-warning { color: #ffc107; }
|
| 628 |
-
.text-ready { color: #6f42c1; }
|
| 629 |
-
.text-shipped-client { color: #28a745; }
|
| 630 |
-
.text-shipped-dordoi { color: #17a2b8; }
|
| 631 |
-
</style>
|
| 632 |
-
</head>
|
| 633 |
-
<body>
|
| 634 |
-
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
|
| 635 |
-
<div class="container-fluid">
|
| 636 |
-
<a class="navbar-brand" href="{{ url_for('index') }}">Швейное производство</a>
|
| 637 |
-
<div class="collapse navbar-collapse">
|
| 638 |
-
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
|
| 639 |
-
<li class="nav-item"><a class="nav-link" href="{{ url_for('order') }}">Заказ</a></li>
|
| 640 |
-
<li class="nav-item"><a class="nav-link" href="{{ url_for('procurement') }}">Закуп</a></li>
|
| 641 |
-
<li class="nav-item"><a class="nav-link" href="{{ url_for('cutting') }}">Раскрой</a></li>
|
| 642 |
-
<li class="nav-item"><a class="nav-link" href="{{ url_for('sewing') }}">Пошив</a></li>
|
| 643 |
-
<li class="nav-item"><a class="nav-link" href="{{ url_for('admin_panel') }}">Админ-панель</a></li>
|
| 644 |
-
<li class="nav-item"><a class="nav-link" href="{{ url_for('reports') }}">Отчеты</a></li>
|
| 645 |
-
<li class="nav-item"><a class="nav-link" href="{{ url_for('cloud_storage') }}">Облако</a></li>
|
| 646 |
-
</ul>
|
| 647 |
-
</div>
|
| 648 |
-
</div>
|
| 649 |
-
</nav>
|
| 650 |
-
<div class="container mt-4">
|
| 651 |
-
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 652 |
-
{% if messages %}
|
| 653 |
-
{% for category, message in messages %}
|
| 654 |
-
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
| 655 |
-
{{ message }}
|
| 656 |
-
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
| 657 |
-
</div>
|
| 658 |
-
{% endfor %}
|
| 659 |
-
{% endif %}
|
| 660 |
-
{% endwith %}
|
| 661 |
-
__CONTENT__
|
| 662 |
-
</div>
|
| 663 |
-
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
| 664 |
-
__SCRIPTS__
|
| 665 |
-
</body>
|
| 666 |
-
</html>
|
| 667 |
-
"""
|
| 668 |
-
|
| 669 |
-
ORDER_CONTENT = """
|
| 670 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 671 |
-
<h1 class="h2"><i class="fas fa-file-invoice me-2"></i>Создание заказа</h1>
|
| 672 |
-
</div>
|
| 673 |
-
<div class="card mb-4">
|
| 674 |
-
<div class="card-header">Новый заказ</div>
|
| 675 |
-
<div class="card-body">
|
| 676 |
-
<form method="POST">
|
| 677 |
-
<div class="mb-3">
|
| 678 |
-
<label for="client_id" class="form-label">Клиент</label>
|
| 679 |
-
<select class="form-select" id="client_id" name="client_id" required>
|
| 680 |
-
<option value="">-- Выберите клиента --</option>
|
| 681 |
-
{% for client in clients %}
|
| 682 |
-
<option value="{{ client.id }}">{{ client.name }} ({{ client.phone }})</option>
|
| 683 |
-
{% endfor %}
|
| 684 |
-
</select>
|
| 685 |
-
</div>
|
| 686 |
-
<div class="mb-3">
|
| 687 |
-
<label for="model" class="form-label">Модель</label>
|
| 688 |
-
<input type="text" class="form-control" id="model" name="model" required>
|
| 689 |
-
</div>
|
| 690 |
-
<div class="mb-3">
|
| 691 |
-
<label for="fabric_quantity" class="form-label">Количество ткани</label>
|
| 692 |
-
<input type="number" step="0.01" class="form-control" id="fabric_quantity" name="fabric_quantity" required>
|
| 693 |
-
</div>
|
| 694 |
-
<div class="mb-3">
|
| 695 |
-
<label for="fittings_quantity" class="form-label">Количество фурнитуры</label>
|
| 696 |
-
<input type="number" class="form-control" id="fittings_quantity" name="fittings_quantity">
|
| 697 |
-
</div>
|
| 698 |
-
<div class="mb-3">
|
| 699 |
-
<label for="item_quantity" class="form-label">Количество изделий</label>
|
| 700 |
-
<input type="number" class="form-control" id="item_quantity" name="item_quantity" required>
|
| 701 |
-
</div>
|
| 702 |
-
<div class="mb-3">
|
| 703 |
-
<label for="size_range" class="form-label">Размерный ряд</label>
|
| 704 |
-
<input type="text" class="form-control" id="size_range" name="size_range">
|
| 705 |
-
</div>
|
| 706 |
-
<button type="submit" class="btn btn-primary">Добавить заказ</button>
|
| 707 |
-
</form>
|
| 708 |
-
</div>
|
| 709 |
-
</div>
|
| 710 |
-
<div class="card">
|
| 711 |
-
<div class="card-header">Список заказов</div>
|
| 712 |
-
<div class="card-body">
|
| 713 |
-
<table class="table table-striped">
|
| 714 |
-
<thead>
|
| 715 |
-
<tr>
|
| 716 |
-
<th>ID</th><th>Клиент</th><th>Модель</th><th>Ткань</th><th>Фурнитура</th><th>Изделия</th><th>Размеры</th><th>Статус</th><th>Дата</th><th>Действия</th>
|
| 717 |
-
</tr>
|
| 718 |
-
</thead>
|
| 719 |
-
<tbody>
|
| 720 |
-
{% for order in orders %}
|
| 721 |
-
<tr>
|
| 722 |
-
<td>{{ order.id[:8] }}</td>
|
| 723 |
-
<td>{{ order.client_name }}</td>
|
| 724 |
-
<td>{{ order.model }}</td>
|
| 725 |
-
<td>{{ order.fabric_quantity_str }}</td>
|
| 726 |
-
<td>{{ order.fittings_quantity_str }}</td>
|
| 727 |
-
<td>{{ order.item_quantity_str }}</td>
|
| 728 |
-
<td>{{ order.size_range }}</td>
|
| 729 |
-
<td class="{{ order.status_class }}">{{ order.status_text }}</td>
|
| 730 |
-
<td>{{ order.timestamp[:16] }}</td>
|
| 731 |
-
<td>
|
| 732 |
-
<a href="{{ url_for('edit_order', order_id=order.id) }}" class="btn btn-sm btn-warning">Ред.</a>
|
| 733 |
-
<form action="{{ url_for('delete_order', order_id=order.id) }}" method="POST" style="display:inline;">
|
| 734 |
-
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Удалить заказ?')">Удалить</button>
|
| 735 |
-
</form>
|
| 736 |
-
</td>
|
| 737 |
-
</tr>
|
| 738 |
-
{% endfor %}
|
| 739 |
-
</tbody>
|
| 740 |
-
</table>
|
| 741 |
-
</div>
|
| 742 |
-
</div>
|
| 743 |
-
"""
|
| 744 |
-
|
| 745 |
-
ORDER_EDIT_CONTENT = """
|
| 746 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 747 |
-
<h1 class="h2"><i class="fas fa-edit me-2"></i>Редактирование заказа</h1>
|
| 748 |
-
</div>
|
| 749 |
-
<div class="card">
|
| 750 |
-
<div class="card-header">Редактировать заказ {{ order.id[:8] }}</div>
|
| 751 |
-
<div class="card-body">
|
| 752 |
-
<form method="POST">
|
| 753 |
-
<div class="mb-3">
|
| 754 |
-
<label for="client_id" class="form-label">Клиент</label>
|
| 755 |
-
<select class="form-select" id="client_id" name="client_id" required>
|
| 756 |
-
{% for client in clients %}
|
| 757 |
-
<option value="{{ client.id }}" {% if client.id == order.client_id %}selected{% endif %}>{{ client.name }} ({{ client.phone }})</option>
|
| 758 |
-
{% endfor %}
|
| 759 |
-
</select>
|
| 760 |
-
</div>
|
| 761 |
-
<div class="mb-3">
|
| 762 |
-
<label for="model" class="form-label">Модель</label>
|
| 763 |
-
<input type="text" class="form-control" id="model" name="model" value="{{ order.model }}" required>
|
| 764 |
-
</div>
|
| 765 |
-
<div class="mb-3">
|
| 766 |
-
<label for="fabric_quantity" class="form-label">Количество ткани</label>
|
| 767 |
-
<input type="number" step="0.01" class="form-control" id="fabric_quantity" name="fabric_quantity" value="{{ order.fabric_quantity }}" required>
|
| 768 |
-
</div>
|
| 769 |
-
<div class="mb-3">
|
| 770 |
-
<label for="fittings_quantity" class="form-label">Количество фурнитуры</label>
|
| 771 |
-
<input type="number" class="form-control" id="fittings_quantity" name="fittings_quantity" value="{{ order.fittings_quantity }}">
|
| 772 |
-
</div>
|
| 773 |
-
<div class="mb-3">
|
| 774 |
-
<label for="item_quantity" class="form-label">Количество изделий</label>
|
| 775 |
-
<input type="number" class="form-control" id="item_quantity" name="item_quantity" value="{{ order.item_quantity }}" required>
|
| 776 |
-
</div>
|
| 777 |
-
<div class="mb-3">
|
| 778 |
-
<label for="size_range" class="form-label">Размерный ряд</label>
|
| 779 |
-
<input type="text" class="form-control" id="size_range" name="size_range" value="{{ order.size_range }}">
|
| 780 |
-
</div>
|
| 781 |
-
<button type="submit" class="btn btn-primary">Сохранить</button>
|
| 782 |
-
</form>
|
| 783 |
-
</div>
|
| 784 |
-
</div>
|
| 785 |
-
"""
|
| 786 |
-
|
| 787 |
-
PROCUREMENT_CONTENT = """
|
| 788 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 789 |
-
<h1 class="h2"><i class="fas fa-shopping-cart me-2"></i>Закуп материалов</h1>
|
| 790 |
-
</div>
|
| 791 |
-
<div class="card mb-4">
|
| 792 |
-
<div class="card-header">Выбор заказа</div>
|
| 793 |
-
<div class="card-body">
|
| 794 |
-
<form id="order-select-form">
|
| 795 |
-
<div class="mb-3">
|
| 796 |
-
<label for="order_id" class="form-label">Выберите заказ</label>
|
| 797 |
-
<select class="form-select" id="order_id" name="order_id">
|
| 798 |
-
<option value="">-- Без заказа --</option>
|
| 799 |
-
{% for order in orders %}
|
| 800 |
-
<option value="{{ order.id }}">{{ order.client_name }} - {{ order.model }} ({{ order.item_quantity_str }} шт.)</option>
|
| 801 |
-
{% endfor %}
|
| 802 |
-
</select>
|
| 803 |
-
</div>
|
| 804 |
-
</form>
|
| 805 |
-
</div>
|
| 806 |
-
</div>
|
| 807 |
-
<div class="card mb-4">
|
| 808 |
-
<div class="card-header">Новый закуп</div>
|
| 809 |
-
<div class="card-body">
|
| 810 |
-
<form method="POST">
|
| 811 |
-
<input type="hidden" name="order_id" id="hidden_order_id">
|
| 812 |
-
<table class="table" id="procurement-table">
|
| 813 |
-
<thead>
|
| 814 |
-
<tr>
|
| 815 |
-
<th>Название</th><th>Количество</th><th>Ед.</th><th>Цена/ед.</th><th>На ед.</th><th>Тип</th><th>Категория</th><th></th>
|
| 816 |
-
</tr>
|
| 817 |
-
</thead>
|
| 818 |
-
<tbody>
|
| 819 |
-
<tr>
|
| 820 |
-
<td><input type="text" class="form-control" name="item_name[]"></td>
|
| 821 |
-
<td><input type="number" step="0.01" class="form-control" name="item_quantity[]"></td>
|
| 822 |
-
<td><input type="text" class="form-control" name="item_unit[]"></td>
|
| 823 |
-
<td><input type="number" step="0.01" class="form-control" name="item_price_per_unit[]"></td>
|
| 824 |
-
<td><input type="number" class="form-control" name="item_per_unit[]"></td>
|
| 825 |
-
<td>
|
| 826 |
-
<select class="form-select" name="item_type[]">
|
| 827 |
-
<option value="fabric">Ткань</option>
|
| 828 |
-
<option value="fittings">Фурнитура</option>
|
| 829 |
-
</select>
|
| 830 |
-
</td>
|
| 831 |
-
<td>
|
| 832 |
-
<select class="form-select category-select" name="item_category[]">
|
| 833 |
-
<option value="">-- Выберите категорию --</option>
|
| 834 |
-
{% for category in categories %}
|
| 835 |
-
<option value="{{ category }}">{{ category }}</option>
|
| 836 |
-
{% endfor %}
|
| 837 |
-
<option value="__new__">Новая категория</option>
|
| 838 |
-
</select>
|
| 839 |
-
<input type="text" class="form-control new-category-input" name="item_new_category[]" style="display:none;">
|
| 840 |
-
</td>
|
| 841 |
-
<td><button type="button" class="btn btn-danger btn-sm remove-row">Удалить</button></td>
|
| 842 |
-
</tr>
|
| 843 |
-
</tbody>
|
| 844 |
-
</table>
|
| 845 |
-
<button type="button" class="btn btn-secondary mb-3" id="add-row">Добавить строку</button>
|
| 846 |
-
<button type="submit" class="btn btn-primary">Зарегистрировать закуп</button>
|
| 847 |
-
</form>
|
| 848 |
-
</div>
|
| 849 |
-
</div>
|
| 850 |
-
<div class="card">
|
| 851 |
-
<div class="card-header">Текущие материалы</div>
|
| 852 |
-
<div class="card-body">
|
| 853 |
-
<table class="table">
|
| 854 |
-
<thead>
|
| 855 |
-
<tr>
|
| 856 |
-
<th>ID</th><th>Название</th><th>Количество</th><th>Цена</th><th>Тип</th><th>Категория</th>
|
| 857 |
-
</tr>
|
| 858 |
-
</thead>
|
| 859 |
-
<tbody>
|
| 860 |
-
{% for m in materials_display %}
|
| 861 |
-
<tr>
|
| 862 |
-
<td>{{ m.id[:8] }}</td>
|
| 863 |
-
<td>{{ m.name }}</td>
|
| 864 |
-
<td>{{ m.quantity_str }}</td>
|
| 865 |
-
<td>{{ m.price_str }}</td>
|
| 866 |
-
<td>{{ m.type }}</td>
|
| 867 |
-
<td>{{ m.category }}</td>
|
| 868 |
-
</tr>
|
| 869 |
-
{% endfor %}
|
| 870 |
-
</tbody>
|
| 871 |
-
</table>
|
| 872 |
-
</div>
|
| 873 |
-
</div>
|
| 874 |
-
"""
|
| 875 |
-
|
| 876 |
-
CUTTING_CONTENT = """
|
| 877 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 878 |
-
<h1 class="h2"><i class="fas fa-cut me-2"></i>Раскрой</h1>
|
| 879 |
-
</div>
|
| 880 |
-
<div class="card">
|
| 881 |
-
<div class="card-header">Добавить задачу раскроя</div>
|
| 882 |
-
<div class="card-body">
|
| 883 |
-
<form method="POST">
|
| 884 |
-
<div class="mb-3">
|
| 885 |
-
<label for="order_id" class="form-label">Заказ</label>
|
| 886 |
-
<select class="form-select" id="order_id" name="order_id" required>
|
| 887 |
-
<option value="">-- Выберите заказ --</option>
|
| 888 |
-
{% for order in orders %}
|
| 889 |
-
<option value="{{ order.id }}">{{ order.model }} ({{ order.item_quantity }} шт.)</option>
|
| 890 |
-
{% endfor %}
|
| 891 |
-
</select>
|
| 892 |
-
</div>
|
| 893 |
-
<div class="mb-3">
|
| 894 |
-
<label for="cutter_id" class="form-label">Раскройщик</label>
|
| 895 |
-
<input type="text" class="form-control" id="cutter_id" name="cutter_id" placeholder="ID раскройщика">
|
| 896 |
-
</div>
|
| 897 |
-
<div class="mb-3">
|
| 898 |
-
<label for="items_cut" class="form-label">Количество раскроенных изделий</label>
|
| 899 |
-
<input type="number" class="form-control" id="items_cut" name="items_cut" required>
|
| 900 |
-
</div>
|
| 901 |
-
<button type="submit" class="btn btn-primary">Добавить</button>
|
| 902 |
-
</form>
|
| 903 |
-
</div>
|
| 904 |
-
</div>
|
| 905 |
-
"""
|
| 906 |
-
|
| 907 |
-
SEWING_CONTENT = """
|
| 908 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 909 |
-
<h1 class="h2"><i class="fas fa-sewing-machine me-2"></i>Пошив</h1>
|
| 910 |
-
</div>
|
| 911 |
-
<div class="card">
|
| 912 |
-
<div class="card-header">Добавить задачу пошива</div>
|
| 913 |
-
<div class="card-body">
|
| 914 |
-
<form method="POST">
|
| 915 |
-
<div class="mb-3">
|
| 916 |
-
<label for="order_id" class="form-label">Заказ</label>
|
| 917 |
-
<select class="form-select" id="order_id" name="order_id" required>
|
| 918 |
-
<option value="">-- Выберите заказ --</option>
|
| 919 |
-
{% for order in orders %}
|
| 920 |
-
<option value="{{ order.id }}">{{ order.model }} ({{ order.item_quantity }} шт.)</option>
|
| 921 |
-
{% endfor %}
|
| 922 |
-
</select>
|
| 923 |
-
</div>
|
| 924 |
-
<div class="mb-3">
|
| 925 |
-
<label for="sewer_id" class="form-label">Швея</label>
|
| 926 |
-
<input type="text" class="form-control" id="sewer_id" name="sewer_id" placeholder="ID швеи">
|
| 927 |
-
</div>
|
| 928 |
-
<div class="mb-3">
|
| 929 |
-
<label for="items_sewn" class="form-label">Количество пошитых изделий</label>
|
| 930 |
-
<input type="number" class="form-control" id="items_sewn" name="items_sewn" required>
|
| 931 |
-
</div>
|
| 932 |
-
<button type="submit" class="btn btn-primary">Добавить</button>
|
| 933 |
-
</form>
|
| 934 |
-
</div>
|
| 935 |
-
</div>
|
| 936 |
-
"""
|
| 937 |
-
|
| 938 |
-
ADMIN_CONTENT = """
|
| 939 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 940 |
-
<h1 class="h2"><i class="fas fa-cogs me-2"></i>Админ-панель</h1>
|
| 941 |
-
</div>
|
| 942 |
-
<div class="row">
|
| 943 |
-
<div class="col-md-6">
|
| 944 |
-
<div class="card mb-4">
|
| 945 |
-
<div class="card-header">Конфигурация</div>
|
| 946 |
-
<div class="card-body">
|
| 947 |
-
<form method="POST" action="{{ url_for('admin_panel') }}">
|
| 948 |
-
<div class="mb-3">
|
| 949 |
-
<label>ЗП раскройщика за единицу</label>
|
| 950 |
-
<input type="number" step="0.01" class="form-control" name="salary_cutter_per_unit" value="{{ data.config.salary_cutter_per_unit }}">
|
| 951 |
-
</div>
|
| 952 |
-
<div class="mb-3">
|
| 953 |
-
<label>ЗП швеи за единицу</label>
|
| 954 |
-
<input type="number" step="0.01" class="form-control" name="salary_sewer_per_unit" value="{{ data.config.salary_sewer_per_unit }}">
|
| 955 |
-
</div>
|
| 956 |
-
<div class="mb-3">
|
| 957 |
-
<label>ЗП упаковщика за единицу</label>
|
| 958 |
-
<input type="number" step="0.01" class="form-control" name="salary_packer_per_unit" value="{{ data.config.salary_packer_per_unit }}">
|
| 959 |
-
</div>
|
| 960 |
-
<button type="submit" class="btn btn-primary">Сохранить</button>
|
| 961 |
-
</form>
|
| 962 |
-
</div>
|
| 963 |
-
</div>
|
| 964 |
-
</div>
|
| 965 |
-
<div class="col-md-6">
|
| 966 |
-
<div class="card mb-4">
|
| 967 |
-
<div class="card-header">Клиенты</div>
|
| 968 |
-
<div class="card-body">
|
| 969 |
-
<ul class="list-group">
|
| 970 |
-
{% for client in clients %}
|
| 971 |
-
<li class="list-group-item">{{ client.name }} - {{ client.phone }}</li>
|
| 972 |
-
{% endfor %}
|
| 973 |
-
</ul>
|
| 974 |
-
</div>
|
| 975 |
-
</div>
|
| 976 |
-
</div>
|
| 977 |
-
</div>
|
| 978 |
-
"""
|
| 979 |
-
|
| 980 |
-
REPORTS_CONTENT = """
|
| 981 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 982 |
-
<h1 class="h2"><i class="fas fa-chart-line me-2"></i>Отчеты</h1>
|
| 983 |
-
</div>
|
| 984 |
-
<div class="card">
|
| 985 |
-
<div class="card-header">Общая информация</div>
|
| 986 |
-
<div class="card-body">
|
| 987 |
-
<p>ЗП раскройщиков: {{ format_currency_py(report.total_cutter_salary - report.advances.cutters) }} сом</p>
|
| 988 |
-
<p>ЗП швей: {{ format_currency_py(report.total_sewer_salary - report.advances.sewers) }} сом</p>
|
| 989 |
-
<p>ЗП упаковщиков: {{ format_currency_py(report.total_packer_salary - report.advances.packers) }} сом</p>
|
| 990 |
-
<p>Общие авансы: {{ format_currency_py(report.advances.cutters + report.advances.sewers + report.advances.packers) }} сом</p>
|
| 991 |
-
<button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#salaryBreakdownModal">Детализация зарплат</button>
|
| 992 |
-
</div>
|
| 993 |
-
</div>
|
| 994 |
-
|
| 995 |
-
<div class="modal fade" id="salaryBreakdownModal" tabindex="-1" aria-labelledby="salaryBreakdownModalLabel" aria-hidden="true">
|
| 996 |
-
<div class="modal-dialog">
|
| 997 |
-
<div class="modal-content">
|
| 998 |
-
<div class="modal-header">
|
| 999 |
-
<h5 class="modal-title" id="salaryBreakdownModalLabel">Детализация зарплат</h5>
|
| 1000 |
-
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
| 1001 |
-
</div>
|
| 1002 |
-
<div class="modal-body">
|
| 1003 |
-
<ul class="list-group list-group-flush">
|
| 1004 |
-
<li class="list-group-item d-flex justify-content-between align-items-center">
|
| 1005 |
-
ЗП Раскройщиков: {{ format_currency_py(report.total_cutter_salary - report.advances.cutters) }} сом
|
| 1006 |
-
<button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#advanceModal" data-type="cutters">Аванс</button>
|
| 1007 |
-
</li>
|
| 1008 |
-
<li class="list-group-item d-flex justify-content-between align-items-center">
|
| 1009 |
-
ЗП Швей: {{ format_currency_py(report.total_sewer_salary - report.advances.sewers) }} сом
|
| 1010 |
-
<button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#advanceModal" data-type="sewers">Аванс</button>
|
| 1011 |
-
</li>
|
| 1012 |
-
<li class="list-group-item d-flex justify-content-between align-items-center">
|
| 1013 |
-
ЗП Упаковщиков: {{ format_currency_py(report.total_packer_salary - report.advances.packers) }} сом
|
| 1014 |
-
<button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#advanceModal" data-type="packers">Аванс</button>
|
| 1015 |
-
</li>
|
| 1016 |
-
<li class="list-group-item d-flex justify-content-between align-items-center fw-bold">
|
| 1017 |
-
Авансы: {{ format_currency_py(report.advances.cutters + report.advances.sewers + report.advances.packers) }} сом
|
| 1018 |
-
</li>
|
| 1019 |
-
</ul>
|
| 1020 |
-
</div>
|
| 1021 |
-
<div class="modal-footer">
|
| 1022 |
-
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
| 1023 |
-
</div>
|
| 1024 |
-
</div>
|
| 1025 |
-
</div>
|
| 1026 |
-
</div>
|
| 1027 |
-
|
| 1028 |
-
<div class="modal fade" id="advanceModal" tabindex="-1" aria-labelledby="advanceModalLabel" aria-hidden="true">
|
| 1029 |
-
<div class="modal-dialog">
|
| 1030 |
-
<div class="modal-content">
|
| 1031 |
-
<div class="modal-header">
|
| 1032 |
-
<h5 class="modal-title" id="advanceModalLabel">Выдать аванс</h5>
|
| 1033 |
-
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
| 1034 |
-
</div>
|
| 1035 |
-
<form method="POST">
|
| 1036 |
-
<div class="modal-body">
|
| 1037 |
-
<input type="hidden" name="worker_type" id="worker_type">
|
| 1038 |
-
<div class="mb-3">
|
| 1039 |
-
<label for="advance_amount" class="form-label">Сумма аванса</label>
|
| 1040 |
-
<input type="number" step="0.01" class="form-control" id="advance_amount" name="advance_amount" required>
|
| 1041 |
-
</div>
|
| 1042 |
-
</div>
|
| 1043 |
-
<div class="modal-footer">
|
| 1044 |
-
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
| 1045 |
-
<button type="submit" name="advance" class="btn btn-primary">Выдать</button>
|
| 1046 |
-
</div>
|
| 1047 |
-
</form>
|
| 1048 |
-
</div>
|
| 1049 |
-
</div>
|
| 1050 |
-
</div>
|
| 1051 |
-
"""
|
| 1052 |
-
|
| 1053 |
-
CLOUD_CONTENT = """
|
| 1054 |
-
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 1055 |
-
<h1 class="h2"><i class="fas fa-cloud me-2"></i>Облачное хранилище</h1>
|
| 1056 |
-
</div>
|
| 1057 |
-
<div class="card">
|
| 1058 |
-
<div class="card-header">Загрузить файл</div>
|
| 1059 |
-
<div class="card-body">
|
| 1060 |
-
<form method="POST" enctype="multipart/form-data">
|
| 1061 |
-
<div class="mb-3">
|
| 1062 |
-
<input type="file" class="form-control" name="file" required>
|
| 1063 |
-
</div>
|
| 1064 |
-
<button type="submit" class="btn btn-primary">Загрузить</button>
|
| 1065 |
-
</form>
|
| 1066 |
-
</div>
|
| 1067 |
-
</div>
|
| 1068 |
-
<div class="card mt-4">
|
| 1069 |
-
<div class="card-header">Список файлов</div>
|
| 1070 |
-
<div class="card-body">
|
| 1071 |
-
<ul class="list-group">
|
| 1072 |
-
{% for file in files %}
|
| 1073 |
-
<li class="list-group-item">
|
| 1074 |
-
<a href="{{ url_for('uploaded_file', filename=file.filename) }}" target="_blank">{{ file.filename }}</a>
|
| 1075 |
-
<span class="text-muted"> - {{ file.timestamp[:16] }}</span>
|
| 1076 |
-
</li>
|
| 1077 |
-
{% endfor %}
|
| 1078 |
-
</ul>
|
| 1079 |
-
</div>
|
| 1080 |
-
</div>
|
| 1081 |
-
"""
|
| 1082 |
-
|
| 1083 |
-
ORDER_SCRIPTS = """
|
| 1084 |
-
<script>
|
| 1085 |
-
document.addEventListener('DOMContentLoaded', function() {
|
| 1086 |
-
// Дополнительная логика может быть добавлена здесь
|
| 1087 |
-
});
|
| 1088 |
-
</script>
|
| 1089 |
-
"""
|
| 1090 |
-
|
| 1091 |
-
PROCUREMENT_SCRIPTS = """
|
| 1092 |
-
<script>
|
| 1093 |
-
document.addEventListener('DOMContentLoaded', function() {
|
| 1094 |
-
const table = document.getElementById('procurement-table').querySelector('tbody');
|
| 1095 |
-
document.getElementById('add-row').addEventListener('click', function() {
|
| 1096 |
-
const row = table.querySelector('tr').cloneNode(true);
|
| 1097 |
-
row.querySelectorAll('input').forEach(input => input.value = '');
|
| 1098 |
-
table.appendChild(row);
|
| 1099 |
-
});
|
| 1100 |
-
|
| 1101 |
-
table.addEventListener('click', function(e) {
|
| 1102 |
-
if (e.target.classList.contains('remove-row')) {
|
| 1103 |
-
if (table.querySelectorAll('tr').length > 1) {
|
| 1104 |
-
e.target.closest('tr').remove();
|
| 1105 |
-
}
|
| 1106 |
-
}
|
| 1107 |
-
});
|
| 1108 |
-
|
| 1109 |
-
table.addEventListener('change', function(e) {
|
| 1110 |
-
if (e.target.classList.contains('category-select')) {
|
| 1111 |
-
const row = e.target.closest('tr');
|
| 1112 |
-
const newInput = row.querySelector('.new-category-input');
|
| 1113 |
-
newInput.style.display = e.target.value === '__new__' ? 'block' : 'none';
|
| 1114 |
-
}
|
| 1115 |
-
});
|
| 1116 |
-
|
| 1117 |
-
const orderSelect = document.getElementById('order_id');
|
| 1118 |
-
const hiddenOrderId = document.getElementById('hidden_order_id');
|
| 1119 |
-
orderSelect.addEventListener('change', function() {
|
| 1120 |
-
hiddenOrderId.value = this.value;
|
| 1121 |
-
if (this.value) {
|
| 1122 |
-
const order = {% raw %}{{ orders|tojson }}{% endraw %}.find(o => o.id === this.value);
|
| 1123 |
-
if (order) {
|
| 1124 |
-
const row = table.querySelector('tr');
|
| 1125 |
-
row.querySelector('input[name="item_name[]"]').value = order.model;
|
| 1126 |
-
row.querySelector('input[name="item_quantity[]"]').value = order.fabric_quantity;
|
| 1127 |
-
row.querySelector('input[name="item_per_unit[]"]').value = order.fittings_quantity || '';
|
| 1128 |
-
row.querySelector('input[name="item_unit[]"]').value = 'м';
|
| 1129 |
-
row.querySelector('select[name="item_type[]"]').value = 'fabric';
|
| 1130 |
-
}
|
| 1131 |
-
}
|
| 1132 |
-
});
|
| 1133 |
-
});
|
| 1134 |
-
</script>
|
| 1135 |
-
"""
|
| 1136 |
-
|
| 1137 |
-
ADMIN_SCRIPTS = """
|
| 1138 |
-
<script>
|
| 1139 |
-
document.addEventListener('DOMContentLoaded', function() {
|
| 1140 |
-
// Логика для админ-панели может быть добавлена здесь
|
| 1141 |
-
});
|
| 1142 |
-
</script>
|
| 1143 |
-
"""
|
| 1144 |
-
|
| 1145 |
-
REPORTS_SCRIPTS = """
|
| 1146 |
-
<script>
|
| 1147 |
-
document.addEventListener('DOMContentLoaded', function() {
|
| 1148 |
-
document.querySelectorAll('[data-bs-target="#advanceModal"]').forEach(btn => {
|
| 1149 |
-
btn.addEventListener('click', function() {
|
| 1150 |
-
document.getElementById('worker_type').value = this.dataset.type;
|
| 1151 |
-
});
|
| 1152 |
-
});
|
| 1153 |
-
});
|
| 1154 |
-
</script>
|
| 1155 |
-
"""
|
| 1156 |
-
|
| 1157 |
-
if __name__ == '__main__':
|
| 1158 |
-
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 1159 |
-
backup_thread.start()
|
| 1160 |
-
app.run(debug=True, host='0.0.0.0', port=7860, use_reloader=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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