Spaces:
Sleeping
Sleeping
File size: 63,864 Bytes
4291477 2a32f00 a390f1a e6e4cd6 7c6b9af 77fc327 8b919e0 b4fd17f ceac302 c688616 931fd0b ceac302 8b919e0 7f4e85f e405cec c4bb4cb e6e4cd6 ceac302 8240a5c 2cb2227 8240a5c a390f1a 2cb2227 8240a5c 2cb2227 ceac302 2cb2227 ceac302 8240a5c 2cb2227 8240a5c 63e6b9a 7c6b9af 500c24f 38eda2f 500c24f 7c6b9af 51849f1 38eda2f 7c6b9af 51849f1 38eda2f 7c6b9af 51849f1 38eda2f 7c6b9af 51849f1 38eda2f 8b919e0 63e6b9a ce448b5 500c24f 9af04fe ce448b5 51849f1 ce448b5 8b919e0 4291477 ceac302 4291477 e6e4cd6 7f4e85f e6e4cd6 51849f1 e6e4cd6 7f4e85f 7c6b9af 51849f1 c4bb4cb e6e4cd6 7f4e85f 77fc327 e6e4cd6 5256584 e6e4cd6 c3b4e1f 2a32f00 38eda2f 4291477 8240a5c 7f4e85f 8240a5c 63e6b9a c4bb4cb 2cb2227 98a25c5 51849f1 c4bb4cb 98a25c5 6c01b01 c4bb4cb 98a25c5 6c01b01 98a25c5 c4bb4cb 6c01b01 c4bb4cb 98a25c5 864df9b 98a25c5 4291477 98a25c5 c4bb4cb 38eda2f 98a25c5 38eda2f bd4b9f2 98a25c5 c4bb4cb bd4b9f2 397b649 98a25c5 bd4b9f2 98a25c5 bd4b9f2 98a25c5 c4bb4cb 38eda2f 98a25c5 38eda2f 98a25c5 38eda2f 98a25c5 38eda2f 98a25c5 38eda2f c4bb4cb c024b89 98a25c5 c4bb4cb 98a25c5 6c01b01 98a25c5 6c01b01 c4bb4cb 397b649 e0103ae 6c01b01 e0103ae c4bb4cb 397b649 e0103ae c4bb4cb 98a25c5 c4bb4cb 6c01b01 c024b89 51849f1 6c01b01 98a25c5 397b649 c4bb4cb c024b89 6c01b01 c4bb4cb 6c01b01 c024b89 6c01b01 c4bb4cb 98a25c5 c024b89 c4bb4cb 6c01b01 98a25c5 c024b89 98a25c5 c4bb4cb 98a25c5 6c01b01 51849f1 c4bb4cb 6c01b01 98a25c5 c4bb4cb 6c01b01 0318b2a 98a25c5 6c01b01 0318b2a 9ff8507 0318b2a 98a25c5 0318b2a 51849f1 daa7bba 0318b2a daa7bba 0318b2a 98a25c5 daa7bba 98a25c5 397b649 98a25c5 ceac302 daa7bba 98a25c5 51849f1 daa7bba 98a25c5 51849f1 98a25c5 daa7bba 0318b2a 98a25c5 99c03dd 0318b2a 51849f1 0318b2a 51849f1 98a25c5 51849f1 0318b2a 98a25c5 e0103ae 98a25c5 0318b2a c024b89 98a25c5 c024b89 a4eb49c 98a25c5 a4eb49c 98a25c5 a4eb49c 10d0a8a 98a25c5 10d0a8a 98a25c5 10d0a8a 4291477 8240a5c ceac302 c4bb4cb 98a25c5 4291477 8240a5c 4291477 98a25c5 2cb2227 38eda2f bd4b9f2 98a25c5 bd4b9f2 c4bb4cb ceac302 38eda2f 51849f1 daa7bba ceac302 daa7bba c4bb4cb 51849f1 6c01b01 4291477 2cb2227 4291477 6c01b01 4291477 6c01b01 4291477 daa7bba c4bb4cb 076b99d daa7bba 0318b2a daa7bba 0318b2a c024b89 a4eb49c c024b89 a4eb49c c024b89 a4eb49c 0318b2a 98a25c5 8240a5c 98a25c5 10d0a8a 51849f1 daa7bba 0318b2a 51849f1 daa7bba 0318b2a a4eb49c 8240a5c b6edd3c 0318b2a 98a25c5 77a445f daa7bba 51849f1 0318b2a 51849f1 daa7bba 51849f1 9eff9e1 98a25c5 daa7bba 51849f1 0318b2a 51849f1 397b649 99c03dd 0318b2a 98a25c5 99c03dd a4eb49c c024b89 a4eb49c e0103ae a4eb49c 98a25c5 c024b89 bb97035 98a25c5 bb97035 0318b2a a4eb49c c024b89 bb97035 0318b2a a4eb49c 0318b2a 98a25c5 c024b89 0318b2a bb97035 c024b89 98a25c5 0318b2a bb97035 0318b2a a4eb49c 0318b2a 98a25c5 0318b2a bb97035 98a25c5 2cb2227 98a25c5 ceac302 98a25c5 2cb2227 0318b2a 8240a5c ceac302 98a25c5 bb97035 8240a5c 0318b2a ceac302 10d0a8a 98a25c5 10d0a8a 2cb2227 10d0a8a 2cb2227 10d0a8a 8240a5c 77a445f c688616 10d0a8a a4eb49c daa7bba 98a25c5 daa7bba 0318b2a 98a25c5 38eda2f 98a25c5 38eda2f 98a25c5 bd4b9f2 38eda2f 98a25c5 bd4b9f2 38eda2f bd4b9f2 0318b2a daa7bba c4bb4cb ceac302 b6edd3c 9509b14 4051dff 38eda2f 4291477 8240a5c da6d436 4051dff da6d436 51849f1 4051dff 98a25c5 99c03dd daa7bba 0318b2a e0103ae 397b649 ceac302 98a25c5 397b649 0318b2a daa7bba 0318b2a 98a25c5 0318b2a daa7bba da6d436 99c03dd da6d436 38eda2f 4291477 2cb2227 4291477 51849f1 c024b89 daa7bba da6d436 ceac302 2cb2227 8240a5c 4291477 2cb2227 4291477 ceac302 4291477 ceac302 4291477 ceac302 4291477 8240a5c 2cb2227 4291477 63e4900 ceac302 4291477 ceac302 4291477 2cb2227 4291477 77a445f 4291477 ceac302 77a445f 4291477 63e4900 ceac302 4291477 ceac302 4291477 77a445f 4291477 77a445f ceac302 77a445f 4291477 63e4900 8240a5c 4291477 da6d436 2a32f00 38eda2f 2cb2227 38eda2f 2a32f00 9425d2e ceac302 38eda2f ceac302 38eda2f 98a25c5 38eda2f c4bb4cb 38eda2f 4051dff 24d83f7 4051dff ceac302 4051dff 4291477 4051dff da6d436 98a25c5 ceac302 500c24f ceac302 500c24f ceac302 500c24f 38eda2f c024b89 24d83f7 500c24f 38eda2f ceac302 c4bb4cb 38eda2f 4051dff 24d83f7 ceac302 4051dff 4291477 4051dff da6d436 98a25c5 4051dff ceac302 c4bb4cb ceac302 c4bb4cb 38eda2f 24d83f7 38eda2f c4bb4cb ceac302 c4bb4cb 38eda2f c4bb4cb 2cb2227 ceac302 2cb2227 ceac302 c4bb4cb 98a25c5 c4bb4cb 98a25c5 a9bbef6 864df9b 38eda2f 98a25c5 a9bbef6 c4bb4cb 98a25c5 c4bb4cb 98a25c5 c4bb4cb 38eda2f c4bb4cb 98a25c5 c4bb4cb 98a25c5 c4bb4cb 98a25c5 c4bb4cb 98a25c5 c4bb4cb 98a25c5 c4bb4cb 98a25c5 c4bb4cb 38eda2f 98a25c5 38eda2f 98a25c5 38eda2f 2cb2227 98a25c5 c4bb4cb 2cb2227 98a25c5 c4bb4cb 98a25c5 397b649 c024b89 864df9b c4bb4cb 98a25c5 864df9b 2cb2227 98a25c5 8240a5c 98a25c5 24d83f7 98a25c5 c024b89 98a25c5 c4bb4cb 98a25c5 38eda2f 98a25c5 38eda2f 98a25c5 51849f1 98a25c5 2cb2227 98a25c5 c024b89 98a25c5 24d83f7 98a25c5 8240a5c 98a25c5 24d83f7 98a25c5 c024b89 98a25c5 c4bb4cb 98a25c5 c4bb4cb 98a25c5 c4bb4cb 2cb2227 b6edd3c 2cb2227 c4bb4cb c024b89 c4bb4cb ceac302 2cb2227 c4bb4cb 98a25c5 c4bb4cb 98a25c5 c4bb4cb 98a25c5 0318b2a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 | from flask import Flask, render_template_string, request, redirect, url_for, session
import json
import os
import logging
import threading
import time
from datetime import datetime
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.secret_key = 'your_unique_secret_key_12345'
DATA_FILE = 'data_detobuv.json'
USERS_FILE = 'users_detobuv.json'
CONFIG_FILE = 'config.json'
SYNC_FILES = [DATA_FILE, USERS_FILE, CONFIG_FILE]
REPO_ID = "Kgshop/clients"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
WHOLESALE_ADDRESS = "Дордой, рынок Кербен, 9 ряд, 06 бутик"
RETAIL_ADDRESS = "Дордой Мир Обуви, номер 150"
CURRENCIES = {
'USD': 'Доллар США ($)',
'KGS': 'Кыргызский сом (с)'
}
logging.basicConfig(level=logging.DEBUG)
def load_config():
try:
with open(CONFIG_FILE, 'r', encoding='utf-8') as file:
config = json.load(file)
return config.get('kgs_to_usd', 89.0)
except (FileNotFoundError, json.JSONDecodeError):
return 89.0
def save_config(kgs_to_usd):
with open(CONFIG_FILE, 'w', encoding='utf-8') as file:
json.dump({'kgs_to_usd': kgs_to_usd}, file, ensure_ascii=False, indent=4)
def convert_price(price_usd, currency):
kgs_to_usd = load_config()
if currency == 'KGS':
return round(price_usd * kgs_to_usd, 2)
return round(price_usd, 2)
def load_data():
try:
download_db_from_hf()
with open(DATA_FILE, 'r', encoding='utf-8') as file:
data = json.load(file)
logging.info("Данные успешно загружены из JSON")
if not isinstance(data, dict) or 'products' not in data or 'categories' not in data:
return {'products': [], 'categories': [] if not isinstance(data, list) else data}
return data
except FileNotFoundError:
logging.warning("Локальный файл базы данных не найден после скачивания.")
return {'products': [], 'categories': []}
except json.JSONDecodeError:
logging.error("Ошибка: Невозможно декодировать JSON файл.")
return {'products': [], 'categories': []}
except RepositoryNotFoundError:
logging.error("Репозиторий не найден. Создание локальной базы данных.")
return {'products': [], 'categories': []}
except Exception as e:
logging.error(f"Произошла ошибка при загрузке данных: {e}")
return {'products': [], 'categories': []}
def save_data(data):
try:
with open(DATA_FILE, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
logging.info("Данные успешно сохранены в JSON")
upload_db_to_hf()
except Exception as e:
logging.error(f"Ошибка при сохранении данных: {e}")
raise
def load_users():
try:
with open(USERS_FILE, 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
return {}
except json.JSONDecodeError:
return {}
def save_users(users):
with open(USERS_FILE, 'w', encoding='utf-8') as file:
json.dump(users, file, ensure_ascii=False, indent=4)
upload_db_to_hf()
def upload_db_to_hf():
try:
api = HfApi()
for file_name in SYNC_FILES:
if os.path.exists(file_name):
api.upload_file(
path_or_fileobj=file_name,
path_in_repo=file_name,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Автоматическое резервное копирование файла {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
)
logging.info(f"Резервная копия {file_name} успешно загружена на Hugging Face.")
else:
logging.warning(f"Файл {file_name} не найден для загрузки.")
except Exception as e:
logging.error(f"Ошибка при загрузке резервной копии: {e}")
def download_db_from_hf():
try:
api = HfApi()
for file_name in SYNC_FILES:
hf_hub_download(
repo_id=REPO_ID,
filename=file_name,
repo_type="dataset",
token=HF_TOKEN_READ,
local_dir=".",
local_dir_use_symlinks=False
)
logging.info(f"Файл {file_name} успешно скачан из Hugging Face.")
except RepositoryNotFoundError as e:
logging.error(f"Репозиторий не найден: {e}")
raise
except Exception as e:
logging.error(f"Ошибка при скачивании файлов: {e}")
raise
def periodic_backup():
while True:
upload_db_to_hf()
time.sleep(800)
@app.route('/')
def catalog():
data = load_data()
products = data['products']
categories = data['categories']
is_authenticated = 'user' in session
selected_currency = session.get('currency', 'USD') if is_authenticated else 'USD'
kgs_to_usd = load_config()
catalog_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Детская обувь оптом и в розницу</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
background: linear-gradient(135deg, #f0f2f5, #e9ecef);
color: #2d3748;
line-height: 1.6;
transition: background 0.3s, color 0.3s;
}
body.dark-mode {
background: linear-gradient(135deg, #1a202c, #2d3748);
color: #e2e8f0;
}
.container {
max-width: 1300px;
margin: 0 auto;
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid #e2e8f0;
}
.header h1 {
font-size: 1.5rem;
font-weight: 600;
}
.auth-links {
display: flex;
gap: 15px;
}
.auth-links a {
color: #3b82f6;
text-decoration: none;
font-weight: 500;
}
.auth-links a:hover {
text-decoration: underline;
}
.theme-toggle {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #4a5568;
transition: color 0.3s ease;
}
.theme-toggle:hover {
color: #3b82f6;
}
.filters-container {
margin: 20px 0;
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
}
.search-container {
margin: 20px 0;
text-align: center;
}
#search-input {
width: 90%;
max-width: 600px;
padding: 12px 18px;
font-size: 1rem;
border: 1px solid #e2e8f0;
border-radius: 8px;
outline: none;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
transition: all 0.3s ease;
}
#search-input:focus {
border-color: #3b82f6;
box-shadow: 0 4px 15px rgba(59, 130, 246, 0.2);
}
.category-filter {
padding: 8px 16px;
border: 1px solid #e2e8f0;
border-radius: 8px;
background-color: #fff;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-size: 0.9rem;
font-weight: 400;
}
.category-filter.active, .category-filter:hover {
background-color: #3b82f6;
color: white;
border-color: #3b82f6;
box-shadow: 0 2px 10px rgba(59, 130, 246, 0.3);
}
.products-grid {
display: grid;
grid-template-columns: repeat(2, minmax(200px, 1fr));
gap: 15px;
padding: 10px;
}
.product {
background: #fff;
border-radius: 15px;
padding: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease;
overflow: hidden;
}
body.dark-mode .product {
background: #2d3748;
color: #fff;
}
.product:hover {
transform: translateY(-5px) scale(1.02);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}
.product-image {
width: 100%;
aspect-ratio: 1;
background-color: #fff;
border-radius: 10px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
}
.product-image img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transition: transform 0.3s ease;
}
.product-image img:hover {
transform: scale(1.1);
}
.product h2 {
font-size: 1rem;
font-weight: 600;
margin: 10px 0;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-price {
font-size: 1.1rem;
color: #ef4444;
font-weight: 700;
text-align: center;
margin: 5px 0;
}
.product-description {
font-size: 0.8rem;
color: #718096;
text-align: center;
margin-bottom: 15px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
body.dark-mode .product-description {
color: #a0aec0;
}
.product-button {
display: block;
width: 100%;
padding: 8px;
border: none;
border-radius: 8px;
background-color: #3b82f6;
color: white;
font-size: 0.8rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
margin: 5px 0;
text-align: center;
text-decoration: none;
}
.product-button:hover {
background-color: #2563eb;
box-shadow: 0 4px 15px rgba(37, 99, 235, 0.4);
transform: translateY(-2px);
}
.add-to-cart {
background-color: #10b981;
}
.add-to-cart:hover {
background-color: #059669;
box-shadow: 0 4px 15px rgba(5, 150, 105, 0.4);
}
#cart-button {
position: fixed;
bottom: 20px;
right: 20px;
background-color: #ef4444;
color: white;
border: none;
border-radius: 50%;
width: 50px;
height: 50px;
font-size: 1.2rem;
cursor: pointer;
display: none;
box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 1000;
}
.modal {
display: none;
position: fixed;
z-index: 1001;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
backdrop-filter: blur(5px);
}
.modal-content {
background: #fff;
margin: 5% auto;
padding: 20px;
border-radius: 15px;
width: 90%;
max-width: 700px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
animation: slideIn 0.3s ease-out;
overflow-y: auto;
max-height: 80vh;
}
body.dark-mode .modal-content {
background: #2d3748;
color: #e2e8f0;
}
@keyframes slideIn {
from { transform: translateY(-50px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.close {
float: right;
font-size: 1.5rem;
color: #718096;
cursor: pointer;
transition: color 0.3s;
}
.close:hover {
color: #2d3748;
}
body.dark-mode .close {
color: #a0aec0;
}
body.dark-mode .close:hover {
color: #fff;
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid #e2e8f0;
}
body.dark-mode .cart-item {
border-bottom: 1px solid #4a5568;
}
.cart-item img {
width: 50px;
height: 50px;
object-fit: contain;
border-radius: 8px;
margin-right: 15px;
}
.quantity-input, .color-select {
width: 100%;
max-width: 150px;
padding: 8px;
border: 1px solid #e2e8f0;
border-radius: 8px;
font-size: 1rem;
margin: 5px 0;
}
.clear-cart {
background-color: #ef4444;
}
.clear-cart:hover {
background-color: #dc2626;
box-shadow: 0 4px 15px rgba(220, 38, 38, 0.4);
}
.order-button {
background-color: #10b981;
}
.order-button:hover {
background-color: #059669;
box-shadow: 0 4px 15px rgba(5, 150, 105, 0.4);
}
.store-address {
padding: 10px;
text-align: center;
font-style: italic;
color: #666;
}
.currency-select {
padding: 8px;
border-radius: 8px;
border: 1px solid #e2e8f0;
font-size: 1rem;
}
.remove-item-button {
background: none;
border: none;
color: #ef4444;
cursor: pointer;
font-size: 1rem;
margin-left: 10px;
}
.remove-item-button:hover {
color: #dc2626;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Каталог</h1>
<div class="auth-links">
{% if is_authenticated %}
<span>Добро пожаловать, {{ session['user'] }}!</span>
<form method="POST" action="{{ url_for('set_currency') }}" style="display: inline;">
<select name="currency" class="currency-select" onchange="this.form.submit()">
{% for code, name in currencies.items() %}
<option value="{{ code }}" {% if code == selected_currency %}selected{% endif %}>{{ name }}</option>
{% endfor %}
</select>
</form>
<a href="{{ url_for('logout') }}">Выйти</a>
{% else %}
<a href="{{ url_for('login') }}">Войти</a>
<a href="{{ url_for('register') }}">Регистрация</a>
{% endif %}
</div>
<button class="theme-toggle" onclick="toggleTheme()">
<i class="fas fa-moon"></i>
</button>
</div>
<div class="store-address">Опт: {{ wholesale_address }} | Розница: {{ retail_address }}</div>
<div class="filters-container">
<button class="category-filter active" data-category="all">Все категории</button>
{% for category in categories %}
<button class="category-filter" data-category="{{ category }}">{{ category }}</button>
{% endfor %}
</div>
<div class="search-container">
<input type="text" id="search-input" placeholder="Поиск товаров...">
</div>
<div class="products-grid" id="products-grid">
{% for product in products %}
<div class="product"
data-name="{{ product['name']|lower }}"
data-description="{{ product['description']|lower }}"
data-category="{{ product.get('category', 'Без категории') }}">
{% if product.get('photos') and product['photos']|length > 0 %}
<div class="product-image">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
alt="{{ product['name'] }}"
loading="lazy">
</div>
{% endif %}
<h2>{{ product['name'] }}</h2>
{% if is_authenticated %}
<div class="product-price">{{ convert_price(product['price'], selected_currency) }} {{ selected_currency }}</div>
{% else %}
<div class="product-price">Цена доступна после входа</div>
{% endif %}
<p class="product-description">{{ product['description'][:50] }}{% if product['description']|length > 50 %}...{% endif %}</p>
<button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button>
{% if is_authenticated %}
<button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})">В корзину</button>
{% endif %}
</div>
{% endfor %}
</div>
</div>
<!-- Product Modal -->
<div id="productModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('productModal')">×</span>
<div id="modalContent"></div>
</div>
</div>
<!-- Quantity and Color Modal -->
<div id="quantityModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('quantityModal')">×</span>
<h2>Укажите количество и цвет</h2>
<input type="number" id="quantityInput" class="quantity-input" min="1" value="1">
<select id="colorSelect" class="color-select"></select>
<button class="product-button" onclick="confirmAddToCart()">Добавить</button>
</div>
</div>
<!-- Cart Modal -->
<div id="cartModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('cartModal')">×</span>
<h2>Корзина</h2>
<div id="cartContent"></div>
<div style="margin-top: 20px; text-align: right;">
<strong>Итого: <span id="cartTotal">0</span> {{ selected_currency }}</strong>
<button class="product-button clear-cart" onclick="clearCart()">Очистить</button>
<button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать</button>
</div>
</div>
</div>
<button id="cart-button" onclick="openCartModal()">🛒</button>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
<script>
const products = {{ products|tojson }};
let selectedProductIndex = null;
const selectedCurrency = '{{ selected_currency }}';
const kgsToUsd = {{ kgs_to_usd|tojson }};
function toggleTheme() {
document.body.classList.toggle('dark-mode');
const icon = document.querySelector('.theme-toggle i');
icon.classList.toggle('fa-moon');
icon.classList.toggle('fa-sun');
localStorage.setItem('theme', document.body.classList.contains('dark-mode') ? 'dark' : 'light');
}
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
document.querySelector('.theme-toggle i').classList.replace('fa-moon', 'fa-sun');
}
// Автоматическая авторизация из localStorage
const storedUser = localStorage.getItem('user');
if (storedUser && !{{ is_authenticated|tojson }}) {
fetch('/auto_login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ login: storedUser })
}).then(response => {
if (response.ok) window.location.reload();
});
}
function openModal(index) {
loadProductDetails(index);
document.getElementById('productModal').style.display = "block";
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = "none";
}
function loadProductDetails(index) {
fetch('/product/' + index)
.then(response => response.text())
.then(data => {
document.getElementById('modalContent').innerHTML = data;
initializeSwiper();
})
.catch(error => console.error('Ошибка:', error));
}
function initializeSwiper() {
new Swiper('.swiper-container', {
slidesPerView: 1,
spaceBetween: 20,
loop: true,
grabCursor: true,
pagination: { el: '.swiper-pagination', clickable: true },
navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
zoom: { maxRatio: 3 }
});
}
function openQuantityModal(index) {
selectedProductIndex = index;
const product = products[index];
const colorSelect = document.getElementById('colorSelect');
colorSelect.innerHTML = '';
if (product.colors && product.colors.length > 0) {
product.colors.forEach(color => {
const option = document.createElement('option');
option.value = color;
option.text = color;
colorSelect.appendChild(option);
});
} else {
const option = document.createElement('option');
option.value = 'Нет цвета';
option.text = 'Нет цвета';
colorSelect.appendChild(option);
}
document.getElementById('quantityModal').style.display = 'block';
document.getElementById('quantityInput').value = 1;
}
function confirmAddToCart() {
if (selectedProductIndex === null) return;
const quantity = parseInt(document.getElementById('quantityInput').value) || 1;
const color = document.getElementById('colorSelect').value;
if (quantity <= 0) {
alert("Укажите количество больше 0");
return;
}
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
const product = products[selectedProductIndex];
const cartItemId = `${product.name}-${color}`;
const existingItem = cart.find(item => item.id === cartItemId);
if (existingItem) {
existingItem.quantity += quantity;
} else {
cart.push({
id: cartItemId,
name: product.name,
price: product.price,
photo: product.photos && product.photos.length > 0 ? product.photos[0] : '',
quantity: quantity,
color: color
});
}
localStorage.setItem('cart', JSON.stringify(cart));
closeModal('quantityModal');
updateCartButton();
}
function updateCartButton() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
document.getElementById('cart-button').style.display = cart.length > 0 ? 'block' : 'none';
}
function openCartModal() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
const cartContent = document.getElementById('cartContent');
let total = 0;
cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => {
const itemPrice = selectedCurrency === 'KGS' ? (item.price * kgsToUsd) : item.price;
const itemTotal = itemPrice * item.quantity;
total += itemTotal;
return `
<div class="cart-item" data-item-id="${item.id}">
<div style="display: flex; align-items: center;">
${item.photo ? `<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" alt="${item.name}">` : ''}
<div>
<strong>${item.name}</strong>
<p>${itemPrice.toFixed(2)} ${selectedCurrency} × ${item.quantity} (Цвет: ${item.color})</p>
</div>
</div>
<span>${itemTotal.toFixed(2)} ${selectedCurrency}</span>
<button class="remove-item-button" onclick="removeItemFromCart('${item.id}')">×</button>
</div>
`;
}).join('');
document.getElementById('cartTotal').textContent = total.toFixed(2);
document.getElementById('cartModal').style.display = 'block';
}
function removeItemFromCart(itemId) {
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
cart = cart.filter(item => item.id !== itemId);
localStorage.setItem('cart', JSON.stringify(cart));
openCartModal();
updateCartButton();
}
function orderViaWhatsApp() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
if (cart.length === 0) {
alert("Корзина пуста!");
return;
}
let total = 0;
let orderText = "Заказ:%0A";
cart.forEach((item, index) => {
const itemPrice = selectedCurrency === 'KGS' ? (item.price * kgsToUsd) : item.price;
const itemTotal = itemPrice * item.quantity;
total += itemTotal;
orderText += `${index + 1}. ${item.name} - ${itemPrice.toFixed(2)} ${selectedCurrency} × ${item.quantity} (Цвет: ${item.color})%0A`;
});
orderText += `Итого: ${total.toFixed(2)} ${selectedCurrency}%0A`;
orderText += `Страна: {{ session.get('country', 'Не указана') }}%0A`;
orderText += `Город: {{ session.get('city', 'Не указан') }}`;
window.open(`https://api.whatsapp.com/send?phone=996555360556&text=${orderText}`, '_blank');
}
function clearCart() {
localStorage.removeItem('cart');
closeModal('cartModal');
updateCartButton();
}
window.onclick = function(event) {
if (event.target.className === 'modal') event.target.style.display = "none";
}
document.getElementById('search-input').addEventListener('input', filterProducts);
document.querySelectorAll('.category-filter').forEach(filter => {
filter.addEventListener('click', function() {
document.querySelectorAll('.category-filter').forEach(f => f.classList.remove('active'));
this.classList.add('active');
filterProducts();
});
});
function filterProducts() {
const searchTerm = document.getElementById('search-input').value.toLowerCase();
const activeCategory = document.querySelector('.category-filter.active').dataset.category;
document.querySelectorAll('.product').forEach(product => {
const name = product.getAttribute('data-name');
const description = product.getAttribute('data-description');
const category = product.getAttribute('data-category');
const matchesSearch = name.includes(searchTerm) || description.includes(searchTerm);
const matchesCategory = activeCategory === 'all' || category === activeCategory;
product.style.display = matchesSearch && matchesCategory ? 'block' : 'none';
});
}
updateCartButton();
</script>
</body>
</html>
'''
return render_template_string(catalog_html, products=products, categories=categories,
repo_id=REPO_ID, is_authenticated=is_authenticated,
wholesale_address=WHOLESALE_ADDRESS, retail_address=RETAIL_ADDRESS,
session=session, convert_price=convert_price,
selected_currency=selected_currency, currencies=CURRENCIES,
kgs_to_usd=kgs_to_usd)
@app.route('/product/<int:index>')
def product_detail(index):
data = load_data()
products = data['products']
is_authenticated = 'user' in session
selected_currency = session.get('currency', 'USD') if is_authenticated else 'USD'
try:
product = products[index]
except IndexError:
return "Продукт не найден", 404
detail_html = '''
<div class="container" style="padding: 20px;">
<h2 style="font-size: 1.8rem; font-weight: 600; margin-bottom: 20px;">{{ product['name'] }}</h2>
<div class="swiper-container" style="max-width: 400px; margin: 0 auto 20px;">
<div class="swiper-wrapper">
{% if product.get('photos') %}
{% for photo in product['photos'] %}
<div class="swiper-slide" style="background-color: #fff; display: flex; justify-content: center; align-items: center;">
<div class="swiper-zoom-container">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
alt="{{ product['name'] }}"
style="max-width: 100%; max-height: 300px; object-fit: contain;">
</div>
</div>
{% endfor %}
{% else %}
<div class="swiper-slide">
<img src="https://via.placeholder.com/300" alt="No Image">
</div>
{% endif %}
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
{% if is_authenticated %}
<p><strong>Цена:</strong> {{ convert_price(product['price'], selected_currency) }} {{ selected_currency }}</p>
{% else %}
<p><strong>Цена:</strong> Доступна после входа</p>
{% endif %}
<p><strong>Описание:</strong> {{ product['description'] }}</p>
<p><strong>Доступные цвета:</strong> {{ product.get('colors', ['Нет цветов'])|join(', ') }}</p>
</div>
'''
return render_template_string(detail_html, product=product, repo_id=REPO_ID,
is_authenticated=is_authenticated, convert_price=convert_price,
selected_currency=selected_currency)
@app.route('/set_currency', methods=['POST'])
def set_currency():
if 'user' in session:
currency = request.form.get('currency')
if currency in CURRENCIES:
session['currency'] = currency
return redirect(url_for('catalog'))
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
login = request.form.get('login')
password = request.form.get('password')
first_name = request.form.get('first_name')
last_name = request.form.get('last_name')
country = request.form.get('country')
city = request.form.get('city')
purchase_type = request.form.get('purchase_type')
if purchase_type == 'retail':
return render_template_string('''
<h2>Мы продаем только оптом</h2>
<p><a href="{{ url_for('register') }}">Назад к регистрации</a></p>
''')
users = load_users()
if login in users:
return "Пользователь с таким логином уже существует", 400
users[login] = {
'password': password,
'first_name': first_name,
'last_name': last_name,
'country': country,
'city': city,
'purchase_type': purchase_type
}
save_users(users)
session['user'] = login
session['country'] = country
session['city'] = city
session['currency'] = 'USD'
return redirect(url_for('catalog'))
return render_template_string('''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Регистрация</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Poppins', sans-serif;
background: linear-gradient(135deg, #f0f2f5, #e9ecef);
padding: 20px;
}
.container {
max-width: 500px;
margin: 0 auto;
background: #fff;
padding: 20px;
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
h2 {
text-align: center;
margin-bottom: 20px;
}
label {
display: block;
margin: 10px 0 5px;
}
input, select {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #e2e8f0;
border-radius: 8px;
}
button {
width: 100%;
padding: 10px;
background-color: #3b82f6;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
}
button:hover {
background-color: #2563eb;
}
</style>
</head>
<body>
<div class="container">
<h2>Регистрация</h2>
<form method="POST">
<label>Логин:</label>
<input type="text" name="login" required>
<label>Пароль:</label>
<input type="password" name="password" required>
<label>Имя:</label>
<input type="text" name="first_name" required>
<label>Фамилия:</label>
<input type="text" name="last_name" required>
<label>Страна:</label>
<input type="text" name="country" required>
<label>Город:</label>
<input type="text" name="city" required>
<label>Тип покупки:</label>
<select name="purchase_type" required>
<option value="wholesale">Оптом</option>
<option value="retail">В розницу</option>
</select>
<button type="submit">Зарегистрироваться</button>
</form>
<p style="text-align: center; margin-top: 15px;">
<a href="{{ url_for('login') }}">Уже есть аккаунт? Войти</a>
</p>
</div>
<script>
document.querySelector('form').addEventListener('submit', function() {
const login = document.querySelector('input[name="login"]').value;
localStorage.setItem('user', login);
});
</script>
</body>
</html>
''')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
login = request.form.get('login')
password = request.form.get('password')
users = load_users()
if login in users and users[login]['password'] == password:
session['user'] = login
session['country'] = users[login]['country']
session['city'] = users[login]['city']
session['currency'] = 'USD'
return redirect(url_for('catalog'))
return "Неверный логин или пароль", 401
return render_template_string('''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Вход</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Poppins', sans-serif;
background: linear-gradient(135deg, #f0f2f5, #e9ecef);
padding: 20px;
}
.container {
max-width: 500px;
margin: 0 auto;
background: #fff;
padding: 20px;
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
h2 {
text-align: center;
margin-bottom: 20px;
}
label {
display: block;
margin: 10px 0 5px;
}
input {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #e2e8f0;
border-radius: 8px;
}
button {
width: 100%;
padding: 10px;
background-color: #3b82f6;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
}
button:hover {
background-color: #2563eb;
}
</style>
</head>
<body>
<div class="container">
<h2>Вход</h2>
<form method="POST">
<label>Логин:</label>
<input type="text" name="login" required>
<label>Пароль:</label>
<input type="password" name="password" required>
<button type="submit">Войти</button>
</form>
<p style="text-align: center; margin-top: 15px;">
<a href="{{ url_for('register') }}">Нет аккаунта? Зарегистрироваться</a>
</p>
</div>
<script>
document.querySelector('form').addEventListener('submit', function() {
const login = document.querySelector('input[name="login"]').value;
localStorage.setItem('user', login);
});
</script>
</body>
</html>
''')
@app.route('/auto_login', methods=['POST'])
def auto_login():
data = request.get_json()
login = data.get('login')
users = load_users()
if login in users:
session['user'] = login
session['country'] = users[login]['country']
session['city'] = users[login]['city']
session['currency'] = 'USD'
return "OK", 200
return "Ошибка авторизации", 401
@app.route('/logout')
def logout():
session.pop('user', None)
session.pop('country', None)
session.pop('city', None)
session.pop('currency', None)
return redirect(url_for('catalog'))
@app.route('/admin', methods=['GET', 'POST'])
def admin():
data = load_data()
products = data['products']
categories = data['categories']
users = load_users()
kgs_to_usd = load_config()
if request.method == 'POST':
action = request.form.get('action')
if action == 'add_category':
category_name = request.form.get('category_name')
if category_name and category_name not in categories:
categories.append(category_name)
save_data(data)
return redirect(url_for('admin'))
return "Ошибка: Категория уже существует или не указано название", 400
elif action == 'delete_category':
category_index = int(request.form.get('category_index'))
deleted_category = categories.pop(category_index)
for product in products:
if product.get('category') == deleted_category:
product['category'] = 'Без категории'
save_data(data)
return redirect(url_for('admin'))
elif action == 'add':
name = request.form.get('name')
price = request.form.get('price')
description = request.form.get('description')
category = request.form.get('category')
photos_files = request.files.getlist('photos')
colors = request.form.getlist('colors')
photos_list = []
if photos_files:
for photo in photos_files[:10]:
if photo and photo.filename:
photo_filename = secure_filename(photo.filename)
uploads_dir = 'uploads'
os.makedirs(uploads_dir, exist_ok=True)
temp_path = os.path.join(uploads_dir, photo_filename)
photo.save(temp_path)
api = HfApi()
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=f"photos/{photo_filename}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Добавлено фото для товара {name}"
)
photos_list.append(photo_filename)
if os.path.exists(temp_path):
os.remove(temp_path)
if not name or not price or not description:
return "Ошибка: Заполните все обязательные поля", 400
price = float(price.replace(',', '.'))
new_product = {
'name': name,
'price': price,
'description': description,
'category': category if category in categories else 'Без категории',
'photos': photos_list,
'colors': colors if colors else []
}
products.append(new_product)
save_data(data)
return redirect(url_for('admin'))
elif action == 'edit':
index = int(request.form.get('index'))
name = request.form.get('name')
price = request.form.get('price')
description = request.form.get('description')
category = request.form.get('category')
photos_files = request.files.getlist('photos')
colors = request.form.getlist('colors')
if photos_files and any(photo.filename for photo in photos_files):
new_photos_list = []
for photo in photos_files[:10]:
if photo and photo.filename:
photo_filename = secure_filename(photo.filename)
uploads_dir = 'uploads'
os.makedirs(uploads_dir, exist_ok=True)
temp_path = os.path.join(uploads_dir, photo_filename)
photo.save(temp_path)
api = HfApi()
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=f"photos/{photo_filename}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Обновлено фото для товара {name}"
)
new_photos_list.append(photo_filename)
if os.path.exists(temp_path):
os.remove(temp_path)
products[index]['photos'] = new_photos_list
products[index]['name'] = name
products[index]['price'] = float(price.replace(',', '.'))
products[index]['description'] = description
products[index]['category'] = category if category in categories else 'Без категории'
products[index]['colors'] = colors if colors else []
save_data(data)
return redirect(url_for('admin'))
elif action == 'delete':
index = int(request.form.get('index'))
del products[index]
save_data(data)
return redirect(url_for('admin'))
elif action == 'set_exchange_rate':
kgs_to_usd = float(request.form.get('kgs_to_usd').replace(',', '.'))
save_config(kgs_to_usd)
upload_db_to_hf()
return redirect(url_for('admin'))
elif action == 'delete_user':
login = request.form.get('login')
if login in users:
del users[login]
save_users(users)
return redirect(url_for('admin'))
admin_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Админ-панель</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Poppins', sans-serif;
background: linear-gradient(135deg, #f0f2f5, #e9ecef);
color: #2d3748;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
padding: 15px 0;
border-bottom: 1px solid #e2e8f0;
}
h1, h2 {
font-weight: 600;
margin-bottom: 20px;
}
form {
background: #fff;
padding: 20px;
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
label {
font-weight: 500;
margin-top: 15px;
display: block;
}
input, textarea, select {
width: 100%;
padding: 12px;
margin-top: 5px;
border: 1px solid #e2e8f0;
border-radius: 8px;
font-size: 1rem;
transition: all 0.3s ease;
}
input:focus, textarea:focus, select:focus {
border-color: #3b82f6;
box-shadow: 0 0 5px rgba(59, 130, 246, 0.3);
outline: none;
}
button {
padding: 12px 20px;
border: none;
border-radius: 8px;
background-color: #3b82f6;
color: white;
font-weight: 500;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
margin-top: 15px;
}
button:hover {
background-color: #2563eb;
box-shadow: 0 4px 15px rgba(37, 99, 235, 0.4);
transform: translateY(-2px);
}
.delete-button {
background-color: #ef4444;
}
.delete-button:hover {
background-color: #dc2626;
box-shadow: 0 4px 15px rgba(220, 38, 38, 0.4);
}
.product-list, .category-list, .user-list {
display: grid;
gap: 20px;
}
.product-item, .category-item, .user-item {
background: #fff;
padding: 20px;
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
.edit-form {
margin-top: 15px;
padding: 15px;
background: #f7fafc;
border-radius: 10px;
}
.color-input-group {
display: flex;
gap: 10px;
margin-top: 5px;
}
.add-color-btn {
background-color: #10b981;
}
.add-color-btn:hover {
background-color: #059669;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Админ-панель</h1>
</div>
<h1>Установка курса KGS к USD</h1>
<form method="POST">
<input type="hidden" name="action" value="set_exchange_rate">
<label>Курс KGS к USD (1 USD = ? KGS):</label>
<input type="number" name="kgs_to_usd" step="0.01" value="{{ kgs_to_usd }}" required>
<button type="submit">Сохранить</button>
</form>
<h1>Добавление товара</h1>
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="add">
<label>Название товара:</label>
<input type="text" name="name" required>
<label>Цена (USD):</label>
<input type="number" name="price" step="0.01" required>
<label>Описание:</label>
<textarea name="description" rows="4" required></textarea>
<label>Категория:</label>
<select name="category">
<option value="Без категории">Без категории</option>
{% for category in categories %}
<option value="{{ category }}">{{ category }}</option>
{% endfor %}
</select>
<label>Фотографии (до 10):</label>
<input type="file" name="photos" accept="image/*" multiple>
<label>Цвета:</label>
<div id="color-inputs">
<div class="color-input-group">
<input type="text" name="colors" placeholder="Например: Красный">
</div>
</div>
<button type="button" class="add-color-btn" onclick="addColorInput()">Добавить цвет</button>
<button type="submit">Добавить товар</button>
</form>
<h1>Управление категориями</h1>
<form method="POST">
<input type="hidden" name="action" value="add_category">
<label>Название категории:</label>
<input type="text" name="category_name" required>
<button type="submit">Добавить</button>
</form>
<h2>Список категорий</h2>
<div class="category-list">
{% for category in categories %}
<div class="category-item">
<h3>{{ category }}</h3>
<form method="POST" style="display: inline;">
<input type="hidden" name="action" value="delete_category">
<input type="hidden" name="category_index" value="{{ loop.index0 }}">
<button type="submit" class="delete-button">Удалить</button>
</form>
</div>
{% endfor %}
</div>
<h2>Управление базой данных</h2>
<form method="POST" action="{{ url_for('backup') }}" style="display: inline;">
<button type="submit">Создать копию</button>
</form>
<form method="GET" action="{{ url_for('download') }}" style="display: inline;">
<button type="submit">Скачать базу</button>
</form>
<h2>Список товаров</h2>
<div class="product-list">
{% for product in products %}
<div class="product-item">
<h3>{{ product['name'] }}</h3>
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
<p><strong>Цена:</strong> {{ product['price'] }} USD ({{ convert_price(product['price'], 'KGS') }} KGS)</p>
<p><strong>Описание:</strong> {{ product['description'] }}</p>
<p><strong>Цвета:</strong> {{ product.get('colors', ['Нет цветов'])|join(', ') }}</p>
{% if product.get('photos') and product['photos']|length > 0 %}
<div style="display: flex; flex-wrap: wrap; gap: 10px;">
{% for photo in product['photos'] %}
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
alt="{{ product['name'] }}"
style="max-width: 100px; border-radius: 10px;">
{% endfor %}
</div>
{% endif %}
<details>
<summary>Редактировать</summary>
<form method="POST" enctype="multipart/form-data" class="edit-form">
<input type="hidden" name="action" value="edit">
<input type="hidden" name="index" value="{{ loop.index0 }}">
<label>Название:</label>
<input type="text" name="name" value="{{ product['name'] }}" required>
<label>Цена (USD):</label>
<input type="number" name="price" step="0.01" value="{{ product['price'] }}" required>
<label>Описание:</label>
<textarea name="description" rows="4" required>{{ product['description'] }}</textarea>
<label>Категория:</label>
<select name="category">
<option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option>
{% for category in categories %}
<option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option>
{% endfor %}
</select>
<label>Фотографии (до 10):</label>
<input type="file" name="photos" accept="image/*" multiple>
<label>Цвета:</label>
<div id="edit-color-inputs-{{ loop.index0 }}">
{% for color in product.get('colors', []) %}
<div class="color-input-group">
<input type="text" name="colors" value="{{ color }}">
</div>
{% endfor %}
</div>
<button type="button" class="add-color-btn" onclick="addColorInput('edit-color-inputs-{{ loop.index0 }}')">Добавить цвет</button>
<button type="submit">Сохранить</button>
</form>
</details>
<form method="POST">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="index" value="{{ loop.index0 }}">
<button type="submit" class="delete-button">Удалить</button>
</form>
</div>
{% endfor %}
</div>
<h2>Список пользователей</h2>
<div class="user-list">
{% for login, user in users.items() %}
<div class="user-item">
<p><strong>Логин:</strong> {{ login }}</p>
<p><strong>Имя:</strong> {{ user['first_name'] }}</p>
<p><strong>Фамилия:</strong> {{ user['last_name'] }}</p>
<p><strong>Страна:</strong> {{ user['country'] }}</p>
<p><strong>Город:</strong> {{ user['city'] }}</p>
<form method="POST">
<input type="hidden" name="action" value="delete_user">
<input type="hidden" name="login" value="{{ login }}">
<button type="submit" class="delete-button">Удалить</button>
</form>
</div>
{% endfor %}
</div>
</div>
<script>
function addColorInput(containerId = 'color-inputs') {
const container = document.getElementById(containerId);
const newInput = document.createElement('div');
newInput.className = 'color-input-group';
newInput.innerHTML = '<input type="text" name="colors" placeholder="Например: Красный">';
container.appendChild(newInput);
}
</script>
</body>
</html>
'''
return render_template_string(admin_html, products=products, categories=categories,
repo_id=REPO_ID, users=users, kgs_to_usd=kgs_to_usd,
convert_price=convert_price)
@app.route('/backup', methods=['POST'])
def backup():
upload_db_to_hf()
return "Резервная копия создана.", 200
@app.route('/download', methods=['GET'])
def download():
download_db_from_hf()
return "База данных скачана.", 200
if __name__ == '__main__':
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
backup_thread.start()
try:
load_data()
except Exception as e:
logging.error(f"Не удалось загрузить базу данных: {e}")
app.run(debug=True, host='0.0.0.0', port=7860) |