Update app.py
Browse files
app.py
CHANGED
|
@@ -113,7 +113,6 @@ def save_data(data):
|
|
| 113 |
json.dump(data, file, ensure_ascii=False, indent=4, cls=DecimalEncoder)
|
| 114 |
os.replace(temp_file, DATA_FILE)
|
| 115 |
logging.info(f"Основные данные успешно сохранены в локальный файл {DATA_FILE}.")
|
| 116 |
-
# Бэкап на HF будет инициироваться отдельно после вызова save_data
|
| 117 |
except Exception as e:
|
| 118 |
logging.error(f"Критическая ошибка при сохранении основных данных: {e}")
|
| 119 |
if os.path.exists(temp_file):
|
|
@@ -176,7 +175,6 @@ def save_client_data(clients):
|
|
| 176 |
json.dump(clients, file, ensure_ascii=False, indent=4)
|
| 177 |
os.replace(temp_file, CLIENT_DATA_FILE)
|
| 178 |
logging.info(f"Данные клиентов успешно сохранены в локальный файл {CLIENT_DATA_FILE}.")
|
| 179 |
-
# Бэкап на HF будет инициироваться отдельно после вызова save_client_data
|
| 180 |
except Exception as e:
|
| 181 |
logging.error(f"Критическая ошибка при сохранении данных клиентов: {e}")
|
| 182 |
if os.path.exists(temp_file):
|
|
@@ -598,7 +596,6 @@ def cutting():
|
|
| 598 |
flash(f"Недостаточно ткани '{fabric['name']}'. В наличии: {format_currency_py(fabric_available_quantity)} {fabric['unit']}, требуется: {format_currency_py(fabric_used)} {fabric['unit']}.", "danger")
|
| 599 |
return redirect(url_for('cutting'))
|
| 600 |
|
| 601 |
-
# Расчет стоимости (все еще нужен для записи в task)
|
| 602 |
fabric_price_per_unit = to_decimal(fabric.get('price_per_unit', '0.00'))
|
| 603 |
material_cost = fabric_used * fabric_price_per_unit
|
| 604 |
salary_cutter = to_decimal(config.get('salary_cutter_per_unit', '0.00'))
|
|
@@ -607,20 +604,13 @@ def cutting():
|
|
| 607 |
current_time = get_current_time().isoformat()
|
| 608 |
|
| 609 |
new_cutting_task = {
|
| 610 |
-
'id': uuid.uuid4().hex,
|
| 611 |
-
'
|
| 612 |
-
'
|
| 613 |
-
'
|
| 614 |
-
'
|
| 615 |
-
'fabric_used': str(fabric_used),
|
| 616 |
-
'status': 'pending',
|
| 617 |
-
'timestamp_created': current_time,
|
| 618 |
-
'timestamp_completed': None,
|
| 619 |
-
'material_cost': str(material_cost), # Сохраняем стоимость
|
| 620 |
-
'cutting_salary_cost': str(cutting_salary_cost) # Сохраняем ЗП
|
| 621 |
}
|
| 622 |
|
| 623 |
-
# Обновление количества ткани
|
| 624 |
new_fabric_quantity = fabric_available_quantity - fabric_used
|
| 625 |
updated = False
|
| 626 |
materials_list = data.get('materials', [])
|
|
@@ -639,7 +629,6 @@ def cutting():
|
|
| 639 |
data['materials'] = materials_list
|
| 640 |
|
| 641 |
save_data(data)
|
| 642 |
-
# Убираем стоимость из flash сообщения
|
| 643 |
flash(f"Задание на раскрой для {cut_items_quantity} ед. из ткани '{fabric['name']}' успешно создано. Статус: Ожидает пошива.", "success")
|
| 644 |
upload_db_to_hf(DATA_FILE)
|
| 645 |
return redirect(url_for('cutting'))
|
|
@@ -654,14 +643,12 @@ def cutting():
|
|
| 654 |
f_copy = find_item_by_id(f['id'], 'materials')
|
| 655 |
if f_copy:
|
| 656 |
f_copy['quantity_str'] = format_currency_py(f_copy.get('quantity', '0.00'))
|
| 657 |
-
# НЕ ДОБАВЛЯЕМ цену в _str
|
| 658 |
-
# f_copy['price_str'] = format_currency_py(f_copy.get('price_per_unit', '0.00'))
|
| 659 |
fabrics_dec.append(f_copy)
|
| 660 |
|
| 661 |
page_title = "Раскрой ткани"
|
| 662 |
# Используем ОПЕРАЦИОННЫЙ базовый шаблон
|
| 663 |
html = BASE_TEMPLATE_OPERATIONAL.replace('__TITLE__', page_title)
|
| 664 |
-
html = html.replace('__CONTENT__', CUTTING_CONTENT)
|
| 665 |
html = html.replace('__SCRIPTS__', CUTTING_SCRIPTS)
|
| 666 |
return render_template_string(html, fabrics=fabrics_dec)
|
| 667 |
|
|
@@ -712,7 +699,7 @@ def sewing():
|
|
| 712 |
can_sew = True
|
| 713 |
current_time = get_current_time().isoformat()
|
| 714 |
|
| 715 |
-
# 1. Списание фурнитуры
|
| 716 |
if fitting_ids and fitting_quantities and len(fitting_ids) == len(fitting_quantities):
|
| 717 |
for i in range(len(fitting_ids)):
|
| 718 |
fit_id = fitting_ids[i]
|
|
@@ -749,7 +736,7 @@ def sewing():
|
|
| 749 |
|
| 750 |
if not can_sew: return redirect(url_for('sewing'))
|
| 751 |
|
| 752 |
-
# 2. Обработка брака
|
| 753 |
if defect_material_ids and defect_quantities and len(defect_material_ids) == len(defect_quantities):
|
| 754 |
for i in range(len(defect_material_ids)):
|
| 755 |
def_mat_id = defect_material_ids[i]
|
|
@@ -809,10 +796,8 @@ def sewing():
|
|
| 809 |
current_qty_dec = to_decimal(mat.get('quantity', '0'))
|
| 810 |
new_quantity_dec = current_qty_dec - qty_to_deduct
|
| 811 |
is_fabric = mat['type'] == 'fabric'
|
| 812 |
-
if is_fabric:
|
| 813 |
-
|
| 814 |
-
else:
|
| 815 |
-
new_quantity_dec = new_quantity_dec.quantize(Decimal('1'), rounding=ROUND_HALF_UP)
|
| 816 |
if new_quantity_dec < 0: new_quantity_dec = Decimal('0')
|
| 817 |
materials_list[i]['quantity'] = str(new_quantity_dec)
|
| 818 |
materials_list[i]['timestamp_last_updated'] = current_time
|
|
@@ -821,7 +806,7 @@ def sewing():
|
|
| 821 |
flash(f"Критическая ошибка: Не удалось найти материал ID {mat_id} для списания.", "danger")
|
| 822 |
return redirect(url_for('sewing'))
|
| 823 |
|
| 824 |
-
# 4. Расчет ЗП швеи
|
| 825 |
salary_sewer = to_decimal(config.get('salary_sewer_per_unit', '0.00'))
|
| 826 |
sewing_salary_cost = Decimal(sewn_quantity) * salary_sewer
|
| 827 |
|
|
@@ -868,7 +853,6 @@ def sewing():
|
|
| 868 |
data['cutting_tasks'] = cutting_tasks_list
|
| 869 |
|
| 870 |
save_data(data)
|
| 871 |
-
# Убираем стоимость из flash сообщения
|
| 872 |
flash(f"Пошив {sewn_quantity} ед. '{sewn_product_name}' зарегистрирован. Отправлено на ОТК.", "success")
|
| 873 |
if defect_log_list: flash(f"Зарегистрирован брак: {len(defect_log_list)} позиций.", "warning")
|
| 874 |
upload_db_to_hf(DATA_FILE)
|
|
@@ -883,8 +867,8 @@ def sewing():
|
|
| 883 |
for task_id in [t['id'] for t in pending_cutting_tasks]:
|
| 884 |
task_data = find_item_by_id(task_id, 'cutting_tasks')
|
| 885 |
if task_data:
|
| 886 |
-
# НЕ ДОБАВЛЯЕМ строки для стоимости/ЗП
|
| 887 |
task_data['fabric_used_str'] = format_currency_py(task_data.get('fabric_used', '0.00'))
|
|
|
|
| 888 |
tasks_for_template.append(task_data)
|
| 889 |
|
| 890 |
fittings_dec = []
|
|
@@ -892,7 +876,7 @@ def sewing():
|
|
| 892 |
f_copy = find_item_by_id(f['id'], 'materials')
|
| 893 |
if f_copy:
|
| 894 |
f_copy['quantity_str'] = format_integer_py(f_copy.get('quantity', '0'))
|
| 895 |
-
# Н
|
| 896 |
fittings_dec.append(f_copy)
|
| 897 |
|
| 898 |
all_materials_dec = []
|
|
@@ -903,13 +887,13 @@ def sewing():
|
|
| 903 |
mat_data['quantity_str'] = format_currency_py(mat_data.get('quantity', '0.00'))
|
| 904 |
else:
|
| 905 |
mat_data['quantity_str'] = format_integer_py(mat_data.get('quantity', '0'))
|
| 906 |
-
# Н
|
| 907 |
all_materials_dec.append(mat_data)
|
| 908 |
|
| 909 |
page_title = "Пошив изделий"
|
| 910 |
# Используем ОПЕРАЦИОННЫЙ базовый шаблон
|
| 911 |
html = BASE_TEMPLATE_OPERATIONAL.replace('__TITLE__', page_title)
|
| 912 |
-
html = html.replace('__CONTENT__', SEWING_CONTENT)
|
| 913 |
html = html.replace('__SCRIPTS__', SEWING_SCRIPTS)
|
| 914 |
return render_template_string(html,
|
| 915 |
cutting_tasks=tasks_for_template,
|
|
@@ -1015,7 +999,7 @@ def qc_packing():
|
|
| 1015 |
if 'qc_packing_items' not in data: data['qc_packing_items'] = []
|
| 1016 |
data['qc_packing_items'].append(packed_item_entry)
|
| 1017 |
|
| 1018 |
-
# Регистрация брака
|
| 1019 |
if quantity_defective > 0:
|
| 1020 |
cutting_task = find_item_by_id(sewing_task.get('cutting_task_id'), 'cutting_tasks')
|
| 1021 |
if not cutting_task: cutting_task = {'material_cost': Decimal('0.00'), 'cutting_salary_cost': Decimal('0.00'), 'cut_items_quantity': 1}
|
|
@@ -1066,7 +1050,7 @@ def qc_packing():
|
|
| 1066 |
|
| 1067 |
data['sewing_tasks'] = sewing_tasks_list
|
| 1068 |
save_data(data)
|
| 1069 |
-
|
| 1070 |
flash_message = f"ОТК/Упаковка для '{sewing_task['product_name']}': упаковано {quantity_packed}, брак {quantity_defective}. "
|
| 1071 |
if packed_item_entry:
|
| 1072 |
flash_message += f"Статус упакованных: Готово к отправке."
|
|
@@ -1100,45 +1084,37 @@ def qc_packing():
|
|
| 1100 |
@app.route('/clients', methods=['GET', 'POST'])
|
| 1101 |
def clients_panel():
|
| 1102 |
if request.method == 'POST':
|
| 1103 |
-
# Добавление нового клиента
|
| 1104 |
name = request.form.get('client_name', '').strip()
|
| 1105 |
phone = request.form.get('client_phone', '').strip()
|
| 1106 |
address = request.form.get('client_address', '').strip()
|
| 1107 |
-
|
| 1108 |
if not name or not phone:
|
| 1109 |
flash("Имя/Название организации и номер телефона обязательны.", "danger")
|
| 1110 |
return redirect(url_for('clients_panel'))
|
| 1111 |
-
|
| 1112 |
clients = load_client_data()
|
| 1113 |
-
|
| 1114 |
normalized_phone = ''.join(filter(str.isdigit, phone))
|
| 1115 |
if any(''.join(filter(str.isdigit, c.get('phone', ''))) == normalized_phone for c in clients):
|
| 1116 |
flash(f"Клиент с похожим номером телефона ({phone}) уже существует.", "warning")
|
| 1117 |
return redirect(url_for('clients_panel'))
|
| 1118 |
-
|
| 1119 |
-
new_client = {
|
| 1120 |
-
'id': uuid.uuid4().hex, 'name': name, 'phone': phone,
|
| 1121 |
-
'address': address if address else None, 'history': []
|
| 1122 |
-
}
|
| 1123 |
clients.append(new_client)
|
| 1124 |
save_client_data(clients)
|
| 1125 |
flash(f"Клиент '{name}' успешно добавлен.", "success")
|
| 1126 |
upload_db_to_hf(CLIENT_DATA_FILE)
|
| 1127 |
return redirect(url_for('clients_panel'))
|
| 1128 |
|
| 1129 |
-
# GET запрос
|
| 1130 |
clients_data = load_client_data()
|
| 1131 |
clients_data.sort(key=lambda x: x.get('name', '').lower())
|
| 1132 |
-
|
| 1133 |
for client in clients_data:
|
| 1134 |
if 'history' in client:
|
|
|
|
| 1135 |
for record in client['history']:
|
| 1136 |
record['timestamp_dt'] = parse_iso_datetime(record.get('timestamp'))
|
| 1137 |
|
| 1138 |
page_title = "База клиентов"
|
| 1139 |
# Используем ОБЫЧНЫЙ базовый шаблон
|
| 1140 |
html = BASE_TEMPLATE.replace('__TITLE__', page_title)
|
| 1141 |
-
html = html.replace('__CONTENT__', CLIENTS_CONTENT)
|
| 1142 |
html = html.replace('__SCRIPTS__', CLIENTS_SCRIPTS)
|
| 1143 |
return render_template_string(html, clients=clients_data)
|
| 1144 |
|
|
@@ -1174,7 +1150,7 @@ def admin_panel():
|
|
| 1174 |
page_title = "Админ-панель"
|
| 1175 |
# Используем ОБЫЧНЫЙ базовый шаблон
|
| 1176 |
html = BASE_TEMPLATE.replace('__TITLE__', page_title)
|
| 1177 |
-
html = html.replace('__CONTENT__', ADMIN_CONTENT)
|
| 1178 |
html = html.replace('__SCRIPTS__', ADMIN_SCRIPTS)
|
| 1179 |
|
| 1180 |
return render_template_string(
|
|
@@ -1213,12 +1189,12 @@ def dispatch_item():
|
|
| 1213 |
return redirect(url_for('admin_panel') + '#dispatch-content')
|
| 1214 |
|
| 1215 |
data = load_data()
|
| 1216 |
-
clients = load_client_data()
|
| 1217 |
item_found = False
|
| 1218 |
client_found = False
|
| 1219 |
client_name = None
|
| 1220 |
|
| 1221 |
-
|
| 1222 |
item_index = -1
|
| 1223 |
qc_packing_items_list = data.get('qc_packing_items', [])
|
| 1224 |
for i, item in enumerate(qc_packing_items_list):
|
|
@@ -1248,27 +1224,28 @@ def dispatch_item():
|
|
| 1248 |
flash("Ошибка: Не выбран клиент для отправки.", "danger")
|
| 1249 |
return redirect(url_for('admin_panel') + '#dispatch-content')
|
| 1250 |
|
| 1251 |
-
|
|
|
|
| 1252 |
for i, client in enumerate(clients):
|
| 1253 |
if client.get('id') == client_id:
|
| 1254 |
client_found = True
|
| 1255 |
client_name = client.get('name')
|
| 1256 |
-
|
| 1257 |
-
client_index_to_save = i #
|
| 1258 |
break
|
| 1259 |
|
| 1260 |
if not client_found:
|
| 1261 |
flash(f"Ошибка: Клиент с ID {client_id} не найден.", "danger")
|
| 1262 |
return redirect(url_for('admin_panel') + '#dispatch-content')
|
| 1263 |
|
| 1264 |
-
# Обновляем статус товара
|
| 1265 |
item_to_dispatch_ref['status'] = 'shipped_client'
|
| 1266 |
shipment_details['client_id'] = client_id
|
| 1267 |
shipment_details['client_name'] = client_name
|
| 1268 |
item_to_dispatch_ref['shipment_details'] = shipment_details
|
| 1269 |
-
logging.info(f"Товар {item_id} помечен как shipped_client.")
|
| 1270 |
|
| 1271 |
-
# Добавляем запись в историю клиента
|
| 1272 |
history_entry = {
|
| 1273 |
'shipment_id': uuid.uuid4().hex,
|
| 1274 |
'timestamp': current_time_iso,
|
|
@@ -1276,12 +1253,12 @@ def dispatch_item():
|
|
| 1276 |
'packed_item_id': item_id
|
| 1277 |
}
|
| 1278 |
# Убеждаемся, что 'history' существует и является списком
|
| 1279 |
-
if 'history' not in
|
| 1280 |
-
|
| 1281 |
logging.warning(f"Инициализирован список истории для клиента {client_id}")
|
| 1282 |
|
| 1283 |
-
|
| 1284 |
-
logging.info(f"Запись добавлена в историю клиента {client_id}. Новая длина истории: {len(
|
| 1285 |
client_data_changed = True
|
| 1286 |
|
| 1287 |
# Обработка отправки на Дордой
|
|
@@ -1297,16 +1274,16 @@ def dispatch_item():
|
|
| 1297 |
# Сохраняем основной файл данных (qc_packing_items_list был изменен по ссылке)
|
| 1298 |
data['qc_packing_items'] = qc_packing_items_list
|
| 1299 |
save_data(data)
|
| 1300 |
-
upload_db_to_hf(DATA_FILE)
|
| 1301 |
logging.info(f"Основные данные сохранены после отправки товара {item_id}.")
|
| 1302 |
|
| 1303 |
# Сохраняем файл клиентов, если были изменения
|
| 1304 |
if client_data_changed:
|
| 1305 |
-
save_client_data(clients)
|
| 1306 |
-
upload_db_to_hf(CLIENT_DATA_FILE)
|
| 1307 |
logging.info(f"Данные клиента {client_id} сохранены после добавления истории.")
|
| 1308 |
else:
|
| 1309 |
-
logging.info(f"Данные клиентов не изменялись при отправке товара {item_id}
|
| 1310 |
|
| 1311 |
# Сообщение об успехе
|
| 1312 |
destination_text = f"клиенту '{client_name}'" if destination_type == 'client' else "на Торговую точку Дордой"
|
|
@@ -1431,18 +1408,14 @@ def backup_hf():
|
|
| 1431 |
if os.path.exists(DATA_FILE):
|
| 1432 |
upload_db_to_hf(DATA_FILE)
|
| 1433 |
files_uploaded += 1
|
| 1434 |
-
else:
|
| 1435 |
-
flash(f"Локальный файл {DATA_FILE} не найден.", "warning")
|
| 1436 |
with client_data_lock:
|
| 1437 |
if os.path.exists(CLIENT_DATA_FILE):
|
| 1438 |
upload_db_to_hf(CLIENT_DATA_FILE)
|
| 1439 |
files_uploaded += 1
|
| 1440 |
-
else:
|
| 1441 |
-
|
| 1442 |
-
|
| 1443 |
-
flash(f"Резервное копирование {files_uploaded} файлов успешно инициировано на Hugging Face.", "success")
|
| 1444 |
-
else:
|
| 1445 |
-
flash("Не найдено файлов для резервного копирования.", "warning")
|
| 1446 |
except Exception as e:
|
| 1447 |
logging.error(f"Ошибка при ручном резервном копировании: {e}")
|
| 1448 |
flash(f"Ошибка при создании резервной копии: {e}", "danger")
|
|
@@ -1450,9 +1423,7 @@ def backup_hf():
|
|
| 1450 |
|
| 1451 |
@app.route('/download', methods=['GET'])
|
| 1452 |
def download_hf():
|
| 1453 |
-
downloaded_files = []
|
| 1454 |
-
errors = []
|
| 1455 |
-
# Скачиваем основной файл
|
| 1456 |
try:
|
| 1457 |
logging.info(f"Запуск ручного скачивания {DATA_FILE} с Hugging Face...")
|
| 1458 |
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)
|
|
@@ -1461,10 +1432,7 @@ def download_hf():
|
|
| 1461 |
except HfHubHTTPError as e:
|
| 1462 |
if e.response.status_code == 404: errors.append(f"Файл {DATA_FILE} не найден в репозитории {REPO_ID}.")
|
| 1463 |
else: errors.append(f"Ошибка HTTP при скачивании {DATA_FILE}: {e}"); logging.error(f"Ошибка HTTP при скачивании {DATA_FILE}: {e}")
|
| 1464 |
-
except Exception as e:
|
| 1465 |
-
logging.error(f"Ошибка при ручном скачивании {DATA_FILE}: {e}")
|
| 1466 |
-
errors.append(f"Ошибка при скачивании {DATA_FILE}: {e}")
|
| 1467 |
-
# Скачиваем файл клиентов
|
| 1468 |
try:
|
| 1469 |
logging.info(f"Запуск ручного скачивания {CLIENT_DATA_FILE} с Hugging Face...")
|
| 1470 |
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)
|
|
@@ -1474,10 +1442,7 @@ def download_hf():
|
|
| 1474 |
except HfHubHTTPError as e:
|
| 1475 |
if e.response.status_code == 404: errors.append(f"Файл {CLIENT_DATA_FILE} не найден в репозитории {REPO_ID}.")
|
| 1476 |
else: errors.append(f"Ошибка HTTP при скачивании {CLIENT_DATA_FILE}: {e}"); logging.error(f"Ошибка HTTP при скачивании {CLIENT_DATA_FILE}: {e}")
|
| 1477 |
-
except Exception as e:
|
| 1478 |
-
logging.error(f"Ошибка при ручном скачивании {CLIENT_DATA_FILE}: {e}")
|
| 1479 |
-
errors.append(f"Ошибка при скачивании {CLIENT_DATA_FILE}: {e}")
|
| 1480 |
-
# Вывод сообщений
|
| 1481 |
if downloaded_files: flash(f"Файлы ({', '.join(downloaded_files)}) успешно скачаны с Hugging Face. Локальные файлы обновлены.", "success")
|
| 1482 |
if errors: flash("Во время скачивания произошли ошибки: " + "; ".join(errors), "danger")
|
| 1483 |
if not downloaded_files and not errors: flash("Не удалось инициировать скачивание.", "warning")
|
|
@@ -1532,8 +1497,7 @@ def reports():
|
|
| 1532 |
if packed_time and start_date <= packed_time <= end_date:
|
| 1533 |
shipment_time_dt = None
|
| 1534 |
details = item_data.get('shipment_details')
|
| 1535 |
-
if details and details.get('timestamp'):
|
| 1536 |
-
shipment_time_dt = parse_iso_datetime(details.get('timestamp'))
|
| 1537 |
item_data['shipment_time_dt'] = shipment_time_dt
|
| 1538 |
filtered_packed_items.append(item_data)
|
| 1539 |
|
|
@@ -1616,15 +1580,18 @@ BASE_TEMPLATE = """
|
|
| 1616 |
.btn-info { background-color: #0dcaf0; border-color: #0dcaf0; color: #000; }
|
| 1617 |
.table-hover tbody tr:hover { background-color: rgba(0, 0, 0, 0.05); }
|
| 1618 |
.container-main { max-width: 1600px; margin: 0 auto; padding-left: 15px; padding-right: 15px; }
|
| 1619 |
-
|
| 1620 |
-
.status-
|
| 1621 |
-
.status-
|
| 1622 |
-
.status-
|
| 1623 |
-
.status-
|
| 1624 |
-
.status-
|
| 1625 |
-
.
|
| 1626 |
-
|
| 1627 |
-
.text-
|
|
|
|
|
|
|
|
|
|
| 1628 |
.flash-messages .alert { margin-bottom: 1rem; border-radius: 0.5rem; }
|
| 1629 |
.dynamic-row, .dynamic-fitting-row, .dynamic-defect-row { border: 1px solid #eee; padding: 15px; margin-bottom: 15px; border-radius: 5px; background-color: #fdfdfd; position: relative; }
|
| 1630 |
.remove-row-btn, .remove-fitting-row-btn, .remove-defect-row-btn { position: absolute; top: 10px; right: 10px; z-index: 10; }
|
|
@@ -1724,60 +1691,21 @@ BASE_TEMPLATE = """
|
|
| 1724 |
|
| 1725 |
<script>
|
| 1726 |
// Глобальная функция для форматирования чисел как валюты (JS)
|
| 1727 |
-
function formatCurrencyJS(value) {
|
| 1728 |
-
try {
|
| 1729 |
-
const number = parseFloat(String(value).replace(/\s/g, '').replace(',', '.')); // Убираем пробелы перед парсингом
|
| 1730 |
-
if (isNaN(number)) { return '0,00'; }
|
| 1731 |
-
return number.toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
| 1732 |
-
} catch (e) { return '0,00'; }
|
| 1733 |
-
}
|
| 1734 |
-
|
| 1735 |
// Глобальная функция для форматирования целых чисел (JS)
|
| 1736 |
-
function formatIntegerJS(value) {
|
| 1737 |
-
try {
|
| 1738 |
-
const number = parseInt(String(value).replace(/\s/g, '').replace(',', '.').split('.')[0]); // Убираем пробелы
|
| 1739 |
-
if (isNaN(number)) { return '0'; }
|
| 1740 |
-
return number.toLocaleString('ru-RU');
|
| 1741 |
-
} catch (e) { return '0'; }
|
| 1742 |
-
}
|
| 1743 |
-
|
| 1744 |
// Глобальная функция для получения текущего времени из футера
|
| 1745 |
-
function getCurrentTimeFromFooter() {
|
| 1746 |
-
const footer = document.querySelector('.footer p');
|
| 1747 |
-
const timeMatch = footer ? footer.textContent.match(/\((.*?)\)/) : null;
|
| 1748 |
-
return timeMatch ? timeMatch[1] : new Date().toLocaleString();
|
| 1749 |
-
}
|
| 1750 |
-
|
| 1751 |
// Вспомогательные JS функции для статусов (могут быть полезны для динамики)
|
| 1752 |
-
function getStatusTextJS(statusKey) {
|
| 1753 |
-
|
| 1754 |
-
'pending': 'Ожидает пошива',
|
| 1755 |
-
'completed': 'Завершено',
|
| 1756 |
-
'pending_qc': 'Ожидает ОТК',
|
| 1757 |
-
'packed_ready_to_ship': 'Готово к отправке',
|
| 1758 |
-
'shipped_client': 'Отправлено клиенту',
|
| 1759 |
-
'shipped_dor_doi': 'Отправлено на Дордой'
|
| 1760 |
-
};
|
| 1761 |
-
return statusMap[statusKey] || statusKey;
|
| 1762 |
-
}
|
| 1763 |
-
function getStatusClassJS(statusKey) {
|
| 1764 |
-
const classMap = {
|
| 1765 |
-
'pending': 'status-pending text-info',
|
| 1766 |
-
'completed': 'status-completed text-success',
|
| 1767 |
-
'pending_qc': 'status-pending_qc text-warning',
|
| 1768 |
-
'packed_ready_to_ship': 'status-packed_ready_to_ship text-ready',
|
| 1769 |
-
'shipped_client': 'status-shipped_client text-shipped-client',
|
| 1770 |
-
'shipped_dor_doi': 'status-shipped_dor_doi text-shipped-dordoi'
|
| 1771 |
-
};
|
| 1772 |
-
return classMap[statusKey] || '';
|
| 1773 |
-
}
|
| 1774 |
</script>
|
| 1775 |
__SCRIPTS__
|
| 1776 |
</body>
|
| 1777 |
</html>
|
| 1778 |
"""
|
| 1779 |
|
| 1780 |
-
# ОПЕРАЦИОННЫЙ Базовый шаблон (БЕЗ навигации)
|
| 1781 |
BASE_TEMPLATE_OPERATIONAL = """
|
| 1782 |
<!DOCTYPE html>
|
| 1783 |
<html lang="ru">
|
|
@@ -1839,12 +1767,14 @@ BASE_TEMPLATE_OPERATIONAL = """
|
|
| 1839 |
{# --- НАВИГАЦИЯ УБРАНА --- #}
|
| 1840 |
|
| 1841 |
<div class="container-main mt-4">
|
| 1842 |
-
{#
|
| 1843 |
-
<div class="mb-3">
|
| 1844 |
<a href="{{ url_for('admin_panel') }}" class="btn btn-sm btn-outline-secondary">
|
| 1845 |
<i class="fas fa-arrow-left me-1"></i> Назад в Админ-панель
|
| 1846 |
</a>
|
| 1847 |
-
</div>
|
|
|
|
|
|
|
| 1848 |
|
| 1849 |
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 1850 |
{% if messages %}
|
|
@@ -1955,8 +1885,6 @@ PROCUREMENT_SCRIPTS = """
|
|
| 1955 |
const firstRow = container.querySelector('.dynamic-row');
|
| 1956 |
if (!firstRow) { console.warn("No template row found."); return; }
|
| 1957 |
const newRow = firstRow.cloneNode(true);
|
| 1958 |
-
|
| 1959 |
-
// Очищаем значения
|
| 1960 |
newRow.querySelectorAll('input[type="text"], input[type="number"]').forEach(input => input.value = '');
|
| 1961 |
newRow.querySelectorAll('select').forEach(select => {
|
| 1962 |
if (select.name === 'item_unit[]') select.value = 'м';
|
|
@@ -1966,51 +1894,28 @@ PROCUREMENT_SCRIPTS = """
|
|
| 1966 |
});
|
| 1967 |
const newCategoryInput = newRow.querySelector('.new-category-input');
|
| 1968 |
if (newCategoryInput) { newCategoryInput.style.display = 'none'; newCategoryInput.required = false; newCategoryInput.value = ''; }
|
| 1969 |
-
|
| 1970 |
const removeBtn = newRow.querySelector('.remove-row-btn');
|
| 1971 |
-
if (
|
| 1972 |
-
|
| 1973 |
container.appendChild(newRow);
|
| 1974 |
attachCategoryChangeEvent(newRow);
|
| 1975 |
}
|
| 1976 |
-
|
| 1977 |
-
function removeRow(button) {
|
| 1978 |
-
const row = button.closest('.dynamic-row');
|
| 1979 |
-
if (row) row.remove();
|
| 1980 |
-
}
|
| 1981 |
-
|
| 1982 |
function handleCategoryChange(selectElement) {
|
| 1983 |
-
const row = selectElement.closest('.dynamic-row');
|
| 1984 |
-
if (!
|
| 1985 |
-
const newCategoryInput = row.querySelector('.new-category-input');
|
| 1986 |
-
if (!newCategoryInput) return;
|
| 1987 |
const isNew = selectElement.value === '__new__';
|
| 1988 |
newCategoryInput.style.display = isNew ? 'block' : 'none';
|
| 1989 |
newCategoryInput.required = isNew;
|
| 1990 |
if (!isNew) newCategoryInput.value = '';
|
| 1991 |
}
|
| 1992 |
-
|
| 1993 |
function attachCategoryChangeEvent(rowElement) {
|
| 1994 |
const categorySelect = rowElement.querySelector('.category-select');
|
| 1995 |
-
if(categorySelect) {
|
| 1996 |
-
categorySelect.removeEventListener('change', categoryChangeHandler); // Remove previous listener to avoid duplicates
|
| 1997 |
-
categorySelect.addEventListener('change', categoryChangeHandler);
|
| 1998 |
-
}
|
| 1999 |
}
|
| 2000 |
-
// Define the handler function once
|
| 2001 |
function categoryChangeHandler() { handleCategoryChange(this); }
|
| 2002 |
-
|
| 2003 |
document.addEventListener('DOMContentLoaded', () => {
|
| 2004 |
-
document.querySelectorAll('.dynamic-row').forEach(row => {
|
| 2005 |
-
|
| 2006 |
-
// Initialize state based on current selection
|
| 2007 |
-
const categorySelect = row.querySelector('.category-select');
|
| 2008 |
-
if (categorySelect) handleCategoryChange(categorySelect);
|
| 2009 |
-
});
|
| 2010 |
-
// Add first row if none exist
|
| 2011 |
-
if (!document.querySelector('#material-rows .dynamic-row')) {
|
| 2012 |
-
addRow();
|
| 2013 |
-
}
|
| 2014 |
});
|
| 2015 |
</script>
|
| 2016 |
"""
|
|
@@ -2022,15 +1927,12 @@ CUTTING_CONTENT = """
|
|
| 2022 |
<div class="card-body">
|
| 2023 |
<form method="POST" id="cutting-form">
|
| 2024 |
<div class="row mb-3 align-items-end">
|
| 2025 |
-
<div class="col-md-5">
|
| 2026 |
<label for="fabric_id" class="form-label">Выберите ткань:</label>
|
| 2027 |
<select id="fabric_id" name="fabric_id" class="form-select" required onchange="updateAvailableQuantity()">
|
| 2028 |
<option value="">-- Выберите ткань --</option>
|
| 2029 |
-
{% for fabric in fabrics %}
|
| 2030 |
-
<option value="{{ fabric.id }}"
|
| 2031 |
-
data-unit="{{ fabric.unit }}"
|
| 2032 |
-
data-quantity="{{ fabric.quantity_str }}"> {# Используем подготовленную строку #}
|
| 2033 |
-
{# Убираем цену из текста опции #}
|
| 2034 |
{{ fabric.name }} ({{ fabric.category | default('Без категории') }}) - {{ fabric.quantity_str }} {{ fabric.unit }}
|
| 2035 |
</option>
|
| 2036 |
{% endfor %}
|
|
@@ -2049,7 +1951,6 @@ CUTTING_CONTENT = """
|
|
| 2049 |
<button type="submit" class="btn btn-primary w-100"><i class="fas fa-paper-plane me-1"></i> Ok</button>
|
| 2050 |
</div>
|
| 2051 |
</div>
|
| 2052 |
-
{# Удалена секция фурнитуры #}
|
| 2053 |
</form>
|
| 2054 |
</div>
|
| 2055 |
</div>
|
|
@@ -2064,23 +1965,16 @@ CUTTING_SCRIPTS = """
|
|
| 2064 |
const availableDiv = document.getElementById('available-quantity');
|
| 2065 |
const unitSpan = document.getElementById('fabric-unit');
|
| 2066 |
if (selectedOption && selectedOption.value) {
|
| 2067 |
-
// Берем УЖЕ ФОРМАТИРОВАННЫЕ строки из data-атрибутов
|
| 2068 |
const quantity = selectedOption.getAttribute('data-quantity') || '0,00';
|
| 2069 |
const unit = selectedOption.getAttribute('data-unit') || '?';
|
| 2070 |
-
|
| 2071 |
-
// const price = selectedOption.getAttribute('data-price') || '0,00';
|
| 2072 |
-
if(availableDiv) availableDiv.textContent = `В наличии: ${quantity} ${unit}`; // Убрали цену
|
| 2073 |
if(unitSpan) unitSpan.textContent = unit;
|
| 2074 |
} else {
|
| 2075 |
if(availableDiv) availableDiv.textContent = '';
|
| 2076 |
if(unitSpan) unitSpan.textContent = 'м';
|
| 2077 |
}
|
| 2078 |
}
|
| 2079 |
-
|
| 2080 |
-
document.addEventListener('DOMContentLoaded', () => {
|
| 2081 |
-
updateAvailableQuantity();
|
| 2082 |
-
// Убрана логика добавления/удаления/обработки строк фурнитуры
|
| 2083 |
-
});
|
| 2084 |
</script>
|
| 2085 |
"""
|
| 2086 |
|
|
@@ -2097,12 +1991,8 @@ SEWING_CONTENT = """
|
|
| 2097 |
<label for="cutting_task_id" class="form-label">Выберите задание на раскрой:</label>
|
| 2098 |
<select id="cutting_task_id" name="cutting_task_id" class="form-select" required onchange="showTaskDetails()">
|
| 2099 |
<option value="">-- Выберите задание --</option>
|
| 2100 |
-
{% for task in cutting_tasks %}
|
| 2101 |
-
<option value="{{ task.id }}"
|
| 2102 |
-
data-fabric-name="{{ task.fabric_name }}"
|
| 2103 |
-
data-cut-quantity="{{ task.cut_items_quantity }}"
|
| 2104 |
-
data-fabric-used="{{ task.fabric_used_str }} {{ task.fabric_unit }}">
|
| 2105 |
-
{# Удалены data-атрибуты для стоимости/зп #}
|
| 2106 |
#{{ loop.index }} - {{ task.fabric_name }} - {{ task.cut_items_quantity }} ед. (Раскрой от {{ task.timestamp_created[:10] }})
|
| 2107 |
</option>
|
| 2108 |
{% endfor %}
|
|
@@ -2122,9 +2012,8 @@ SEWING_CONTENT = """
|
|
| 2122 |
<p class="mb-1"><strong>Ткань:</strong> <span id="detail-fabric-name"></span></p>
|
| 2123 |
<p class="mb-1"><strong>Раскроено:</strong> <span id="detail-cut-quantity"></span> ед.</p>
|
| 2124 |
<p class="mb-1"><strong>Расход ткани (на все):</strong> <span id="detail-fabric-used"></span></p>
|
| 2125 |
-
{# Удалены строки стоимости/зп #}
|
| 2126 |
</div>
|
| 2127 |
-
<div class="col-md-6">
|
| 2128 |
</div>
|
| 2129 |
</div>
|
| 2130 |
|
|
@@ -2146,8 +2035,7 @@ SEWING_CONTENT = """
|
|
| 2146 |
<div class="col-md-5">
|
| 2147 |
<select name="fitting_ids[]" class="form-select form-select-sm fitting-select">
|
| 2148 |
<option value="">-- Выберите фурнитуру --</option>
|
| 2149 |
-
{% for fitting in fittings %}
|
| 2150 |
-
{# Удален data-price из option #}
|
| 2151 |
<option value="{{ fitting.id }}" data-quantity="{{ fitting.quantity_str }}" data-unit="{{ fitting.unit }}">
|
| 2152 |
{{ fitting.name }} ({{ fitting.category | default('Без категории') }}) - {{ fitting.quantity_str }} {{ fitting.unit }}
|
| 2153 |
</option>
|
|
@@ -2155,9 +2043,9 @@ SEWING_CONTENT = """
|
|
| 2155 |
</select>
|
| 2156 |
</div>
|
| 2157 |
<div class="col-md-3">
|
| 2158 |
-
<input type="number" name="fitting_quantities[]" class="form-control form-control-sm" placeholder="Кол-во (на все сшитые)" min="1" step="1">
|
| 2159 |
</div>
|
| 2160 |
-
<div class="col-md-3 fitting-availability form-text text-info"></div>
|
| 2161 |
<button type="button" class="btn btn-sm btn-danger remove-fitting-row-btn" onclick="removeFittingRow(this)" title="Удалить фурнитуру"><i class="fas fa-times"></i></button>
|
| 2162 |
</div>
|
| 2163 |
<!-- Конец шаблона -->
|
|
@@ -2173,10 +2061,9 @@ SEWING_CONTENT = """
|
|
| 2173 |
<div class="col-md-5">
|
| 2174 |
<select name="defect_material_id[]" class="form-select form-select-sm defect-material-select">
|
| 2175 |
<option value="">-- Выберите материал/фурнитуру для брака --</option>
|
| 2176 |
-
{% for material in all_materials %}
|
| 2177 |
{% set unit_display = material.unit %}
|
| 2178 |
{% set type_display = 'Фурн.' if material.type == 'fittings' else 'Ткань' %}
|
| 2179 |
-
{# Удален data-price из option #}
|
| 2180 |
<option value="{{ material.id }}" data-quantity="{{ material.quantity_str }}" data-unit="{{ unit_display }}" data-type="{{ material.type }}">
|
| 2181 |
{{ material.name }} ({{ material.category | default('Без категории') }}) - {{ material.quantity_str }} {{ unit_display }} [{{ type_display }}]
|
| 2182 |
</option>
|
|
@@ -2184,9 +2071,9 @@ SEWING_CONTENT = """
|
|
| 2184 |
</select>
|
| 2185 |
</div>
|
| 2186 |
<div class="col-md-3">
|
| 2187 |
-
<input type="text" name="defect_quantity[]" class="form-control form-control-sm defect-quantity-input" placeholder="Количество">
|
| 2188 |
</div>
|
| 2189 |
-
<div class="col-md-3 defect-availability form-text text-info"></div>
|
| 2190 |
<button type="button" class="btn btn-sm btn-danger remove-defect-row-btn" onclick="removeDefectRow(this)" title="Удалить брак"><i class="fas fa-times"></i></button>
|
| 2191 |
</div>
|
| 2192 |
<!-- Конец шаблона -->
|
|
@@ -2217,37 +2104,25 @@ SEWING_SCRIPTS = """
|
|
| 2217 |
const productNameInput = document.getElementById('sewn_product_name');
|
| 2218 |
|
| 2219 |
if (selectedOption && selectedOption.value) {
|
| 2220 |
-
// Берем строки из data-атрибутов
|
| 2221 |
const fabricName = selectedOption.getAttribute('data-fabric-name') || 'N/A';
|
| 2222 |
const cutQuantity = selectedOption.getAttribute('data-cut-quantity') || '0';
|
| 2223 |
const fabricUsed = selectedOption.getAttribute('data-fabric-used') || 'N/A';
|
| 2224 |
-
// НЕ БЕРЕМ стоимость/зп
|
| 2225 |
|
| 2226 |
-
// Обновляем поля деталей
|
| 2227 |
const fields = {
|
| 2228 |
'detail-fabric-name': fabricName,
|
| 2229 |
'detail-cut-quantity': cutQuantity,
|
| 2230 |
'detail-fabric-used': fabricUsed
|
| 2231 |
-
// НЕ ОБНОВЛЯЕМ стоимость/зп
|
| 2232 |
};
|
| 2233 |
for(const id in fields) {
|
| 2234 |
const element = document.getElementById(id);
|
| 2235 |
if(element) element.textContent = fields[id];
|
| 2236 |
}
|
| 2237 |
-
|
| 2238 |
-
|
| 2239 |
-
if(costElem) costElem.textContent = '';
|
| 2240 |
-
const salaryElem = document.getElementById('detail-cutting-salary');
|
| 2241 |
-
if(salaryElem) salaryElem.textContent = '';
|
| 2242 |
-
|
| 2243 |
|
| 2244 |
if(maxSewnSpan) maxSewnSpan.textContent = cutQuantity;
|
| 2245 |
-
if(sewnInput)
|
| 2246 |
-
|
| 2247 |
-
}
|
| 2248 |
-
if (productNameInput && !productNameInput.value) {
|
| 2249 |
-
productNameInput.value = fabricName;
|
| 2250 |
-
}
|
| 2251 |
if(detailsDiv) detailsDiv.style.display = 'block';
|
| 2252 |
} else {
|
| 2253 |
if(detailsDiv) detailsDiv.style.display = 'none';
|
|
@@ -2257,114 +2132,73 @@ SEWING_SCRIPTS = """
|
|
| 2257 |
}
|
| 2258 |
}
|
| 2259 |
|
| 2260 |
-
// --- Функции для динамических строк ФУРНИТУРЫ ---
|
| 2261 |
function addFittingRow() {
|
| 2262 |
const container = document.getElementById('fittings-rows');
|
| 2263 |
-
const firstRow = container.querySelector('.dynamic-fitting-row');
|
| 2264 |
-
if (!firstRow) return;
|
| 2265 |
const newRow = firstRow.cloneNode(true);
|
| 2266 |
newRow.querySelectorAll('select, input').forEach(el => el.value = '');
|
| 2267 |
-
const availabilityDiv = newRow.querySelector('.fitting-availability');
|
| 2268 |
-
if(
|
| 2269 |
-
const removeBtn = newRow.querySelector('.remove-fitting-row-btn');
|
| 2270 |
-
if(removeBtn) removeBtn.style.display = 'inline-block';
|
| 2271 |
container.appendChild(newRow);
|
| 2272 |
attachFittingChangeEvent(newRow);
|
| 2273 |
}
|
| 2274 |
-
function removeFittingRow(button) {
|
| 2275 |
-
const row = button.closest('.dynamic-fitting-row');
|
| 2276 |
-
if (row) row.remove();
|
| 2277 |
-
}
|
| 2278 |
function handleFittingChange(selectElement) {
|
| 2279 |
-
const row = selectElement.closest('.dynamic-fitting-row');
|
| 2280 |
-
if (!
|
| 2281 |
-
const availabilityDiv = row.querySelector('.fitting-availability');
|
| 2282 |
-
if (!availabilityDiv) return;
|
| 2283 |
const selectedOption = selectElement.options[selectElement.selectedIndex];
|
| 2284 |
if (selectedOption && selectedOption.value) {
|
| 2285 |
const quantity = selectedOption.getAttribute('data-quantity') || '0';
|
| 2286 |
const unit = selectedOption.getAttribute('data-unit') || 'шт';
|
| 2287 |
-
|
| 2288 |
-
// const price = selectedOption.getAttribute('data-price') || '0,00';
|
| 2289 |
-
availabilityDiv.textContent = `Доступно: ${quantity} ${unit}`; // Убрали цену
|
| 2290 |
} else { availabilityDiv.textContent = ''; }
|
| 2291 |
}
|
| 2292 |
-
|
| 2293 |
-
|
| 2294 |
-
|
| 2295 |
-
|
| 2296 |
-
|
| 2297 |
-
}
|
| 2298 |
-
}
|
| 2299 |
-
function fittingChangeHandler() { handleFittingChange(this); }
|
| 2300 |
|
| 2301 |
-
// --- Функции для динамиче��ких строк БРАКА ---
|
| 2302 |
function addDefectRow() {
|
| 2303 |
const container = document.getElementById('defect-rows');
|
| 2304 |
-
const firstRow = container.querySelector('.dynamic-defect-row');
|
| 2305 |
-
if (!firstRow) return;
|
| 2306 |
const newRow = firstRow.cloneNode(true);
|
| 2307 |
newRow.querySelectorAll('select, input').forEach(el => el.value = '');
|
| 2308 |
-
const availabilityDiv = newRow.querySelector('.defect-availability');
|
| 2309 |
-
if(
|
| 2310 |
-
const
|
| 2311 |
-
if(qtyInput){ qtyInput.inputMode = 'text'; qtyInput.placeholder = 'Количество'; qtyInput.step = 'any'; }
|
| 2312 |
-
const removeBtn = newRow.querySelector('.remove-defect-row-btn');
|
| 2313 |
-
if(removeBtn) removeBtn.style.display = 'inline-block';
|
| 2314 |
container.appendChild(newRow);
|
| 2315 |
attachDefectChangeEvent(newRow);
|
| 2316 |
}
|
| 2317 |
-
function removeDefectRow(button) {
|
| 2318 |
-
const row = button.closest('.dynamic-defect-row');
|
| 2319 |
-
if(row) row.remove();
|
| 2320 |
-
}
|
| 2321 |
function handleDefectChange(selectElement) {
|
| 2322 |
-
const row = selectElement.closest('.dynamic-defect-row');
|
| 2323 |
-
if (!row) return;
|
| 2324 |
const availabilityDiv = row.querySelector('.defect-availability');
|
| 2325 |
const quantityInput = row.querySelector('.defect-quantity-input');
|
| 2326 |
const selectedOption = selectElement.options[selectElement.selectedIndex];
|
| 2327 |
if (!availabilityDiv || !quantityInput) return;
|
| 2328 |
-
|
| 2329 |
if (selectedOption && selectedOption.value) {
|
| 2330 |
const quantity = selectedOption.getAttribute('data-quantity') || '0';
|
| 2331 |
const unit = selectedOption.getAttribute('data-unit') || '?';
|
| 2332 |
const type = selectedOption.getAttribute('data-type') || '?';
|
| 2333 |
-
|
| 2334 |
-
|
| 2335 |
-
|
| 2336 |
-
if (type === 'fabric') {
|
| 2337 |
-
quantityInput.inputMode = 'decimal'; quantityInput.placeholder = 'e.g., 0,5'; quantityInput.step = '0.01';
|
| 2338 |
-
} else {
|
| 2339 |
-
quantityInput.inputMode = 'numeric'; quantityInput.placeholder = 'Кол-во (шт)'; quantityInput.step = '1';
|
| 2340 |
-
}
|
| 2341 |
} else {
|
| 2342 |
availabilityDiv.textContent = '';
|
| 2343 |
quantityInput.inputMode = 'text'; quantityInput.placeholder = 'Количество'; quantityInput.step = 'any';
|
| 2344 |
}
|
| 2345 |
}
|
| 2346 |
-
|
| 2347 |
-
|
| 2348 |
-
|
| 2349 |
-
|
| 2350 |
-
|
| 2351 |
-
}
|
| 2352 |
-
}
|
| 2353 |
-
function defectChangeHandler() { handleDefectChange(this); }
|
| 2354 |
|
| 2355 |
-
// --- Инициализация при загрузке страницы ---
|
| 2356 |
document.addEventListener('DOMContentLoaded', () => {
|
| 2357 |
showTaskDetails();
|
| 2358 |
-
document.querySelectorAll('.dynamic-fitting-row').forEach(row => {
|
| 2359 |
-
|
| 2360 |
-
const fittingSelect = row.querySelector('.fitting-select');
|
| 2361 |
-
if (fittingSelect && fittingSelect.value) { handleFittingChange(fittingSelect); }
|
| 2362 |
-
});
|
| 2363 |
-
document.querySelectorAll('.dynamic-defect-row').forEach(row => {
|
| 2364 |
-
attachDefectChangeEvent(row);
|
| 2365 |
-
const defectSelect = row.querySelector('.defect-material-select');
|
| 2366 |
-
if (defectSelect && defectSelect.value) { handleDefectChange(defectSelect); }
|
| 2367 |
-
});
|
| 2368 |
});
|
| 2369 |
</script>
|
| 2370 |
"""
|
|
@@ -2420,8 +2254,8 @@ QC_PACKING_CONTENT = """
|
|
| 2420 |
# Скрипты ОТК (без изменений)
|
| 2421 |
QC_PACKING_SCRIPTS = """
|
| 2422 |
<script>
|
| 2423 |
-
let maxAllowedQuantity = 0;
|
| 2424 |
-
let totalSewnQuantity = 0;
|
| 2425 |
|
| 2426 |
function updateQcQuantities() {
|
| 2427 |
const select = document.getElementById('sewing_task_id');
|
|
@@ -2429,92 +2263,49 @@ QC_PACKING_SCRIPTS = """
|
|
| 2429 |
const packedInput = document.getElementById('quantity_packed');
|
| 2430 |
const defectiveInput = document.getElementById('quantity_defective');
|
| 2431 |
const totalInfo = document.getElementById('qc-total-info');
|
| 2432 |
-
|
| 2433 |
if (selectedOption && selectedOption.value) {
|
| 2434 |
totalSewnQuantity = parseInt(selectedOption.getAttribute('data-sewn-quantity')) || 0;
|
| 2435 |
-
maxAllowedQuantity = parseInt(selectedOption.getAttribute('data-remaining-quantity')) || 0;
|
| 2436 |
-
|
| 2437 |
-
if(
|
| 2438 |
-
|
| 2439 |
-
|
| 2440 |
-
}
|
| 2441 |
-
if(defectiveInput) {
|
| 2442 |
-
defectiveInput.max = maxAllowedQuantity;
|
| 2443 |
-
defectiveInput.value = '0'; // Сброс
|
| 2444 |
-
}
|
| 2445 |
-
if(totalInfo) {
|
| 2446 |
-
totalInfo.textContent = `Всего сшито: ${totalSewnQuantity} ед. Осталось обработать: ${maxAllowedQuantity} ед. Сумма упак. и брака не должна превышать остаток.`;
|
| 2447 |
-
totalInfo.classList.remove('text-danger', 'text-success');
|
| 2448 |
-
}
|
| 2449 |
-
validateQcSum(); // Валидируем сразу
|
| 2450 |
-
|
| 2451 |
} else {
|
| 2452 |
-
maxAllowedQuantity = 0;
|
| 2453 |
-
totalSewnQuantity = 0;
|
| 2454 |
if(packedInput) { packedInput.max = ''; packedInput.value = ''; }
|
| 2455 |
if(defectiveInput) { defectiveInput.max = ''; defectiveInput.value = '0'; }
|
| 2456 |
if(totalInfo) totalInfo.textContent = 'Выберите задание на пошив.';
|
| 2457 |
totalInfo.classList.remove('text-danger', 'text-success');
|
| 2458 |
}
|
| 2459 |
}
|
| 2460 |
-
|
| 2461 |
function validateQcSum() {
|
| 2462 |
const packedInput = document.getElementById('quantity_packed');
|
| 2463 |
const defectiveInput = document.getElementById('quantity_defective');
|
| 2464 |
const totalInfo = document.getElementById('qc-total-info');
|
| 2465 |
if (!packedInput || !defectiveInput || !totalInfo) return false;
|
| 2466 |
-
|
| 2467 |
-
// Не валидируем, если не выбрано задание
|
| 2468 |
const select = document.getElementById('sewing_task_id');
|
| 2469 |
-
if (!select || !select.value)
|
| 2470 |
-
// totalInfo.textContent = 'Выберите задание на пошив.';
|
| 2471 |
-
return false; // Считаем невалидным, если нет задания
|
| 2472 |
-
}
|
| 2473 |
-
|
| 2474 |
const packed = parseInt(packedInput.value) || 0;
|
| 2475 |
const defective = parseInt(defectiveInput.value) || 0;
|
| 2476 |
const totalProcessed = packed + defective;
|
| 2477 |
-
|
| 2478 |
totalInfo.classList.remove('text-danger', 'text-success');
|
| 2479 |
-
|
| 2480 |
-
if (maxAllowedQuantity =
|
| 2481 |
-
|
| 2482 |
-
|
| 2483 |
-
return false;
|
| 2484 |
-
}
|
| 2485 |
-
if (totalProcessed > maxAllowedQuantity) {
|
| 2486 |
-
totalInfo.textContent = `Ошибка: Сумма (${totalProcessed}) превышает ОСТАТОК (${maxAllowedQuantity})!`;
|
| 2487 |
-
totalInfo.classList.add('text-danger');
|
| 2488 |
-
return false;
|
| 2489 |
-
} else if (totalProcessed === 0) {
|
| 2490 |
-
totalInfo.textContent = `Всего сшито: ${totalSewnQuantity} ед. Осталось обработать: ${maxAllowedQuantity} ед. Укажите кол-во упак. или брака.`;
|
| 2491 |
-
return false; // Не валидно, если сумма 0
|
| 2492 |
-
} else {
|
| 2493 |
-
totalInfo.textContent = `Всего сшито: ${totalSewnQuantity} ед. Осталось обработать: ${maxAllowedQuantity} ед. Сумма (${totalProcessed}) корректна.`;
|
| 2494 |
-
totalInfo.classList.add('text-success');
|
| 2495 |
-
return true;
|
| 2496 |
-
}
|
| 2497 |
}
|
| 2498 |
-
|
| 2499 |
function validateQcForm() {
|
| 2500 |
const select = document.getElementById('sewing_task_id');
|
| 2501 |
-
if (!select || !select.value) {
|
| 2502 |
-
|
| 2503 |
-
}
|
| 2504 |
-
|
| 2505 |
-
if (!isValidSum) {
|
| 2506 |
-
// Сообщение об ошибке уже показано в validateQcSum
|
| 2507 |
-
alert('Ошибка в количестве упакованных или бракованных изделий. Проверьте введенные значения и остаток по заданию.');
|
| 2508 |
-
return false;
|
| 2509 |
-
}
|
| 2510 |
-
return true; // Если сумма корректна, можно отправлять
|
| 2511 |
}
|
| 2512 |
-
|
| 2513 |
document.addEventListener('DOMContentLoaded', () => { updateQcQuantities(); });
|
| 2514 |
</script>
|
| 2515 |
"""
|
| 2516 |
|
| 2517 |
-
# Контент Базы Клиентов (
|
| 2518 |
CLIENTS_CONTENT = """
|
| 2519 |
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 2520 |
<h1 class="h2"><i class="fas fa-users me-2"></i>База клиентов</h1>
|
|
@@ -2575,7 +2366,6 @@ CLIENTS_CONTENT = """
|
|
| 2575 |
<button type="button" class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#historyModal-{{ client.id }}" title="Посмотреть историю отправок">
|
| 2576 |
<i class="fas fa-history"></i> История
|
| 2577 |
</button>
|
| 2578 |
-
{# Можно добавить кнопки редактирования/удаления, если нужно #}
|
| 2579 |
</td>
|
| 2580 |
</tr>
|
| 2581 |
{% else %}
|
|
@@ -2601,7 +2391,8 @@ CLIENTS_CONTENT = """
|
|
| 2601 |
<div class="modal-body">
|
| 2602 |
{% if client.history %}
|
| 2603 |
<ul class="list-group list-group-flush">
|
| 2604 |
-
{
|
|
|
|
| 2605 |
<li class="list-group-item">
|
| 2606 |
<strong>Дата:</strong> {{ record.timestamp_dt.strftime('%Y-%m-%d %H:%M') if record.timestamp_dt else record.timestamp[:16]|replace('T',' ') }} <br>
|
| 2607 |
<strong>ID отправки:</strong> <small>{{ record.shipment_id }}</small><br>
|
|
@@ -2631,10 +2422,8 @@ CLIENTS_CONTENT = """
|
|
| 2631 |
# Скрипты Базы Клиентов (без изменений)
|
| 2632 |
CLIENTS_SCRIPTS = """
|
| 2633 |
<script>
|
| 2634 |
-
// --- Поиск по таблице клиентов ---
|
| 2635 |
const searchInput = document.getElementById('client-search');
|
| 2636 |
const tableBody = document.getElementById('clients-table')?.querySelector('tbody');
|
| 2637 |
-
|
| 2638 |
if (searchInput && tableBody) {
|
| 2639 |
searchInput.addEventListener('input', function() {
|
| 2640 |
const searchTerm = searchInput.value.toLowerCase().trim();
|
|
@@ -2642,38 +2431,20 @@ if (searchInput && tableBody) {
|
|
| 2642 |
let found = false;
|
| 2643 |
rows.forEach(row => {
|
| 2644 |
const searchData = row.dataset.search || '';
|
| 2645 |
-
if (searchData.includes(searchTerm)) {
|
| 2646 |
-
|
| 2647 |
-
found = true;
|
| 2648 |
-
} else {
|
| 2649 |
-
row.style.display = 'none';
|
| 2650 |
-
}
|
| 2651 |
});
|
| 2652 |
-
// Опционально: показать сообщение, если ничего не найдено
|
| 2653 |
const noResultRow = tableBody.querySelector('.no-result-row');
|
| 2654 |
if (!found && searchTerm !== '') {
|
| 2655 |
if (!noResultRow) {
|
| 2656 |
-
const tr = document.createElement('tr');
|
| 2657 |
-
tr.className = 'no-result-row';
|
| 2658 |
tr.innerHTML = `<td colspan="5" class="text-center text-muted">Клиенты не найдены по запросу "${searchTerm}".</td>`;
|
| 2659 |
tableBody.appendChild(tr);
|
| 2660 |
-
} else {
|
| 2661 |
-
|
| 2662 |
-
}
|
| 2663 |
-
} else if (noResultRow) {
|
| 2664 |
-
noResultRow.remove();
|
| 2665 |
-
}
|
| 2666 |
});
|
| 2667 |
}
|
| 2668 |
-
|
| 2669 |
-
// --- Сортировка таблицы (общая функция из админки) ---
|
| 2670 |
-
// Функция sortTable уже определена в BASE_TEMPLATE, она будет работать и здесь
|
| 2671 |
-
// Необходимо только убедиться, что id таблицы ('clients-table') правильный
|
| 2672 |
-
|
| 2673 |
-
document.addEventListener('DOMContentLoaded', function() {
|
| 2674 |
-
// Any specific JS for the clients page can go here
|
| 2675 |
-
// e.g., initializing tooltips if added
|
| 2676 |
-
});
|
| 2677 |
</script>
|
| 2678 |
"""
|
| 2679 |
|
|
@@ -2813,7 +2584,7 @@ ADMIN_CONTENT = """
|
|
| 2813 |
<div class="tab-pane fade" id="cutting-content" role="tabpanel">
|
| 2814 |
<div class="card"><div class="card-header"><i class="fas fa-cut"></i>Задания на раскрой</div><div class="card-body">
|
| 2815 |
<div class="table-responsive"><table class="table table-striped table-hover table-sm"><thead><tr>
|
| 2816 |
-
<th>ID</th><th>Ткань</th><th>Кол-во</th><th>Расход</th>
|
| 2817 |
</tr></thead><tbody>
|
| 2818 |
{% for task in cutting_tasks|reverse %}
|
| 2819 |
<tr>
|
|
@@ -2821,19 +2592,17 @@ ADMIN_CONTENT = """
|
|
| 2821 |
<td>{{ task.fabric_name }}<small title="{{ task.fabric_id }}">({{ task.fabric_id[:6] }}...)</small></td>
|
| 2822 |
<td>{{ format_integer_py(task.cut_items_quantity) }}</td>
|
| 2823 |
<td>{{ format_currency_py(task.fabric_used) }} {{ task.fabric_unit }}</td>
|
| 2824 |
-
{#<td>{{ format_currency_py(task.material_cost) }}</td>#}
|
| 2825 |
-
{#<td>{{ format_currency_py(task.cutting_salary_cost) }}</td>#}
|
| 2826 |
<td><span class="{{ getStatusClass(task.status) }}">{{ getStatusText(task.status) }}</span></td>
|
| 2827 |
<td>{{ task.timestamp_created[:16] | replace('T', ' ') if task.timestamp_created else 'N/A' }}</td>
|
| 2828 |
<td>{{ task.timestamp_completed[:16] | replace('T', ' ') if task.timestamp_completed else '-' }}</td>
|
| 2829 |
-
</tr>{% else %}<tr><td colspan="7" class="text-center text-muted">Нет заданий на раскрой.</td></tr>{% endfor %}
|
| 2830 |
</tbody></table></div></div></div>
|
| 2831 |
</div>
|
| 2832 |
<!-- Вкладка Пошив (БЕЗ ЗП/Стоимости) -->
|
| 2833 |
<div class="tab-pane fade" id="sewing-content" role="tabpanel">
|
| 2834 |
<div class="card"><div class="card-header"><i class="fas fa-tshirt"></i>Задания на пошив</div><div class="card-body">
|
| 2835 |
<div class="table-responsive"><table class="table table-striped table-hover table-sm"><thead><tr>
|
| 2836 |
-
<th>ID</th><th>Изделие</th><th>Сшито</th><th>Исп. фурн.</th>
|
| 2837 |
</tr></thead><tbody>
|
| 2838 |
{% for task in sewing_tasks|reverse %}
|
| 2839 |
<tr>
|
|
@@ -2848,8 +2617,6 @@ ADMIN_CONTENT = """
|
|
| 2848 |
</ul>
|
| 2849 |
{% else %}<span class="text-muted small">-</span>{% endif %}
|
| 2850 |
</td>
|
| 2851 |
-
{#<td>{{ format_currency_py(task.fittings_cost) }}</td>#}
|
| 2852 |
-
{#<td>{{ format_currency_py(task.sewing_salary_cost) }}</td>#}
|
| 2853 |
<td>
|
| 2854 |
{% if task.defects_reported %}
|
| 2855 |
<ul class="list-unstyled mb-0 small text-danger">
|
|
@@ -2868,7 +2635,7 @@ ADMIN_CONTENT = """
|
|
| 2868 |
<td>{{ task.timestamp_created[:16] | replace('T', ' ') if task.timestamp_created else 'N/A' }}</td>
|
| 2869 |
<td>{{ task.timestamp_completed[:16] | replace('T', ' ') if task.timestamp_completed else '-' }}</td>
|
| 2870 |
<td title="{{ task.cutting_task_id }}"><small>{{ task.cutting_task_id[:8] }}...</small></td>
|
| 2871 |
-
</tr>{% else %}<tr><td colspan="10" class="text-center text-muted">Нет заданий на пошив.</td></tr>{% endfor %}
|
| 2872 |
</tbody></table></div></div></div>
|
| 2873 |
</div>
|
| 2874 |
<!-- Вкладка Упакованные (с себестоимостью и ценой) -->
|
|
@@ -3365,13 +3132,7 @@ REPORTS_CONTENT = """
|
|
| 3365 |
REPORTS_SCRIPTS = """
|
| 3366 |
<script>
|
| 3367 |
document.addEventListener('DOMContentLoaded', function () {
|
| 3368 |
-
|
| 3369 |
-
flatpickr(".flatpickr-date", {
|
| 3370 |
-
dateFormat: "Y-m-d",
|
| 3371 |
-
locale: "ru" // Используем русский язык
|
| 3372 |
-
});
|
| 3373 |
-
|
| 3374 |
-
// --- Логика отображения полей фильтра ---
|
| 3375 |
const filterTypeSelect = document.getElementById('filter_type');
|
| 3376 |
const customStartDate = document.getElementById('custom-start-date');
|
| 3377 |
const customEndDate = document.getElementById('custom-end-date');
|
|
@@ -3381,89 +3142,38 @@ document.addEventListener('DOMContentLoaded', function () {
|
|
| 3381 |
|
| 3382 |
function toggleDateSelectors() {
|
| 3383 |
const selectedType = filterTypeSelect.value;
|
| 3384 |
-
|
| 3385 |
-
|
| 3386 |
-
customStartDate.style.display = '
|
| 3387 |
-
|
| 3388 |
-
|
| 3389 |
-
|
| 3390 |
-
|
| 3391 |
-
|
| 3392 |
-
|
| 3393 |
-
if (selectedType ==
|
| 3394 |
-
customStartDate.style.display = 'block';
|
| 3395 |
-
customEndDate.style.display = 'block';
|
| 3396 |
-
} else if (selectedType === 'day') {
|
| 3397 |
-
daySelector.style.display = 'block';
|
| 3398 |
-
} else if (selectedType === 'month') {
|
| 3399 |
-
monthSelector.style.display = 'block';
|
| 3400 |
-
} else if (selectedType === 'year') {
|
| 3401 |
-
yearSelector.style.display = 'block';
|
| 3402 |
-
}
|
| 3403 |
-
// week не имеет отдельного селектора
|
| 3404 |
-
|
| 3405 |
-
// Очищаем *значения* ненужных полей (опционально, но полезно)
|
| 3406 |
-
if (selectedType !== 'custom') {
|
| 3407 |
-
document.getElementById('start_date').value = '';
|
| 3408 |
-
document.getElementById('end_date').value = '';
|
| 3409 |
-
}
|
| 3410 |
-
if (selectedType !== 'day') {
|
| 3411 |
-
const dayPicker = document.getElementById('filter_date_day')._flatpickr;
|
| 3412 |
-
if(dayPicker) dayPicker.clear(); // Используем API flatpickr
|
| 3413 |
-
}
|
| 3414 |
-
if (selectedType !== 'month') {
|
| 3415 |
-
document.getElementById('filter_date_month').value = ''; // Стандартный input type="month"
|
| 3416 |
-
}
|
| 3417 |
-
if (selectedType !== 'year') {
|
| 3418 |
-
const yearInput = document.getElementById('filter_date_year');
|
| 3419 |
-
// if (!yearInput.value) yearInput.value = new Date().getFullYear(); // Не устанавливаем по умолчанию
|
| 3420 |
-
}
|
| 3421 |
}
|
|
|
|
| 3422 |
|
| 3423 |
-
if (filterTypeSelect) {
|
| 3424 |
-
filterTypeSelect.addEventListener('change', toggleDateSelectors);
|
| 3425 |
-
// Вызываем при загрузке, чтобы показать правильные поля на основе выбранного значения
|
| 3426 |
-
toggleDateSelectors();
|
| 3427 |
-
}
|
| 3428 |
-
|
| 3429 |
-
// --- Активация табов Bootstrap для деталей отчета ---
|
| 3430 |
var triggerTabList = [].slice.call(document.querySelectorAll('#reportDetailsTabs button[data-bs-toggle="tab"]'));
|
| 3431 |
triggerTabList.forEach(function (triggerEl) {
|
| 3432 |
var tabInstance = bootstrap.Tab.getInstance(triggerEl) || new bootstrap.Tab(triggerEl);
|
| 3433 |
-
triggerEl.addEventListener('click', function (event) {
|
| 3434 |
-
event.preventDefault();
|
| 3435 |
-
tabInstance.show();
|
| 3436 |
-
window.history.replaceState(null, null, window.location.pathname + window.location.search + triggerEl.getAttribute('data-bs-target'));
|
| 3437 |
-
});
|
| 3438 |
});
|
| 3439 |
-
|
| 3440 |
-
// Активировать таб из URL hash при загрузке, если есть
|
| 3441 |
const validReportHashes = ['#prod-summary-content', '#packed-items-content', '#defects-report-content', '#expenses-report-content'];
|
| 3442 |
-
let reportHash = window.location.hash;
|
| 3443 |
-
let reportTabActivated = false;
|
| 3444 |
if(reportHash && validReportHashes.includes(reportHash) ) {
|
| 3445 |
var reportTabEl = document.querySelector(`button[data-bs-target="${reportHash}"]`);
|
| 3446 |
-
if(reportTabEl) {
|
| 3447 |
-
var reportTabInstance = bootstrap.Tab.getInstance(reportTabEl) || new bootstrap.Tab(reportTabEl);
|
| 3448 |
-
reportTabInstance.show();
|
| 3449 |
-
reportTabActivated = true;
|
| 3450 |
-
}
|
| 3451 |
}
|
| 3452 |
-
// Если хэш невалиден или отсутствует, активируем первый таб
|
| 3453 |
if (!reportTabActivated) {
|
| 3454 |
var defaultReportTabEl = document.getElementById('prod-summary-tab');
|
| 3455 |
-
if (defaultReportTabEl) {
|
| 3456 |
-
var defaultReportTabInstance = bootstrap.Tab.getInstance(defaultReportTabEl) || new bootstrap.Tab(defaultReportTabEl);
|
| 3457 |
-
defaultReportTabInstance.show();
|
| 3458 |
-
// Не меняем hash по умолчанию
|
| 3459 |
-
}
|
| 3460 |
}
|
| 3461 |
-
|
| 3462 |
});
|
| 3463 |
</script>
|
| 3464 |
"""
|
| 3465 |
|
| 3466 |
-
|
| 3467 |
# --- Конец HTML Шаблонов ---
|
| 3468 |
|
| 3469 |
# Добавляем утилиты в контекст Jinja
|
|
@@ -3484,15 +3194,12 @@ if __name__ == '__main__':
|
|
| 3484 |
|
| 3485 |
try:
|
| 3486 |
logging.info("Первоначальная загрузка данных...")
|
| 3487 |
-
load_data()
|
| 3488 |
-
load_client_data()
|
| 3489 |
logging.info("Данные успешно загружены/инициализированы.")
|
| 3490 |
except Exception as e:
|
| 3491 |
logging.critical(f"Не удалось загрузить базы данных при запуске: {e}", exc_info=True)
|
| 3492 |
|
| 3493 |
logging.info("Запуск Flask приложения на http://0.0.0.0:7860")
|
| 3494 |
-
# use_reloader=False ВАЖНО для работы потока бэкапа, даже с debug=True
|
| 3495 |
app.run(debug=True, host='0.0.0.0', port=7860, use_reloader=False)
|
| 3496 |
-
# Для продакшена: debug=False
|
| 3497 |
-
# app.run(debug=False, host='0.0.0.0', port=7860)
|
| 3498 |
|
|
|
|
| 113 |
json.dump(data, file, ensure_ascii=False, indent=4, cls=DecimalEncoder)
|
| 114 |
os.replace(temp_file, DATA_FILE)
|
| 115 |
logging.info(f"Основные данные успешно сохранены в локальный файл {DATA_FILE}.")
|
|
|
|
| 116 |
except Exception as e:
|
| 117 |
logging.error(f"Критическая ошибка при сохранении основных данных: {e}")
|
| 118 |
if os.path.exists(temp_file):
|
|
|
|
| 175 |
json.dump(clients, file, ensure_ascii=False, indent=4)
|
| 176 |
os.replace(temp_file, CLIENT_DATA_FILE)
|
| 177 |
logging.info(f"Данные клиентов успешно сохранены в локальный файл {CLIENT_DATA_FILE}.")
|
|
|
|
| 178 |
except Exception as e:
|
| 179 |
logging.error(f"Критическая ошибка при сохранении данных клиентов: {e}")
|
| 180 |
if os.path.exists(temp_file):
|
|
|
|
| 596 |
flash(f"Недостаточно ткани '{fabric['name']}'. В наличии: {format_currency_py(fabric_available_quantity)} {fabric['unit']}, требуется: {format_currency_py(fabric_used)} {fabric['unit']}.", "danger")
|
| 597 |
return redirect(url_for('cutting'))
|
| 598 |
|
|
|
|
| 599 |
fabric_price_per_unit = to_decimal(fabric.get('price_per_unit', '0.00'))
|
| 600 |
material_cost = fabric_used * fabric_price_per_unit
|
| 601 |
salary_cutter = to_decimal(config.get('salary_cutter_per_unit', '0.00'))
|
|
|
|
| 604 |
current_time = get_current_time().isoformat()
|
| 605 |
|
| 606 |
new_cutting_task = {
|
| 607 |
+
'id': uuid.uuid4().hex, 'fabric_id': fabric_id,
|
| 608 |
+
'fabric_name': fabric['name'], 'fabric_unit': fabric['unit'],
|
| 609 |
+
'cut_items_quantity': cut_items_quantity, 'fabric_used': str(fabric_used),
|
| 610 |
+
'status': 'pending', 'timestamp_created': current_time, 'timestamp_completed': None,
|
| 611 |
+
'material_cost': str(material_cost), 'cutting_salary_cost': str(cutting_salary_cost)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 612 |
}
|
| 613 |
|
|
|
|
| 614 |
new_fabric_quantity = fabric_available_quantity - fabric_used
|
| 615 |
updated = False
|
| 616 |
materials_list = data.get('materials', [])
|
|
|
|
| 629 |
data['materials'] = materials_list
|
| 630 |
|
| 631 |
save_data(data)
|
|
|
|
| 632 |
flash(f"Задание на раскрой для {cut_items_quantity} ед. из ткани '{fabric['name']}' успешно создано. Статус: Ожидает пошива.", "success")
|
| 633 |
upload_db_to_hf(DATA_FILE)
|
| 634 |
return redirect(url_for('cutting'))
|
|
|
|
| 643 |
f_copy = find_item_by_id(f['id'], 'materials')
|
| 644 |
if f_copy:
|
| 645 |
f_copy['quantity_str'] = format_currency_py(f_copy.get('quantity', '0.00'))
|
|
|
|
|
|
|
| 646 |
fabrics_dec.append(f_copy)
|
| 647 |
|
| 648 |
page_title = "Раскрой ткани"
|
| 649 |
# Используем ОПЕРАЦИОННЫЙ базовый шаблон
|
| 650 |
html = BASE_TEMPLATE_OPERATIONAL.replace('__TITLE__', page_title)
|
| 651 |
+
html = html.replace('__CONTENT__', CUTTING_CONTENT)
|
| 652 |
html = html.replace('__SCRIPTS__', CUTTING_SCRIPTS)
|
| 653 |
return render_template_string(html, fabrics=fabrics_dec)
|
| 654 |
|
|
|
|
| 699 |
can_sew = True
|
| 700 |
current_time = get_current_time().isoformat()
|
| 701 |
|
| 702 |
+
# 1. Списание фурнитуры
|
| 703 |
if fitting_ids and fitting_quantities and len(fitting_ids) == len(fitting_quantities):
|
| 704 |
for i in range(len(fitting_ids)):
|
| 705 |
fit_id = fitting_ids[i]
|
|
|
|
| 736 |
|
| 737 |
if not can_sew: return redirect(url_for('sewing'))
|
| 738 |
|
| 739 |
+
# 2. Обработка брака
|
| 740 |
if defect_material_ids and defect_quantities and len(defect_material_ids) == len(defect_quantities):
|
| 741 |
for i in range(len(defect_material_ids)):
|
| 742 |
def_mat_id = defect_material_ids[i]
|
|
|
|
| 796 |
current_qty_dec = to_decimal(mat.get('quantity', '0'))
|
| 797 |
new_quantity_dec = current_qty_dec - qty_to_deduct
|
| 798 |
is_fabric = mat['type'] == 'fabric'
|
| 799 |
+
if is_fabric: new_quantity_dec = new_quantity_dec.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
|
| 800 |
+
else: new_quantity_dec = new_quantity_dec.quantize(Decimal('1'), rounding=ROUND_HALF_UP)
|
|
|
|
|
|
|
| 801 |
if new_quantity_dec < 0: new_quantity_dec = Decimal('0')
|
| 802 |
materials_list[i]['quantity'] = str(new_quantity_dec)
|
| 803 |
materials_list[i]['timestamp_last_updated'] = current_time
|
|
|
|
| 806 |
flash(f"Критическая ошибка: Не удалось найти материал ID {mat_id} для списания.", "danger")
|
| 807 |
return redirect(url_for('sewing'))
|
| 808 |
|
| 809 |
+
# 4. Расчет ЗП швеи
|
| 810 |
salary_sewer = to_decimal(config.get('salary_sewer_per_unit', '0.00'))
|
| 811 |
sewing_salary_cost = Decimal(sewn_quantity) * salary_sewer
|
| 812 |
|
|
|
|
| 853 |
data['cutting_tasks'] = cutting_tasks_list
|
| 854 |
|
| 855 |
save_data(data)
|
|
|
|
| 856 |
flash(f"Пошив {sewn_quantity} ед. '{sewn_product_name}' зарегистрирован. Отправлено на ОТК.", "success")
|
| 857 |
if defect_log_list: flash(f"Зарегистрирован брак: {len(defect_log_list)} позиций.", "warning")
|
| 858 |
upload_db_to_hf(DATA_FILE)
|
|
|
|
| 867 |
for task_id in [t['id'] for t in pending_cutting_tasks]:
|
| 868 |
task_data = find_item_by_id(task_id, 'cutting_tasks')
|
| 869 |
if task_data:
|
|
|
|
| 870 |
task_data['fabric_used_str'] = format_currency_py(task_data.get('fabric_used', '0.00'))
|
| 871 |
+
# Не добавляем стоимость/зп в _str
|
| 872 |
tasks_for_template.append(task_data)
|
| 873 |
|
| 874 |
fittings_dec = []
|
|
|
|
| 876 |
f_copy = find_item_by_id(f['id'], 'materials')
|
| 877 |
if f_copy:
|
| 878 |
f_copy['quantity_str'] = format_integer_py(f_copy.get('quantity', '0'))
|
| 879 |
+
# Не добавляем price_str
|
| 880 |
fittings_dec.append(f_copy)
|
| 881 |
|
| 882 |
all_materials_dec = []
|
|
|
|
| 887 |
mat_data['quantity_str'] = format_currency_py(mat_data.get('quantity', '0.00'))
|
| 888 |
else:
|
| 889 |
mat_data['quantity_str'] = format_integer_py(mat_data.get('quantity', '0'))
|
| 890 |
+
# Не добавляем price_str
|
| 891 |
all_materials_dec.append(mat_data)
|
| 892 |
|
| 893 |
page_title = "Пошив изделий"
|
| 894 |
# Используем ОПЕРАЦИОННЫЙ базовый шаблон
|
| 895 |
html = BASE_TEMPLATE_OPERATIONAL.replace('__TITLE__', page_title)
|
| 896 |
+
html = html.replace('__CONTENT__', SEWING_CONTENT)
|
| 897 |
html = html.replace('__SCRIPTS__', SEWING_SCRIPTS)
|
| 898 |
return render_template_string(html,
|
| 899 |
cutting_tasks=tasks_for_template,
|
|
|
|
| 999 |
if 'qc_packing_items' not in data: data['qc_packing_items'] = []
|
| 1000 |
data['qc_packing_items'].append(packed_item_entry)
|
| 1001 |
|
| 1002 |
+
# Регистрация брака
|
| 1003 |
if quantity_defective > 0:
|
| 1004 |
cutting_task = find_item_by_id(sewing_task.get('cutting_task_id'), 'cutting_tasks')
|
| 1005 |
if not cutting_task: cutting_task = {'material_cost': Decimal('0.00'), 'cutting_salary_cost': Decimal('0.00'), 'cut_items_quantity': 1}
|
|
|
|
| 1050 |
|
| 1051 |
data['sewing_tasks'] = sewing_tasks_list
|
| 1052 |
save_data(data)
|
| 1053 |
+
# Убираем стоимость из flash
|
| 1054 |
flash_message = f"ОТК/Упаковка для '{sewing_task['product_name']}': упаковано {quantity_packed}, брак {quantity_defective}. "
|
| 1055 |
if packed_item_entry:
|
| 1056 |
flash_message += f"Статус упакованных: Готово к отправке."
|
|
|
|
| 1084 |
@app.route('/clients', methods=['GET', 'POST'])
|
| 1085 |
def clients_panel():
|
| 1086 |
if request.method == 'POST':
|
|
|
|
| 1087 |
name = request.form.get('client_name', '').strip()
|
| 1088 |
phone = request.form.get('client_phone', '').strip()
|
| 1089 |
address = request.form.get('client_address', '').strip()
|
|
|
|
| 1090 |
if not name or not phone:
|
| 1091 |
flash("Имя/Название организации и номер телефона обязательны.", "danger")
|
| 1092 |
return redirect(url_for('clients_panel'))
|
|
|
|
| 1093 |
clients = load_client_data()
|
|
|
|
| 1094 |
normalized_phone = ''.join(filter(str.isdigit, phone))
|
| 1095 |
if any(''.join(filter(str.isdigit, c.get('phone', ''))) == normalized_phone for c in clients):
|
| 1096 |
flash(f"Клиент с похожим номером телефона ({phone}) уже существует.", "warning")
|
| 1097 |
return redirect(url_for('clients_panel'))
|
| 1098 |
+
new_client = {'id': uuid.uuid4().hex, 'name': name, 'phone': phone, 'address': address if address else None, 'history': [] }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1099 |
clients.append(new_client)
|
| 1100 |
save_client_data(clients)
|
| 1101 |
flash(f"Клиент '{name}' успешно добавлен.", "success")
|
| 1102 |
upload_db_to_hf(CLIENT_DATA_FILE)
|
| 1103 |
return redirect(url_for('clients_panel'))
|
| 1104 |
|
| 1105 |
+
# GET запрос
|
| 1106 |
clients_data = load_client_data()
|
| 1107 |
clients_data.sort(key=lambda x: x.get('name', '').lower())
|
|
|
|
| 1108 |
for client in clients_data:
|
| 1109 |
if 'history' in client:
|
| 1110 |
+
client['history'].sort(key=lambda x: x.get('timestamp', ''), reverse=True) # Сортируем историю по дате
|
| 1111 |
for record in client['history']:
|
| 1112 |
record['timestamp_dt'] = parse_iso_datetime(record.get('timestamp'))
|
| 1113 |
|
| 1114 |
page_title = "База клиентов"
|
| 1115 |
# Используем ОБЫЧНЫЙ базовый шаблон
|
| 1116 |
html = BASE_TEMPLATE.replace('__TITLE__', page_title)
|
| 1117 |
+
html = html.replace('__CONTENT__', CLIENTS_CONTENT) # Используем исправленный CLIENTS_CONTENT
|
| 1118 |
html = html.replace('__SCRIPTS__', CLIENTS_SCRIPTS)
|
| 1119 |
return render_template_string(html, clients=clients_data)
|
| 1120 |
|
|
|
|
| 1150 |
page_title = "Админ-панель"
|
| 1151 |
# Используем ОБЫЧНЫЙ базовый шаблон
|
| 1152 |
html = BASE_TEMPLATE.replace('__TITLE__', page_title)
|
| 1153 |
+
html = html.replace('__CONTENT__', ADMIN_CONTENT) # Используем обновленный ADMIN_CONTENT
|
| 1154 |
html = html.replace('__SCRIPTS__', ADMIN_SCRIPTS)
|
| 1155 |
|
| 1156 |
return render_template_string(
|
|
|
|
| 1189 |
return redirect(url_for('admin_panel') + '#dispatch-content')
|
| 1190 |
|
| 1191 |
data = load_data()
|
| 1192 |
+
clients = load_client_data() # Загружаем свежие данные клиентов
|
| 1193 |
item_found = False
|
| 1194 |
client_found = False
|
| 1195 |
client_name = None
|
| 1196 |
|
| 1197 |
+
item_to_dispatch_ref = None # Ссылка на элемент в списке data
|
| 1198 |
item_index = -1
|
| 1199 |
qc_packing_items_list = data.get('qc_packing_items', [])
|
| 1200 |
for i, item in enumerate(qc_packing_items_list):
|
|
|
|
| 1224 |
flash("Ошибка: Не выбран клиент для отправки.", "danger")
|
| 1225 |
return redirect(url_for('admin_panel') + '#dispatch-content')
|
| 1226 |
|
| 1227 |
+
# Найти клиента
|
| 1228 |
+
client_object_to_update = None # Ссылка на объект клиента в списке clients
|
| 1229 |
for i, client in enumerate(clients):
|
| 1230 |
if client.get('id') == client_id:
|
| 1231 |
client_found = True
|
| 1232 |
client_name = client.get('name')
|
| 1233 |
+
client_object_to_update = client # Получаем ссылку
|
| 1234 |
+
client_index_to_save = i # На всякий случай
|
| 1235 |
break
|
| 1236 |
|
| 1237 |
if not client_found:
|
| 1238 |
flash(f"Ошибка: Клиент с ID {client_id} не найден.", "danger")
|
| 1239 |
return redirect(url_for('admin_panel') + '#dispatch-content')
|
| 1240 |
|
| 1241 |
+
# Обновляем статус товара
|
| 1242 |
item_to_dispatch_ref['status'] = 'shipped_client'
|
| 1243 |
shipment_details['client_id'] = client_id
|
| 1244 |
shipment_details['client_name'] = client_name
|
| 1245 |
item_to_dispatch_ref['shipment_details'] = shipment_details
|
| 1246 |
+
logging.info(f"Товар {item_id} помечен как shipped_client для клиента {client_name} ({client_id}).")
|
| 1247 |
|
| 1248 |
+
# Добавляем запись в историю клиента, работая со ссылкой
|
| 1249 |
history_entry = {
|
| 1250 |
'shipment_id': uuid.uuid4().hex,
|
| 1251 |
'timestamp': current_time_iso,
|
|
|
|
| 1253 |
'packed_item_id': item_id
|
| 1254 |
}
|
| 1255 |
# Убеждаемся, что 'history' существует и является списком
|
| 1256 |
+
if 'history' not in client_object_to_update or not isinstance(client_object_to_update.get('history'), list):
|
| 1257 |
+
client_object_to_update['history'] = []
|
| 1258 |
logging.warning(f"Инициализирован список истории для клиента {client_id}")
|
| 1259 |
|
| 1260 |
+
client_object_to_update['history'].append(history_entry)
|
| 1261 |
+
logging.info(f"Запись добавлена в историю клиента {client_id}. Новая длина истории: {len(client_object_to_update['history'])}")
|
| 1262 |
client_data_changed = True
|
| 1263 |
|
| 1264 |
# Обработка отправки на Дордой
|
|
|
|
| 1274 |
# Сохраняем основной файл данных (qc_packing_items_list был изменен по ссылке)
|
| 1275 |
data['qc_packing_items'] = qc_packing_items_list
|
| 1276 |
save_data(data)
|
| 1277 |
+
upload_db_to_hf(DATA_FILE) # Инициируем бэкап
|
| 1278 |
logging.info(f"Основные данные сохранены после отправки товара {item_id}.")
|
| 1279 |
|
| 1280 |
# Сохраняем файл клиентов, если были изменения
|
| 1281 |
if client_data_changed:
|
| 1282 |
+
save_client_data(clients) # Передаем измененный список clients
|
| 1283 |
+
upload_db_to_hf(CLIENT_DATA_FILE) # Инициируем бэкап
|
| 1284 |
logging.info(f"Данные клиента {client_id} сохранены после добавления истории.")
|
| 1285 |
else:
|
| 1286 |
+
logging.info(f"Данные клиентов не изменялись при отправке товара {item_id}.")
|
| 1287 |
|
| 1288 |
# Сообщение об успехе
|
| 1289 |
destination_text = f"клиенту '{client_name}'" if destination_type == 'client' else "на Торговую точку Дордой"
|
|
|
|
| 1408 |
if os.path.exists(DATA_FILE):
|
| 1409 |
upload_db_to_hf(DATA_FILE)
|
| 1410 |
files_uploaded += 1
|
| 1411 |
+
else: flash(f"Локальный файл {DATA_FILE} не найден.", "warning")
|
|
|
|
| 1412 |
with client_data_lock:
|
| 1413 |
if os.path.exists(CLIENT_DATA_FILE):
|
| 1414 |
upload_db_to_hf(CLIENT_DATA_FILE)
|
| 1415 |
files_uploaded += 1
|
| 1416 |
+
else: flash(f"Локальный файл {CLIENT_DATA_FILE} не найден.", "warning")
|
| 1417 |
+
if files_uploaded > 0: flash(f"Резервное копирование {files_uploaded} файлов успешно инициировано на Hugging Face.", "success")
|
| 1418 |
+
else: flash("Не найдено файлов для резервного копирования.", "warning")
|
|
|
|
|
|
|
|
|
|
| 1419 |
except Exception as e:
|
| 1420 |
logging.error(f"Ошибка при ручном резервном копировании: {e}")
|
| 1421 |
flash(f"Ошибка при создании резервной копии: {e}", "danger")
|
|
|
|
| 1423 |
|
| 1424 |
@app.route('/download', methods=['GET'])
|
| 1425 |
def download_hf():
|
| 1426 |
+
downloaded_files = []; errors = []
|
|
|
|
|
|
|
| 1427 |
try:
|
| 1428 |
logging.info(f"Запуск ручного скачивания {DATA_FILE} с Hugging Face...")
|
| 1429 |
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)
|
|
|
|
| 1432 |
except HfHubHTTPError as e:
|
| 1433 |
if e.response.status_code == 404: errors.append(f"Файл {DATA_FILE} не найден в репозитории {REPO_ID}.")
|
| 1434 |
else: errors.append(f"Ошибка HTTP при скачивании {DATA_FILE}: {e}"); logging.error(f"Ошибка HTTP при скачивании {DATA_FILE}: {e}")
|
| 1435 |
+
except Exception as e: logging.error(f"Ошибка при ручном скачивании {DATA_FILE}: {e}"); errors.append(f"Ошибка при скачивании {DATA_FILE}: {e}")
|
|
|
|
|
|
|
|
|
|
| 1436 |
try:
|
| 1437 |
logging.info(f"Запуск ручного скачивания {CLIENT_DATA_FILE} с Hugging Face...")
|
| 1438 |
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)
|
|
|
|
| 1442 |
except HfHubHTTPError as e:
|
| 1443 |
if e.response.status_code == 404: errors.append(f"Файл {CLIENT_DATA_FILE} не найден в репозитории {REPO_ID}.")
|
| 1444 |
else: errors.append(f"Ошибка HTTP при скачивании {CLIENT_DATA_FILE}: {e}"); logging.error(f"Ошибка HTTP при скачивании {CLIENT_DATA_FILE}: {e}")
|
| 1445 |
+
except Exception as e: logging.error(f"Ошибка при ручном скачивании {CLIENT_DATA_FILE}: {e}"); errors.append(f"Ошибка при скачивании {CLIENT_DATA_FILE}: {e}")
|
|
|
|
|
|
|
|
|
|
| 1446 |
if downloaded_files: flash(f"Файлы ({', '.join(downloaded_files)}) успешно скачаны с Hugging Face. Локальные файлы обновлены.", "success")
|
| 1447 |
if errors: flash("Во время скачивания произошли ошибки: " + "; ".join(errors), "danger")
|
| 1448 |
if not downloaded_files and not errors: flash("Не удалось инициировать скачивание.", "warning")
|
|
|
|
| 1497 |
if packed_time and start_date <= packed_time <= end_date:
|
| 1498 |
shipment_time_dt = None
|
| 1499 |
details = item_data.get('shipment_details')
|
| 1500 |
+
if details and details.get('timestamp'): shipment_time_dt = parse_iso_datetime(details.get('timestamp'))
|
|
|
|
| 1501 |
item_data['shipment_time_dt'] = shipment_time_dt
|
| 1502 |
filtered_packed_items.append(item_data)
|
| 1503 |
|
|
|
|
| 1580 |
.btn-info { background-color: #0dcaf0; border-color: #0dcaf0; color: #000; }
|
| 1581 |
.table-hover tbody tr:hover { background-color: rgba(0, 0, 0, 0.05); }
|
| 1582 |
.container-main { max-width: 1600px; margin: 0 auto; padding-left: 15px; padding-right: 15px; }
|
| 1583 |
+
/* Статусы */
|
| 1584 |
+
.status-pending { color: #0dcaf0; font-weight: bold; } /* Ожидает пошива (был text-warning) */
|
| 1585 |
+
.status-completed { color: #198754; font-weight: bold; } /* Завершено */
|
| 1586 |
+
.status-pending_qc { color: #ffc107; font-weight: bold; } /* Ожидает ОТК */
|
| 1587 |
+
.status-packed_ready_to_ship { color: #6f42c1; font-weight: bold; } /* Готово к отправке (изменил цвет на фиолетовый) */
|
| 1588 |
+
.status-shipped_client { color: #0d6efd; font-weight: bold; } /* Отправлено клиенту (синий) */
|
| 1589 |
+
.status-shipped_dor_doi { color: #20c997; font-weight: bold; } /* Отправлено на Дордой (бирюзовый) */
|
| 1590 |
+
/* Дополнительные классы для текста */
|
| 1591 |
+
.text-ready { color: #6f42c1 !important; } /* Готово к отправке (фиолетовый) */
|
| 1592 |
+
.text-shipped-client { color: #0d6efd !important; } /* Отправлено клиенту (синий) */
|
| 1593 |
+
.text-shipped-dordoi { color: #20c997 !important; } /* Отправлено на Дордой (бирюзовый) */
|
| 1594 |
+
/* --- */
|
| 1595 |
.flash-messages .alert { margin-bottom: 1rem; border-radius: 0.5rem; }
|
| 1596 |
.dynamic-row, .dynamic-fitting-row, .dynamic-defect-row { border: 1px solid #eee; padding: 15px; margin-bottom: 15px; border-radius: 5px; background-color: #fdfdfd; position: relative; }
|
| 1597 |
.remove-row-btn, .remove-fitting-row-btn, .remove-defect-row-btn { position: absolute; top: 10px; right: 10px; z-index: 10; }
|
|
|
|
| 1691 |
|
| 1692 |
<script>
|
| 1693 |
// Глобальная функция для форматирования чисел как валюты (JS)
|
| 1694 |
+
function formatCurrencyJS(value) { try { const number = parseFloat(String(value).replace(/\s/g, '').replace(',', '.')); if (isNaN(number)) { return '0,00'; } return number.toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } catch (e) { return '0,00'; } }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1695 |
// Глобальная функция для форматирования целых чисел (JS)
|
| 1696 |
+
function formatIntegerJS(value) { try { const number = parseInt(String(value).replace(/\s/g, '').replace(',', '.').split('.')[0]); if (isNaN(number)) { return '0'; } return number.toLocaleString('ru-RU'); } catch (e) { return '0'; } }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1697 |
// Глобальная функция для получения текущего времени из футера
|
| 1698 |
+
function getCurrentTimeFromFooter() { const footer = document.querySelector('.footer p'); const timeMatch = footer ? footer.textContent.match(/\((.*?)\)/) : null; return timeMatch ? timeMatch[1] : new Date().toLocaleString(); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1699 |
// Вспомогательные JS функции для статусов (могут быть полезны для динамики)
|
| 1700 |
+
function getStatusTextJS(statusKey) { const map = {'pending': 'Ожидает пошива','completed': 'Завершено','pending_qc': 'Ожидает ОТК','packed_ready_to_ship': 'Готово к отправке','shipped_client': 'Отправлено клиенту','shipped_dor_doi': 'Отправлено на Дордой'}; return map[statusKey] || statusKey; }
|
| 1701 |
+
function getStatusClassJS(statusKey) { const map = {'pending': 'status-pending text-info','completed': 'status-completed text-success','pending_qc': 'status-pending_qc text-warning','packed_ready_to_ship': 'status-packed_ready_to_ship text-ready','shipped_client': 'status-shipped_client text-shipped-client','shipped_dor_doi': 'status-shipped_dor_doi text-shipped-dordoi'}; return map[statusKey] || ''; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1702 |
</script>
|
| 1703 |
__SCRIPTS__
|
| 1704 |
</body>
|
| 1705 |
</html>
|
| 1706 |
"""
|
| 1707 |
|
| 1708 |
+
# ОПЕРАЦИОННЫЙ Базовый шаблон (БЕЗ навигации и БЕЗ кнопки "Назад")
|
| 1709 |
BASE_TEMPLATE_OPERATIONAL = """
|
| 1710 |
<!DOCTYPE html>
|
| 1711 |
<html lang="ru">
|
|
|
|
| 1767 |
{# --- НАВИГАЦИЯ УБРАНА --- #}
|
| 1768 |
|
| 1769 |
<div class="container-main mt-4">
|
| 1770 |
+
{# --- КНОПКА НАЗАД УБРАНА --- #}
|
| 1771 |
+
{# <div class="mb-3">
|
| 1772 |
<a href="{{ url_for('admin_panel') }}" class="btn btn-sm btn-outline-secondary">
|
| 1773 |
<i class="fas fa-arrow-left me-1"></i> Назад в Админ-панель
|
| 1774 |
</a>
|
| 1775 |
+
</div> #}
|
| 1776 |
+
|
| 1777 |
+
<h2 class="mb-4">__TITLE__</h2> {# Добавлен заголовок страницы #}
|
| 1778 |
|
| 1779 |
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 1780 |
{% if messages %}
|
|
|
|
| 1885 |
const firstRow = container.querySelector('.dynamic-row');
|
| 1886 |
if (!firstRow) { console.warn("No template row found."); return; }
|
| 1887 |
const newRow = firstRow.cloneNode(true);
|
|
|
|
|
|
|
| 1888 |
newRow.querySelectorAll('input[type="text"], input[type="number"]').forEach(input => input.value = '');
|
| 1889 |
newRow.querySelectorAll('select').forEach(select => {
|
| 1890 |
if (select.name === 'item_unit[]') select.value = 'м';
|
|
|
|
| 1894 |
});
|
| 1895 |
const newCategoryInput = newRow.querySelector('.new-category-input');
|
| 1896 |
if (newCategoryInput) { newCategoryInput.style.display = 'none'; newCategoryInput.required = false; newCategoryInput.value = ''; }
|
|
|
|
| 1897 |
const removeBtn = newRow.querySelector('.remove-row-btn');
|
| 1898 |
+
if (removeBtn) removeBtn.style.display = 'inline-block';
|
|
|
|
| 1899 |
container.appendChild(newRow);
|
| 1900 |
attachCategoryChangeEvent(newRow);
|
| 1901 |
}
|
| 1902 |
+
function removeRow(button) { const row = button.closest('.dynamic-row'); if (row) row.remove(); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1903 |
function handleCategoryChange(selectElement) {
|
| 1904 |
+
const row = selectElement.closest('.dynamic-row'); if (!row) return;
|
| 1905 |
+
const newCategoryInput = row.querySelector('.new-category-input'); if (!newCategoryInput) return;
|
|
|
|
|
|
|
| 1906 |
const isNew = selectElement.value === '__new__';
|
| 1907 |
newCategoryInput.style.display = isNew ? 'block' : 'none';
|
| 1908 |
newCategoryInput.required = isNew;
|
| 1909 |
if (!isNew) newCategoryInput.value = '';
|
| 1910 |
}
|
|
|
|
| 1911 |
function attachCategoryChangeEvent(rowElement) {
|
| 1912 |
const categorySelect = rowElement.querySelector('.category-select');
|
| 1913 |
+
if(categorySelect) { categorySelect.removeEventListener('change', categoryChangeHandler); categorySelect.addEventListener('change', categoryChangeHandler); }
|
|
|
|
|
|
|
|
|
|
| 1914 |
}
|
|
|
|
| 1915 |
function categoryChangeHandler() { handleCategoryChange(this); }
|
|
|
|
| 1916 |
document.addEventListener('DOMContentLoaded', () => {
|
| 1917 |
+
document.querySelectorAll('.dynamic-row').forEach(row => { attachCategoryChangeEvent(row); const categorySelect = row.querySelector('.category-select'); if (categorySelect) handleCategoryChange(categorySelect); });
|
| 1918 |
+
if (!document.querySelector('#material-rows .dynamic-row')) { addRow(); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1919 |
});
|
| 1920 |
</script>
|
| 1921 |
"""
|
|
|
|
| 1927 |
<div class="card-body">
|
| 1928 |
<form method="POST" id="cutting-form">
|
| 1929 |
<div class="row mb-3 align-items-end">
|
| 1930 |
+
<div class="col-md-5">
|
| 1931 |
<label for="fabric_id" class="form-label">Выберите ткань:</label>
|
| 1932 |
<select id="fabric_id" name="fabric_id" class="form-select" required onchange="updateAvailableQuantity()">
|
| 1933 |
<option value="">-- Выберите ткань --</option>
|
| 1934 |
+
{% for fabric in fabrics %}
|
| 1935 |
+
<option value="{{ fabric.id }}" data-unit="{{ fabric.unit }}" data-quantity="{{ fabric.quantity_str }}">
|
|
|
|
|
|
|
|
|
|
| 1936 |
{{ fabric.name }} ({{ fabric.category | default('Без категории') }}) - {{ fabric.quantity_str }} {{ fabric.unit }}
|
| 1937 |
</option>
|
| 1938 |
{% endfor %}
|
|
|
|
| 1951 |
<button type="submit" class="btn btn-primary w-100"><i class="fas fa-paper-plane me-1"></i> Ok</button>
|
| 1952 |
</div>
|
| 1953 |
</div>
|
|
|
|
| 1954 |
</form>
|
| 1955 |
</div>
|
| 1956 |
</div>
|
|
|
|
| 1965 |
const availableDiv = document.getElementById('available-quantity');
|
| 1966 |
const unitSpan = document.getElementById('fabric-unit');
|
| 1967 |
if (selectedOption && selectedOption.value) {
|
|
|
|
| 1968 |
const quantity = selectedOption.getAttribute('data-quantity') || '0,00';
|
| 1969 |
const unit = selectedOption.getAttribute('data-unit') || '?';
|
| 1970 |
+
if(availableDiv) availableDiv.textContent = `В наличии: ${quantity} ${unit}`;
|
|
|
|
|
|
|
| 1971 |
if(unitSpan) unitSpan.textContent = unit;
|
| 1972 |
} else {
|
| 1973 |
if(availableDiv) availableDiv.textContent = '';
|
| 1974 |
if(unitSpan) unitSpan.textContent = 'м';
|
| 1975 |
}
|
| 1976 |
}
|
| 1977 |
+
document.addEventListener('DOMContentLoaded', () => { updateAvailableQuantity(); });
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1978 |
</script>
|
| 1979 |
"""
|
| 1980 |
|
|
|
|
| 1991 |
<label for="cutting_task_id" class="form-label">Выберите задание на раскрой:</label>
|
| 1992 |
<select id="cutting_task_id" name="cutting_task_id" class="form-select" required onchange="showTaskDetails()">
|
| 1993 |
<option value="">-- Выберите задание --</option>
|
| 1994 |
+
{% for task in cutting_tasks %}
|
| 1995 |
+
<option value="{{ task.id }}" data-fabric-name="{{ task.fabric_name }}" data-cut-quantity="{{ task.cut_items_quantity }}" data-fabric-used="{{ task.fabric_used_str }} {{ task.fabric_unit }}">
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1996 |
#{{ loop.index }} - {{ task.fabric_name }} - {{ task.cut_items_quantity }} ед. (Раскрой от {{ task.timestamp_created[:10] }})
|
| 1997 |
</option>
|
| 1998 |
{% endfor %}
|
|
|
|
| 2012 |
<p class="mb-1"><strong>Ткань:</strong> <span id="detail-fabric-name"></span></p>
|
| 2013 |
<p class="mb-1"><strong>Раскроено:</strong> <span id="detail-cut-quantity"></span> ед.</p>
|
| 2014 |
<p class="mb-1"><strong>Расход ткани (на все):</strong> <span id="detail-fabric-used"></span></p>
|
|
|
|
| 2015 |
</div>
|
| 2016 |
+
<div class="col-md-6"></div>
|
| 2017 |
</div>
|
| 2018 |
</div>
|
| 2019 |
|
|
|
|
| 2035 |
<div class="col-md-5">
|
| 2036 |
<select name="fitting_ids[]" class="form-select form-select-sm fitting-select">
|
| 2037 |
<option value="">-- Выберите фурнитуру --</option>
|
| 2038 |
+
{% for fitting in fittings %}
|
|
|
|
| 2039 |
<option value="{{ fitting.id }}" data-quantity="{{ fitting.quantity_str }}" data-unit="{{ fitting.unit }}">
|
| 2040 |
{{ fitting.name }} ({{ fitting.category | default('Без категории') }}) - {{ fitting.quantity_str }} {{ fitting.unit }}
|
| 2041 |
</option>
|
|
|
|
| 2043 |
</select>
|
| 2044 |
</div>
|
| 2045 |
<div class="col-md-3">
|
| 2046 |
+
<input type="number" name="fitting_quantities[]" class="form-control form-control-sm" placeholder="Кол-во (на все сшитые)" min="1" step="1">
|
| 2047 |
</div>
|
| 2048 |
+
<div class="col-md-3 fitting-availability form-text text-info"></div>
|
| 2049 |
<button type="button" class="btn btn-sm btn-danger remove-fitting-row-btn" onclick="removeFittingRow(this)" title="Удалить фурнитуру"><i class="fas fa-times"></i></button>
|
| 2050 |
</div>
|
| 2051 |
<!-- Конец шаблона -->
|
|
|
|
| 2061 |
<div class="col-md-5">
|
| 2062 |
<select name="defect_material_id[]" class="form-select form-select-sm defect-material-select">
|
| 2063 |
<option value="">-- Выберите материал/фурнитуру для брака --</option>
|
| 2064 |
+
{% for material in all_materials %}
|
| 2065 |
{% set unit_display = material.unit %}
|
| 2066 |
{% set type_display = 'Фурн.' if material.type == 'fittings' else 'Ткань' %}
|
|
|
|
| 2067 |
<option value="{{ material.id }}" data-quantity="{{ material.quantity_str }}" data-unit="{{ unit_display }}" data-type="{{ material.type }}">
|
| 2068 |
{{ material.name }} ({{ material.category | default('Без категории') }}) - {{ material.quantity_str }} {{ unit_display }} [{{ type_display }}]
|
| 2069 |
</option>
|
|
|
|
| 2071 |
</select>
|
| 2072 |
</div>
|
| 2073 |
<div class="col-md-3">
|
| 2074 |
+
<input type="text" name="defect_quantity[]" class="form-control form-control-sm defect-quantity-input" placeholder="Количество">
|
| 2075 |
</div>
|
| 2076 |
+
<div class="col-md-3 defect-availability form-text text-info"></div>
|
| 2077 |
<button type="button" class="btn btn-sm btn-danger remove-defect-row-btn" onclick="removeDefectRow(this)" title="Удалить брак"><i class="fas fa-times"></i></button>
|
| 2078 |
</div>
|
| 2079 |
<!-- Конец шаблона -->
|
|
|
|
| 2104 |
const productNameInput = document.getElementById('sewn_product_name');
|
| 2105 |
|
| 2106 |
if (selectedOption && selectedOption.value) {
|
|
|
|
| 2107 |
const fabricName = selectedOption.getAttribute('data-fabric-name') || 'N/A';
|
| 2108 |
const cutQuantity = selectedOption.getAttribute('data-cut-quantity') || '0';
|
| 2109 |
const fabricUsed = selectedOption.getAttribute('data-fabric-used') || 'N/A';
|
|
|
|
| 2110 |
|
|
|
|
| 2111 |
const fields = {
|
| 2112 |
'detail-fabric-name': fabricName,
|
| 2113 |
'detail-cut-quantity': cutQuantity,
|
| 2114 |
'detail-fabric-used': fabricUsed
|
|
|
|
| 2115 |
};
|
| 2116 |
for(const id in fields) {
|
| 2117 |
const element = document.getElementById(id);
|
| 2118 |
if(element) element.textContent = fields[id];
|
| 2119 |
}
|
| 2120 |
+
const costElem = document.getElementById('detail-material-cost'); if(costElem) costElem.textContent = '';
|
| 2121 |
+
const salaryElem = document.getElementById('detail-cutting-salary'); if(salaryElem) salaryElem.textContent = '';
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2122 |
|
| 2123 |
if(maxSewnSpan) maxSewnSpan.textContent = cutQuantity;
|
| 2124 |
+
if(sewnInput) sewnInput.max = cutQuantity;
|
| 2125 |
+
if (productNameInput && !productNameInput.value) productNameInput.value = fabricName;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2126 |
if(detailsDiv) detailsDiv.style.display = 'block';
|
| 2127 |
} else {
|
| 2128 |
if(detailsDiv) detailsDiv.style.display = 'none';
|
|
|
|
| 2132 |
}
|
| 2133 |
}
|
| 2134 |
|
|
|
|
| 2135 |
function addFittingRow() {
|
| 2136 |
const container = document.getElementById('fittings-rows');
|
| 2137 |
+
const firstRow = container.querySelector('.dynamic-fitting-row'); if (!firstRow) return;
|
|
|
|
| 2138 |
const newRow = firstRow.cloneNode(true);
|
| 2139 |
newRow.querySelectorAll('select, input').forEach(el => el.value = '');
|
| 2140 |
+
const availabilityDiv = newRow.querySelector('.fitting-availability'); if(availabilityDiv) availabilityDiv.textContent = '';
|
| 2141 |
+
const removeBtn = newRow.querySelector('.remove-fitting-row-btn'); if(removeBtn) removeBtn.style.display = 'inline-block';
|
|
|
|
|
|
|
| 2142 |
container.appendChild(newRow);
|
| 2143 |
attachFittingChangeEvent(newRow);
|
| 2144 |
}
|
| 2145 |
+
function removeFittingRow(button) { const row = button.closest('.dynamic-fitting-row'); if (row) row.remove(); }
|
|
|
|
|
|
|
|
|
|
| 2146 |
function handleFittingChange(selectElement) {
|
| 2147 |
+
const row = selectElement.closest('.dynamic-fitting-row'); if (!row) return;
|
| 2148 |
+
const availabilityDiv = row.querySelector('.fitting-availability'); if (!availabilityDiv) return;
|
|
|
|
|
|
|
| 2149 |
const selectedOption = selectElement.options[selectElement.selectedIndex];
|
| 2150 |
if (selectedOption && selectedOption.value) {
|
| 2151 |
const quantity = selectedOption.getAttribute('data-quantity') || '0';
|
| 2152 |
const unit = selectedOption.getAttribute('data-unit') || 'шт';
|
| 2153 |
+
availabilityDiv.textContent = `Доступно: ${quantity} ${unit}`;
|
|
|
|
|
|
|
| 2154 |
} else { availabilityDiv.textContent = ''; }
|
| 2155 |
}
|
| 2156 |
+
function attachFittingChangeEvent(rowElement) {
|
| 2157 |
+
const fittingSelect = rowElement.querySelector('.fitting-select');
|
| 2158 |
+
if(fittingSelect) { fittingSelect.removeEventListener('change', fittingChangeHandler); fittingSelect.addEventListener('change', fittingChangeHandler); }
|
| 2159 |
+
}
|
| 2160 |
+
function fittingChangeHandler() { handleFittingChange(this); }
|
|
|
|
|
|
|
|
|
|
| 2161 |
|
|
|
|
| 2162 |
function addDefectRow() {
|
| 2163 |
const container = document.getElementById('defect-rows');
|
| 2164 |
+
const firstRow = container.querySelector('.dynamic-defect-row'); if (!firstRow) return;
|
|
|
|
| 2165 |
const newRow = firstRow.cloneNode(true);
|
| 2166 |
newRow.querySelectorAll('select, input').forEach(el => el.value = '');
|
| 2167 |
+
const availabilityDiv = newRow.querySelector('.defect-availability'); if(availabilityDiv) availabilityDiv.textContent = '';
|
| 2168 |
+
const qtyInput = newRow.querySelector('.defect-quantity-input'); if(qtyInput){ qtyInput.inputMode = 'text'; qtyInput.placeholder = 'Количество'; qtyInput.step = 'any'; }
|
| 2169 |
+
const removeBtn = newRow.querySelector('.remove-defect-row-btn'); if(removeBtn) removeBtn.style.display = 'inline-block';
|
|
|
|
|
|
|
|
|
|
| 2170 |
container.appendChild(newRow);
|
| 2171 |
attachDefectChangeEvent(newRow);
|
| 2172 |
}
|
| 2173 |
+
function removeDefectRow(button) { const row = button.closest('.dynamic-defect-row'); if(row) row.remove(); }
|
|
|
|
|
|
|
|
|
|
| 2174 |
function handleDefectChange(selectElement) {
|
| 2175 |
+
const row = selectElement.closest('.dynamic-defect-row'); if (!row) return;
|
|
|
|
| 2176 |
const availabilityDiv = row.querySelector('.defect-availability');
|
| 2177 |
const quantityInput = row.querySelector('.defect-quantity-input');
|
| 2178 |
const selectedOption = selectElement.options[selectElement.selectedIndex];
|
| 2179 |
if (!availabilityDiv || !quantityInput) return;
|
|
|
|
| 2180 |
if (selectedOption && selectedOption.value) {
|
| 2181 |
const quantity = selectedOption.getAttribute('data-quantity') || '0';
|
| 2182 |
const unit = selectedOption.getAttribute('data-unit') || '?';
|
| 2183 |
const type = selectedOption.getAttribute('data-type') || '?';
|
| 2184 |
+
availabilityDiv.textContent = `Доступно: ${quantity} ${unit}`;
|
| 2185 |
+
if (type === 'fabric') { quantityInput.inputMode = 'decimal'; quantityInput.placeholder = 'e.g., 0,5'; quantityInput.step = '0.01'; }
|
| 2186 |
+
else { quantityInput.inputMode = 'numeric'; quantityInput.placeholder = 'Кол-во (шт)'; quantityInput.step = '1'; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2187 |
} else {
|
| 2188 |
availabilityDiv.textContent = '';
|
| 2189 |
quantityInput.inputMode = 'text'; quantityInput.placeholder = 'Количество'; quantityInput.step = 'any';
|
| 2190 |
}
|
| 2191 |
}
|
| 2192 |
+
function attachDefectChangeEvent(rowElement) {
|
| 2193 |
+
const defectSelect = rowElement.querySelector('.defect-material-select');
|
| 2194 |
+
if(defectSelect) { defectSelect.removeEventListener('change', defectChangeHandler); defectSelect.addEventListener('change', defectChangeHandler); }
|
| 2195 |
+
}
|
| 2196 |
+
function defectChangeHandler() { handleDefectChange(this); }
|
|
|
|
|
|
|
|
|
|
| 2197 |
|
|
|
|
| 2198 |
document.addEventListener('DOMContentLoaded', () => {
|
| 2199 |
showTaskDetails();
|
| 2200 |
+
document.querySelectorAll('.dynamic-fitting-row').forEach(row => { attachFittingChangeEvent(row); const fittingSelect = row.querySelector('.fitting-select'); if (fittingSelect && fittingSelect.value) handleFittingChange(fittingSelect); });
|
| 2201 |
+
document.querySelectorAll('.dynamic-defect-row').forEach(row => { attachDefectChangeEvent(row); const defectSelect = row.querySelector('.defect-material-select'); if (defectSelect && defectSelect.value) handleDefectChange(defectSelect); });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2202 |
});
|
| 2203 |
</script>
|
| 2204 |
"""
|
|
|
|
| 2254 |
# Скрипты ОТК (без изменений)
|
| 2255 |
QC_PACKING_SCRIPTS = """
|
| 2256 |
<script>
|
| 2257 |
+
let maxAllowedQuantity = 0;
|
| 2258 |
+
let totalSewnQuantity = 0;
|
| 2259 |
|
| 2260 |
function updateQcQuantities() {
|
| 2261 |
const select = document.getElementById('sewing_task_id');
|
|
|
|
| 2263 |
const packedInput = document.getElementById('quantity_packed');
|
| 2264 |
const defectiveInput = document.getElementById('quantity_defective');
|
| 2265 |
const totalInfo = document.getElementById('qc-total-info');
|
|
|
|
| 2266 |
if (selectedOption && selectedOption.value) {
|
| 2267 |
totalSewnQuantity = parseInt(selectedOption.getAttribute('data-sewn-quantity')) || 0;
|
| 2268 |
+
maxAllowedQuantity = parseInt(selectedOption.getAttribute('data-remaining-quantity')) || 0;
|
| 2269 |
+
if(packedInput) { packedInput.max = maxAllowedQuantity; packedInput.value = ''; }
|
| 2270 |
+
if(defectiveInput) { defectiveInput.max = maxAllowedQuantity; defectiveInput.value = '0'; }
|
| 2271 |
+
if(totalInfo) { totalInfo.textContent = `Всего сшито: ${totalSewnQuantity} ед. Осталось обработать: ${maxAllowedQuantity} ед. Сумма упак. и брака не должна превышать остаток.`; totalInfo.classList.remove('text-danger', 'text-success'); }
|
| 2272 |
+
validateQcSum();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2273 |
} else {
|
| 2274 |
+
maxAllowedQuantity = 0; totalSewnQuantity = 0;
|
|
|
|
| 2275 |
if(packedInput) { packedInput.max = ''; packedInput.value = ''; }
|
| 2276 |
if(defectiveInput) { defectiveInput.max = ''; defectiveInput.value = '0'; }
|
| 2277 |
if(totalInfo) totalInfo.textContent = 'Выберите задание на пошив.';
|
| 2278 |
totalInfo.classList.remove('text-danger', 'text-success');
|
| 2279 |
}
|
| 2280 |
}
|
|
|
|
| 2281 |
function validateQcSum() {
|
| 2282 |
const packedInput = document.getElementById('quantity_packed');
|
| 2283 |
const defectiveInput = document.getElementById('quantity_defective');
|
| 2284 |
const totalInfo = document.getElementById('qc-total-info');
|
| 2285 |
if (!packedInput || !defectiveInput || !totalInfo) return false;
|
|
|
|
|
|
|
| 2286 |
const select = document.getElementById('sewing_task_id');
|
| 2287 |
+
if (!select || !select.value) return false;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2288 |
const packed = parseInt(packedInput.value) || 0;
|
| 2289 |
const defective = parseInt(defectiveInput.value) || 0;
|
| 2290 |
const totalProcessed = packed + defective;
|
|
|
|
| 2291 |
totalInfo.classList.remove('text-danger', 'text-success');
|
| 2292 |
+
if (maxAllowedQuantity === 0 && totalProcessed > 0) { totalInfo.textContent = `Задание уже полностью обработано (${totalSewnQuantity} ед.). Нельзя добавить больше.`; totalInfo.classList.add('text-danger'); return false; }
|
| 2293 |
+
if (totalProcessed > maxAllowedQuantity) { totalInfo.textContent = `Ошибка: Сумма (${totalProcessed}) превышает ОСТАТОК (${maxAllowedQuantity})!`; totalInfo.classList.add('text-danger'); return false; }
|
| 2294 |
+
else if (totalProcessed === 0) { totalInfo.textContent = `Всего сшито: ${totalSewnQuantity} ед. Осталось обработать: ${maxAllowedQuantity} ед. Укажите кол-во упак. или брака.`; return false; }
|
| 2295 |
+
else { totalInfo.textContent = `Всего сшито: ${totalSewnQuantity} ед. Осталось обработать: ${maxAllowedQuantity} ед. Сумма (${totalProcessed}) корректна.`; totalInfo.classList.add('text-success'); return true; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2296 |
}
|
|
|
|
| 2297 |
function validateQcForm() {
|
| 2298 |
const select = document.getElementById('sewing_task_id');
|
| 2299 |
+
if (!select || !select.value) { alert('Пожалуйста, выберите задание на пошив.'); return false; }
|
| 2300 |
+
const isValidSum = validateQcSum();
|
| 2301 |
+
if (!isValidSum) { alert('Ошибка в количестве упакованных или бракованных изделий. Проверьте введенные значения и остаток по заданию.'); return false; }
|
| 2302 |
+
return true;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2303 |
}
|
|
|
|
| 2304 |
document.addEventListener('DOMContentLoaded', () => { updateQcQuantities(); });
|
| 2305 |
</script>
|
| 2306 |
"""
|
| 2307 |
|
| 2308 |
+
# Контент Базы Клиентов (исправлена ошибка итерации)
|
| 2309 |
CLIENTS_CONTENT = """
|
| 2310 |
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
| 2311 |
<h1 class="h2"><i class="fas fa-users me-2"></i>База клиентов</h1>
|
|
|
|
| 2366 |
<button type="button" class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#historyModal-{{ client.id }}" title="Посмотреть историю отправок">
|
| 2367 |
<i class="fas fa-history"></i> История
|
| 2368 |
</button>
|
|
|
|
| 2369 |
</td>
|
| 2370 |
</tr>
|
| 2371 |
{% else %}
|
|
|
|
| 2391 |
<div class="modal-body">
|
| 2392 |
{% if client.history %}
|
| 2393 |
<ul class="list-group list-group-flush">
|
| 2394 |
+
{# Исправлено: Используем reversed() #}
|
| 2395 |
+
{% for record in reversed(client.history) %} {# Сначала последние #}
|
| 2396 |
<li class="list-group-item">
|
| 2397 |
<strong>Дата:</strong> {{ record.timestamp_dt.strftime('%Y-%m-%d %H:%M') if record.timestamp_dt else record.timestamp[:16]|replace('T',' ') }} <br>
|
| 2398 |
<strong>ID отправки:</strong> <small>{{ record.shipment_id }}</small><br>
|
|
|
|
| 2422 |
# Скрипты Базы Клиентов (без изменений)
|
| 2423 |
CLIENTS_SCRIPTS = """
|
| 2424 |
<script>
|
|
|
|
| 2425 |
const searchInput = document.getElementById('client-search');
|
| 2426 |
const tableBody = document.getElementById('clients-table')?.querySelector('tbody');
|
|
|
|
| 2427 |
if (searchInput && tableBody) {
|
| 2428 |
searchInput.addEventListener('input', function() {
|
| 2429 |
const searchTerm = searchInput.value.toLowerCase().trim();
|
|
|
|
| 2431 |
let found = false;
|
| 2432 |
rows.forEach(row => {
|
| 2433 |
const searchData = row.dataset.search || '';
|
| 2434 |
+
if (searchData.includes(searchTerm)) { row.style.display = ''; found = true; }
|
| 2435 |
+
else { row.style.display = 'none'; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2436 |
});
|
|
|
|
| 2437 |
const noResultRow = tableBody.querySelector('.no-result-row');
|
| 2438 |
if (!found && searchTerm !== '') {
|
| 2439 |
if (!noResultRow) {
|
| 2440 |
+
const tr = document.createElement('tr'); tr.className = 'no-result-row';
|
|
|
|
| 2441 |
tr.innerHTML = `<td colspan="5" class="text-center text-muted">Клиенты не найдены по запросу "${searchTerm}".</td>`;
|
| 2442 |
tableBody.appendChild(tr);
|
| 2443 |
+
} else { noResultRow.querySelector('td').textContent = `Клиенты не найдены по запросу "${searchTerm}".`; }
|
| 2444 |
+
} else if (noResultRow) { noResultRow.remove(); }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2445 |
});
|
| 2446 |
}
|
| 2447 |
+
document.addEventListener('DOMContentLoaded', function() {});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2448 |
</script>
|
| 2449 |
"""
|
| 2450 |
|
|
|
|
| 2584 |
<div class="tab-pane fade" id="cutting-content" role="tabpanel">
|
| 2585 |
<div class="card"><div class="card-header"><i class="fas fa-cut"></i>Задания на раскрой</div><div class="card-body">
|
| 2586 |
<div class="table-responsive"><table class="table table-striped table-hover table-sm"><thead><tr>
|
| 2587 |
+
<th>ID</th><th>Ткань</th><th>Кол-во</th><th>Расход</th><th>Статус</th><th>Создано</th><th>Завершено</th>
|
| 2588 |
</tr></thead><tbody>
|
| 2589 |
{% for task in cutting_tasks|reverse %}
|
| 2590 |
<tr>
|
|
|
|
| 2592 |
<td>{{ task.fabric_name }}<small title="{{ task.fabric_id }}">({{ task.fabric_id[:6] }}...)</small></td>
|
| 2593 |
<td>{{ format_integer_py(task.cut_items_quantity) }}</td>
|
| 2594 |
<td>{{ format_currency_py(task.fabric_used) }} {{ task.fabric_unit }}</td>
|
|
|
|
|
|
|
| 2595 |
<td><span class="{{ getStatusClass(task.status) }}">{{ getStatusText(task.status) }}</span></td>
|
| 2596 |
<td>{{ task.timestamp_created[:16] | replace('T', ' ') if task.timestamp_created else 'N/A' }}</td>
|
| 2597 |
<td>{{ task.timestamp_completed[:16] | replace('T', ' ') if task.timestamp_completed else '-' }}</td>
|
| 2598 |
+
</tr>{% else %}<tr><td colspan="7" class="text-center text-muted">Нет заданий на раскрой.</td></tr>{% endfor %}
|
| 2599 |
</tbody></table></div></div></div>
|
| 2600 |
</div>
|
| 2601 |
<!-- Вкладка Пошив (БЕЗ ЗП/Стоимости) -->
|
| 2602 |
<div class="tab-pane fade" id="sewing-content" role="tabpanel">
|
| 2603 |
<div class="card"><div class="card-header"><i class="fas fa-tshirt"></i>Задания на пошив</div><div class="card-body">
|
| 2604 |
<div class="table-responsive"><table class="table table-striped table-hover table-sm"><thead><tr>
|
| 2605 |
+
<th>ID</th><th>Изделие</th><th>Сшито</th><th>Исп. фурн.</th><th>Брак пошива</th><th>Статус</th><th>Упак./Брак ОТК</th><th>Создано</th><th>Завершено</th><th>Раскрой ID</th>
|
| 2606 |
</tr></thead><tbody>
|
| 2607 |
{% for task in sewing_tasks|reverse %}
|
| 2608 |
<tr>
|
|
|
|
| 2617 |
</ul>
|
| 2618 |
{% else %}<span class="text-muted small">-</span>{% endif %}
|
| 2619 |
</td>
|
|
|
|
|
|
|
| 2620 |
<td>
|
| 2621 |
{% if task.defects_reported %}
|
| 2622 |
<ul class="list-unstyled mb-0 small text-danger">
|
|
|
|
| 2635 |
<td>{{ task.timestamp_created[:16] | replace('T', ' ') if task.timestamp_created else 'N/A' }}</td>
|
| 2636 |
<td>{{ task.timestamp_completed[:16] | replace('T', ' ') if task.timestamp_completed else '-' }}</td>
|
| 2637 |
<td title="{{ task.cutting_task_id }}"><small>{{ task.cutting_task_id[:8] }}...</small></td>
|
| 2638 |
+
</tr>{% else %}<tr><td colspan="10" class="text-center text-muted">Нет заданий на пошив.</td></tr>{% endfor %}
|
| 2639 |
</tbody></table></div></div></div>
|
| 2640 |
</div>
|
| 2641 |
<!-- Вкладка Упакованные (с себестоимостью и ценой) -->
|
|
|
|
| 3132 |
REPORTS_SCRIPTS = """
|
| 3133 |
<script>
|
| 3134 |
document.addEventListener('DOMContentLoaded', function () {
|
| 3135 |
+
flatpickr(".flatpickr-date", { dateFormat: "Y-m-d", locale: "ru" });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3136 |
const filterTypeSelect = document.getElementById('filter_type');
|
| 3137 |
const customStartDate = document.getElementById('custom-start-date');
|
| 3138 |
const customEndDate = document.getElementById('custom-end-date');
|
|
|
|
| 3142 |
|
| 3143 |
function toggleDateSelectors() {
|
| 3144 |
const selectedType = filterTypeSelect.value;
|
| 3145 |
+
customStartDate.style.display = 'none'; customEndDate.style.display = 'none';
|
| 3146 |
+
daySelector.style.display = 'none'; monthSelector.style.display = 'none'; yearSelector.style.display = 'none';
|
| 3147 |
+
if (selectedType === 'custom') { customStartDate.style.display = 'block'; customEndDate.style.display = 'block'; }
|
| 3148 |
+
else if (selectedType === 'day') { daySelector.style.display = 'block'; }
|
| 3149 |
+
else if (selectedType === 'month') { monthSelector.style.display = 'block'; }
|
| 3150 |
+
else if (selectedType === 'year') { yearSelector.style.display = 'block'; }
|
| 3151 |
+
if (selectedType !== 'custom') { document.getElementById('start_date').value = ''; document.getElementById('end_date').value = ''; }
|
| 3152 |
+
if (selectedType !== 'day') { const dp = document.getElementById('filter_date_day')._flatpickr; if(dp) dp.clear(); }
|
| 3153 |
+
if (selectedType !== 'month') { document.getElementById('filter_date_month').value = ''; }
|
| 3154 |
+
// if (selectedType !== 'year') { document.getElementById('filter_date_year').value = new Date().getFullYear(); } // Don't default year
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3155 |
}
|
| 3156 |
+
if (filterTypeSelect) { filterTypeSelect.addEventListener('change', toggleDateSelectors); toggleDateSelectors(); }
|
| 3157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3158 |
var triggerTabList = [].slice.call(document.querySelectorAll('#reportDetailsTabs button[data-bs-toggle="tab"]'));
|
| 3159 |
triggerTabList.forEach(function (triggerEl) {
|
| 3160 |
var tabInstance = bootstrap.Tab.getInstance(triggerEl) || new bootstrap.Tab(triggerEl);
|
| 3161 |
+
triggerEl.addEventListener('click', function (event) { event.preventDefault(); tabInstance.show(); window.history.replaceState(null, null, window.location.pathname + window.location.search + triggerEl.getAttribute('data-bs-target')); });
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3162 |
});
|
|
|
|
|
|
|
| 3163 |
const validReportHashes = ['#prod-summary-content', '#packed-items-content', '#defects-report-content', '#expenses-report-content'];
|
| 3164 |
+
let reportHash = window.location.hash; let reportTabActivated = false;
|
|
|
|
| 3165 |
if(reportHash && validReportHashes.includes(reportHash) ) {
|
| 3166 |
var reportTabEl = document.querySelector(`button[data-bs-target="${reportHash}"]`);
|
| 3167 |
+
if(reportTabEl) { var reportTabInstance = bootstrap.Tab.getInstance(reportTabEl) || new bootstrap.Tab(reportTabEl); reportTabInstance.show(); reportTabActivated = true; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3168 |
}
|
|
|
|
| 3169 |
if (!reportTabActivated) {
|
| 3170 |
var defaultReportTabEl = document.getElementById('prod-summary-tab');
|
| 3171 |
+
if (defaultReportTabEl) { var defaultReportTabInstance = bootstrap.Tab.getInstance(defaultReportTabEl) || new bootstrap.Tab(defaultReportTabEl); defaultReportTabInstance.show(); }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3172 |
}
|
|
|
|
| 3173 |
});
|
| 3174 |
</script>
|
| 3175 |
"""
|
| 3176 |
|
|
|
|
| 3177 |
# --- Конец HTML Шаблонов ---
|
| 3178 |
|
| 3179 |
# Добавляем утилиты в контекст Jinja
|
|
|
|
| 3194 |
|
| 3195 |
try:
|
| 3196 |
logging.info("Первоначальная загрузка данных...")
|
| 3197 |
+
load_data()
|
| 3198 |
+
load_client_data()
|
| 3199 |
logging.info("Данные успешно загружены/инициализированы.")
|
| 3200 |
except Exception as e:
|
| 3201 |
logging.critical(f"Не удалось загрузить базы данных при запуске: {e}", exc_info=True)
|
| 3202 |
|
| 3203 |
logging.info("Запуск Flask приложения на http://0.0.0.0:7860")
|
|
|
|
| 3204 |
app.run(debug=True, host='0.0.0.0', port=7860, use_reloader=False)
|
|
|
|
|
|
|
| 3205 |
|