-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlager_mc.py
More file actions
8269 lines (7238 loc) · 299 KB
/
lager_mc.py
File metadata and controls
8269 lines (7238 loc) · 299 KB
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
#!/usr/bin/env python3
import curses
import csv
import datetime
import base64
import binascii
import html
import json
import os
import psycopg2
import psycopg2.extras
import locale
import re
import ssl
import subprocess
import string
import shutil
import tempfile
import textwrap
import time
from pathlib import Path
from urllib.parse import urlparse
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from address_label import build_address_label_pdf
from app_logging import MAIN_LOG_PATH, PRINT_LOG_PATH, get_logger
from app_settings import DEFAULT_SETTINGS, load_settings, save_settings
from app_version import APP_VERSION
from delivery_note import build_delivery_note_pdf, build_delivery_note_rows
from post.internetmarke_client import InternetmarkeClient
from post.product_catalog import find_post_product, list_post_base_products
from shipping.carriers import (
DEFAULT_ACTIVE_SHIPPING_CARRIERS,
SHIPPING_CARRIER_DEFINITIONS,
SHIPPING_CARRIER_ORDER,
ShippingCarrierRuntime,
carrier_allows_shopify as _shipping_carrier_allows_shopify,
carrier_definition as _shipping_carrier_definition,
carrier_field_to_code as _shipping_carrier_field_to_code,
carrier_label as _shipping_carrier_label,
carrier_option_mode as _shipping_carrier_option_mode,
carrier_setting_field as _shipping_carrier_setting_field,
configurable_carrier_codes as _configurable_shipping_carrier_codes,
default_tracking_mode_for_carrier as _default_tracking_mode_for_carrier,
normalize_active_carriers as _normalize_active_shipping_carriers,
shipping_active_carrier_values as _shipping_active_carrier_values,
shipping_carrier_options as _shipping_carrier_options_impl,
shopify_tracking_company as _shopify_tracking_company,
)
from shipping.history import (
SHIPPING_LABEL_TABLE,
ensure_shipping_history_schema,
find_or_create_shopify_fulfillment_job as _find_or_create_shopify_fulfillment_job,
get_latest_shopify_job_for_label as _get_latest_shopify_job_for_label,
get_latest_shipping_label_for_order as _get_latest_shipping_label_for_order,
insert_shipping_label_history as _insert_shipping_label_history,
list_shipping_labels as _list_shipping_labels,
update_shipping_label_reprint as _update_shipping_label_reprint,
update_shipping_label_status as _update_shipping_label_status,
)
locale.setlocale(locale.LC_ALL, "")
SETTINGS = load_settings()
LOGGER = get_logger("lager_mc")
PRINT_LOGGER = get_logger("print")
BASE_DIR = Path(__file__).resolve().parent
LABEL_PRINT_SCRIPT = str(BASE_DIR / "label_print.py")
GLS_DIR = BASE_DIR / "gls"
GLS_LABEL_DIR = GLS_DIR / "labels"
POST_DIR = BASE_DIR / "post"
POST_LABEL_DIR = POST_DIR / "labels"
SHOPIFY_SYNC_SERVICE = "shopify-sync"
_SERVICE_RUNTIME_CACHE = {"loaded_at": 0.0, "rows": {}}
_POST_PAGE_FORMAT_CACHE = {"loaded_at": 0.0, "formats": []}
_POST_SELECTION_CACHE = {}
_SHIPPING_CARRIER_CACHE = "gls"
SHIPPING_SERVICE_OPTIONS = [
{"code": "service_flexdelivery", "label": "FlexDelivery - Zustelloptionen fuer den Empfaenger", "locked": False},
{"code": "service_addresseeonly", "label": "AddresseeOnly - Nur an den Empfaenger persoenlich", "locked": False},
{"code": "service_guaranteed24", "label": "Guaranteed24 - Garantierte Zustellung am naechsten Werktag", "locked": False},
{"code": "service_preadvice", "label": "PreAdvice - Vorabankuendigung an den Empfaenger", "locked": False},
{"code": "service_smsservice", "label": "SMS Service - Versandinfo per SMS", "locked": False},
]
MANUAL_LABEL_COUNTRY_OPTIONS = [
{"value": "AD", "label": "Andorra"},
{"value": "AT", "label": "Austria"},
{"value": "BE", "label": "Belgium"},
{"value": "BG", "label": "Bulgaria"},
{"value": "CH", "label": "Switzerland"},
{"value": "CY", "label": "Cyprus"},
{"value": "CZ", "label": "Czechia"},
{"value": "DE", "label": "Germany"},
{"value": "DK", "label": "Denmark"},
{"value": "EE", "label": "Estonia"},
{"value": "ES", "label": "Spain"},
{"value": "FI", "label": "Finland"},
{"value": "FR", "label": "France"},
{"value": "GB", "label": "United Kingdom"},
{"value": "GR", "label": "Greece"},
{"value": "HR", "label": "Croatia"},
{"value": "HU", "label": "Hungary"},
{"value": "IE", "label": "Ireland"},
{"value": "IS", "label": "Iceland"},
{"value": "IT", "label": "Italy"},
{"value": "LI", "label": "Liechtenstein"},
{"value": "LT", "label": "Lithuania"},
{"value": "LU", "label": "Luxembourg"},
{"value": "LV", "label": "Latvia"},
{"value": "MC", "label": "Monaco"},
{"value": "MT", "label": "Malta"},
{"value": "NL", "label": "Netherlands"},
{"value": "NO", "label": "Norway"},
{"value": "PL", "label": "Poland"},
{"value": "PT", "label": "Portugal"},
{"value": "RO", "label": "Romania"},
{"value": "SE", "label": "Sweden"},
{"value": "SI", "label": "Slovenia"},
{"value": "SK", "label": "Slovakia"},
{"value": "SM", "label": "San Marino"},
{"value": "VA", "label": "Vatican City"},
]
COUNTRY_NAME_DE = {
"AD": "Andorra",
"AT": "Oesterreich",
"BE": "Belgien",
"BG": "Bulgarien",
"CH": "Schweiz",
"CY": "Zypern",
"CZ": "Tschechien",
"DE": "Deutschland",
"DK": "Daenemark",
"EE": "Estland",
"ES": "Spanien",
"FI": "Finnland",
"FR": "Frankreich",
"GB": "Vereinigtes Koenigreich",
"GR": "Griechenland",
"HR": "Kroatien",
"HU": "Ungarn",
"IE": "Irland",
"IS": "Island",
"IT": "Italien",
"LI": "Liechtenstein",
"LT": "Litauen",
"LU": "Luxemburg",
"LV": "Lettland",
"MC": "Monaco",
"MT": "Malta",
"NL": "Niederlande",
"NO": "Norwegen",
"PL": "Polen",
"PT": "Portugal",
"RO": "Rumänien",
"SE": "Schweden",
"SI": "Slowenien",
"SK": "Slowakei",
"SM": "San Marino",
"VA": "Vatikanstadt",
}
COUNTRY_ALPHA3 = {
"AD": "AND",
"AT": "AUT",
"BE": "BEL",
"BG": "BGR",
"CH": "CHE",
"CY": "CYP",
"CZ": "CZE",
"DE": "DEU",
"DK": "DNK",
"EE": "EST",
"ES": "ESP",
"FI": "FIN",
"FR": "FRA",
"GB": "GBR",
"GR": "GRC",
"HR": "HRV",
"HU": "HUN",
"IE": "IRL",
"IS": "ISL",
"IT": "ITA",
"LI": "LIE",
"LT": "LTU",
"LU": "LUX",
"LV": "LVA",
"MC": "MCO",
"MT": "MLT",
"NL": "NLD",
"NO": "NOR",
"PL": "POL",
"PT": "PRT",
"RO": "ROU",
"SE": "SWE",
"SI": "SVN",
"SK": "SVK",
"SM": "SMR",
"VA": "VAT",
}
FULFILLMENT_FILTER_SEQUENCE = ["all", "open", "unfulfilled", "partial", "fulfilled"]
PAYMENT_FILTER_SEQUENCE = ["all", "paid", "pending", "authorized", "partially_paid", "refunded", "voided"]
ITEMS_AUTO_REFRESH_SECONDS = 10.0
ORDERS_AUTO_REFRESH_SECONDS = 10.0
ORDER_DETAILS_LOAD_DELAY_SECONDS = 0.25
SERVICE_RUNTIME_CACHE_SECONDS = 30.0
COLS = [
("SKU", 18),
("Name", 60),
("Regal", 7),
("Fach", 6),
("Platz", 7),
("Gesamt", 7),
("N. verf.", 8),
("Best.", 7),
("Verfüg.", 7),
("S", 2),
]
SUPPORTED_LANGUAGES = {"de", "en"}
BASE_THEMES = {
"blue": {
"pair_1_fg": "white",
"pair_1_bg": "blue",
"pair_2_fg": "black",
"pair_2_bg": "cyan",
"pair_3_fg": "black",
"pair_3_bg": "white",
},
"green": {
"pair_1_fg": "black",
"pair_1_bg": "green",
"pair_2_fg": "black",
"pair_2_bg": "yellow",
"pair_3_fg": "black",
"pair_3_bg": "white",
},
"mono": {
"pair_1_fg": "white",
"pair_1_bg": "black",
"pair_2_fg": "black",
"pair_2_bg": "white",
"pair_3_fg": "white",
"pair_3_bg": "black",
},
"megatrends": {
"pair_1_fg": "brightyellow",
"pair_1_bg": "blue",
"pair_2_fg": "blue",
"pair_2_bg": "brightwhite",
"pair_3_fg": "brightblack",
"pair_3_bg": "black",
},
"smoth": {
"pair_1_fg": "white",
"pair_1_bg": "brightblue",
"pair_2_fg": "brightblue",
"pair_2_bg": "brightwhite",
"pair_3_fg": "brightblue",
"pair_3_bg": "blue",
},
"norton": {
"pair_1_fg": "brightcyan",
"pair_1_bg": "blue",
"pair_2_fg": "brightcyan",
"pair_2_bg": "black",
"pair_3_fg": "brightwhite",
"pair_3_bg": "black",
},
"gold-standard": {
"pair_1_fg": "brightyellow",
"pair_1_bg": "brown",
"pair_2_fg": "brown",
"pair_2_bg": "brightyellow",
"pair_3_fg": "brown",
"pair_3_bg": "black",
},
"subtile": {
"pair_1_fg": "brightwhite",
"pair_1_bg": "white",
"pair_2_fg": "brightblack",
"pair_2_bg": "white",
"pair_3_fg": "white",
"pair_3_bg": "brightblack",
},
"monokai": {
"pair_1_fg": "brightwhite",
"pair_1_bg": "brightblack",
"pair_2_fg": "brightwhite",
"pair_2_bg": "white",
"pair_3_fg": "white",
"pair_3_bg": "black",
},
}
CUSTOM_COLOR_RGB = {
"brown": (680, 340, 0),
"darkgray": (350, 350, 350),
"darkgrey": (350, 350, 350),
"gray": (650, 650, 650),
"grey": (650, 650, 650),
"lightgray": (800, 800, 800),
"lightgrey": (800, 800, 800),
"brightblack": (500, 500, 500),
"brightred": (1000, 200, 200),
"brightgreen": (200, 1000, 200),
"brightyellow": (1000, 1000, 300),
"brightblue": (300, 300, 1000),
"brightmagenta": (1000, 300, 1000),
"brightcyan": (300, 1000, 1000),
"brightwhite": (1000, 1000, 1000),
}
CUSTOM_COLOR_IDS = {}
THEME_KEY_SET = {
"pair_1_fg",
"pair_1_bg",
"pair_2_fg",
"pair_2_bg",
"pair_3_fg",
"pair_3_bg",
}
TRANSLATIONS = {
"de": {
"app_title": "Lagerverwaltung",
"settings": "Einstellungen",
"focus_items": " Fokus: Artikel ",
"focus_locations": " Fokus: Regale ",
"view_external": " | Ansicht: Extern ",
"filter_prefix": " Filter: {value} ",
"status_primary": " Tab Fokus F1 Sortieren F2 Lokal F3 Ohne F4 Info F5 Neu F6 Platz F7 Menge F8 Label F9 Reset F10 Ende F11 Mehr F12 Auftraege ",
"status_secondary": " Shift+F1 Inventur Shift+F5 Bearb. Shift+F8 Multi-Label Shift+F11 Einst. F11 Standard F12 Auftraege F10 Ende ",
"no_locations": "Keine Lagerplaetze",
"locations_panel": "Regale",
"items_panel": "Artikel",
"press_key": "Taste druecken ...",
"confirm_yes_no": "[J]a / [N]ein",
"search": "Suche",
"search_footer": "Enter suchen F9 Abbrechen",
"printer_dialog": "Drucker",
"printer_error": "Drucker Fehler",
"printer_none": "Keinen Drucker auswaehlen",
"printer_empty": "(leer)",
"printer_active": "aktiv",
"printer_default": "default",
"printer_reload_footer": "Enter waehlen F5 Neu laden F9 Zurueck",
"settings_footer": "Enter weiter ↑↓ wechseln F2 Speichern F3 Drucker F9 Abbrechen",
"settings_footer_select": "Enter weiter/Auswahl ↑↓ wechseln F2 Speichern F3 Drucker F9 Abbrechen",
"pick_language": "Sprache waehlen",
"pick_theme": "Farbthema waehlen",
"pick_cancel": "F9 Zurueck",
"field_db_host": "DB Host",
"field_db_name": "DB Name",
"field_db_user": "DB User",
"field_db_pass": "DB Passwort",
"field_language": "Sprache",
"field_theme": "Farbthema",
"field_theme_file": "Theme Datei",
"field_printer_uri": "Drucker URI",
"field_printer_model": "Drucker Modell",
"field_label_size": "Labelformat",
"field_label_font_regular": "Label Font (Reg)",
"field_label_font_condensed": "Label Font (Cond)",
"field_regex_regal": "Regex Regal",
"field_regex_fach": "Regex Fach",
"field_regex_platz": "Regex Platz",
"field_picklist_printer": "Pickliste Drucker",
"field_delivery_printer": "Lieferschein Drucker",
"field_delivery_format": "Lieferschein Format",
"field_shipping_printer": "Versandlabel Drucker",
"field_shipping_printer_gls": "GLS Label Drucker",
"field_shipping_printer_free": "Adresslabel Drucker",
"field_shipping_printer_post": "POST Label Drucker",
"field_shipping_printer_fallback": "Label Drucker Fallback",
"field_shipping_active_carriers": "Aktive Versanddienste",
"field_shipping_label_output_dir": "Versandlabel Ordner",
"field_shipping_format": "Versand Labelformat",
"field_shipping_format_gls": "GLS Labelformat",
"field_shipping_format_free": "Adresslabel Format",
"field_shipping_format_post": "POST Labelformat",
"field_shipping_services": "Versand Services",
"field_shipping_packaging_weight": "Verpackung Gewicht (g)",
"field_shopify_tracking_mode_gls": "Shopify Tracking GLS",
"field_shopify_tracking_mode_post": "Shopify Tracking POST",
"field_shopify_tracking_url_gls": "Shopify Tracking URL GLS",
"field_shopify_tracking_url_post": "Shopify Tracking URL POST",
"field_gls_api_url": "GLS API URL",
"field_gls_user": "GLS User",
"field_gls_password": "GLS Passwort",
"field_gls_contact_id": "GLS ContactID",
"field_post_api_url": "POST API URL",
"field_post_api_key": "POST API Key",
"field_post_api_secret": "POST API Secret",
"field_post_user": "POST User",
"field_post_password": "POST Passwort",
"field_post_partner_id": "POST Partner-ID",
"field_free_label_template": "Adresslabel Vorlage",
"field_pdf_dir": "PDF Ordner",
"field_template": "LS Vorlage",
"field_logo": "LS Logo URL/Pfad",
"field_sender_name": "LS Name",
"field_sender_street": "LS Strasse",
"field_sender_city": "LS Ort",
"field_sender_email": "LS E-Mail",
"col_shelf": "Regal",
"col_bin": "Fach",
"col_slot": "Platz",
"col_total": "Gesamt",
"col_unavailable": "N. verf.",
"col_committed": "Best.",
"col_available": "Verf.",
"error": "Fehler",
"saved": "Gespeichert",
"saved_settings": "Einstellungen wurden gespeichert.",
"theme_file_missing": "Theme-Datei existiert nicht.",
"theme_invalid": "Farbthema ungueltig. Erlaubt: {names}",
"lang_de": "Deutsch",
"lang_en": "Englisch",
"theme_blue": "Blau",
"theme_green": "Gruen",
"theme_mono": "Monochrom",
"theme_megatrends": "Megatrends (DOS)",
"theme_smoth": "Smoth (DOS)",
"theme_norton": "Norton (DOS)",
"theme_gold_standard": "Gold Standard (DOS)",
"theme_subtile": "Subtile (DOS)",
"theme_monokai": "Monokai (DOS)",
},
"en": {
"app_title": "Inventory Manager",
"settings": "Settings",
"focus_items": " Focus: Items ",
"focus_locations": " Focus: Shelves ",
"view_external": " | View: External ",
"filter_prefix": " Filter: {value} ",
"status_primary": " Tab Focus F1 Sort F2 Local F3 Missing F4 Info F5 New F6 Location F7 Qty F8 Label F9 Reset F10 Exit F11 More F12 Orders ",
"status_secondary": " Shift+F1 Stocktake Shift+F5 Edit Shift+F8 Multi-Label Shift+F11 Settings F11 Standard F12 Orders F10 Exit ",
"no_locations": "No storage locations",
"locations_panel": "Locations",
"items_panel": "Items",
"press_key": "Press any key ...",
"confirm_yes_no": "[Y]es / [N]o",
"search": "Search",
"search_footer": "Enter search F9 Cancel",
"printer_dialog": "Printers",
"printer_error": "Printer Error",
"printer_none": "Select no printer",
"printer_empty": "(empty)",
"printer_active": "active",
"printer_default": "default",
"printer_reload_footer": "Enter select F5 Reload F9 Back",
"settings_footer": "Enter next ↑↓ move F2 Save F3 Printer F9 Cancel",
"settings_footer_select": "Enter next/select ↑↓ move F2 Save F3 Printer F9 Cancel",
"pick_language": "Select language",
"pick_theme": "Select color theme",
"pick_cancel": "F9 Back",
"field_db_host": "DB Host",
"field_db_name": "DB Name",
"field_db_user": "DB User",
"field_db_pass": "DB Password",
"field_language": "Language",
"field_theme": "Color Theme",
"field_theme_file": "Theme File",
"field_printer_uri": "Printer URI",
"field_printer_model": "Printer Model",
"field_label_size": "Label Format",
"field_label_font_regular": "Label Font (Reg)",
"field_label_font_condensed": "Label Font (Cond)",
"field_regex_regal": "Regex Shelf",
"field_regex_fach": "Regex Bin",
"field_regex_platz": "Regex Slot",
"field_picklist_printer": "Picklist Printer",
"field_delivery_printer": "Delivery Printer",
"field_delivery_format": "Delivery Format",
"field_shipping_printer": "Shipping Label Printer",
"field_shipping_printer_gls": "GLS Label Printer",
"field_shipping_printer_free": "Address Label Printer",
"field_shipping_printer_post": "POST Label Printer",
"field_shipping_printer_fallback": "Label Printer Fallback",
"field_shipping_active_carriers": "Active Shipping Carriers",
"field_shipping_label_output_dir": "Shipping Label Folder",
"field_shipping_format": "Shipping Label Format",
"field_shipping_format_gls": "GLS Label Format",
"field_shipping_format_free": "Address Label Format",
"field_shipping_format_post": "POST Label Format",
"field_shipping_services": "Shipping Services",
"field_shipping_packaging_weight": "Packaging Weight (g)",
"field_shopify_tracking_mode_gls": "Shopify Tracking GLS",
"field_shopify_tracking_mode_post": "Shopify Tracking POST",
"field_shopify_tracking_url_gls": "Shopify Tracking URL GLS",
"field_shopify_tracking_url_post": "Shopify Tracking URL POST",
"field_gls_api_url": "GLS API URL",
"field_gls_user": "GLS User",
"field_gls_password": "GLS Password",
"field_gls_contact_id": "GLS ContactID",
"field_post_api_url": "POST API URL",
"field_post_api_key": "POST API Key",
"field_post_api_secret": "POST API Secret",
"field_post_user": "POST User",
"field_post_password": "POST Password",
"field_post_partner_id": "POST Partner ID",
"field_free_label_template": "Address Label Template",
"field_pdf_dir": "PDF Folder",
"field_template": "Delivery Template",
"field_logo": "Delivery Logo URL/Path",
"field_sender_name": "Sender Name",
"field_sender_street": "Sender Street",
"field_sender_city": "Sender City",
"field_sender_email": "Sender E-Mail",
"col_shelf": "Shelf",
"col_bin": "Bin",
"col_slot": "Slot",
"col_total": "Total",
"col_unavailable": "Unav.",
"col_committed": "Comm.",
"col_available": "Avail.",
"error": "Error",
"saved": "Saved",
"saved_settings": "Settings were saved.",
"theme_file_missing": "Theme file does not exist.",
"theme_invalid": "Invalid color theme. Allowed: {names}",
"lang_de": "German",
"lang_en": "English",
"theme_blue": "Blue",
"theme_green": "Green",
"theme_mono": "Monochrome",
"theme_megatrends": "Megatrends (DOS)",
"theme_smoth": "Smoth (DOS)",
"theme_norton": "Norton (DOS)",
"theme_gold_standard": "Gold Standard (DOS)",
"theme_subtile": "Subtile (DOS)",
"theme_monokai": "Monokai (DOS)",
},
}
def current_language():
language = (SETTINGS.get("language") or DEFAULT_SETTINGS.get("language") or "de").lower().strip()
if language not in SUPPORTED_LANGUAGES:
return "de"
return language
def t(key, **kwargs):
language = current_language()
value = TRANSLATIONS.get(language, {}).get(key)
if value is None:
value = TRANSLATIONS["de"].get(key, key)
if kwargs:
try:
return value.format(**kwargs)
except Exception:
return value
return value
def get_active_theme_name():
themes = get_all_themes()
theme_name = (SETTINGS.get("color_theme") or DEFAULT_SETTINGS.get("color_theme") or "blue").strip().lower()
if theme_name not in themes:
return "blue"
return theme_name
def get_theme_file_candidates():
configured = (SETTINGS.get("color_theme_file") or "").strip()
candidates = []
if configured:
candidates.append(Path(os.path.expanduser(configured)))
else:
candidates.append(Path(__file__).resolve().parent / "themes.local.json")
candidates.append(Path(__file__).resolve().parent / "local_only" / "themes.json")
return candidates
def _is_valid_theme_map(value):
if not isinstance(value, dict):
return False
return THEME_KEY_SET.issubset(set(value.keys()))
def load_custom_themes_from_file(path):
candidate = Path(path)
try:
raw = candidate.read_text(encoding="utf-8")
data = json.loads(raw)
except Exception as exc:
LOGGER.warning("Konnte Theme-Datei nicht lesen: %s (%s)", candidate, exc)
return {}
if isinstance(data, dict) and isinstance(data.get("themes"), dict):
data = data["themes"]
if not isinstance(data, dict):
LOGGER.warning("Theme-Datei hat ungueltiges Format: %s", candidate)
return {}
custom = {}
for name, theme in data.items():
theme_name = str(name).strip().lower()
if not theme_name:
continue
if _is_valid_theme_map(theme):
custom[theme_name] = {key: str(theme[key]).strip().lower() for key in THEME_KEY_SET}
else:
LOGGER.warning("Theme '%s' in %s ist unvollstaendig und wird ignoriert.", name, candidate)
return custom
def load_custom_themes():
for candidate in get_theme_file_candidates():
if not candidate.exists():
continue
custom = load_custom_themes_from_file(candidate)
if custom:
return custom
return {}
def get_all_themes():
themes = dict(BASE_THEMES)
themes.update(load_custom_themes())
return themes
def _color_from_name(name):
color_name = (name or "white").lower()
custom_id = _custom_color_id(color_name)
if custom_id is not None:
return custom_id
return {
"black": curses.COLOR_BLACK,
"red": curses.COLOR_RED,
"green": curses.COLOR_GREEN,
"darkgray": curses.COLOR_BLACK,
"darkgrey": curses.COLOR_BLACK,
"gray": curses.COLOR_BLACK,
"grey": curses.COLOR_BLACK,
"lightgray": curses.COLOR_WHITE,
"lightgrey": curses.COLOR_WHITE,
"brown": curses.COLOR_RED,
"yellow": curses.COLOR_YELLOW,
"blue": curses.COLOR_BLUE,
"magenta": curses.COLOR_MAGENTA,
"cyan": curses.COLOR_CYAN,
"brightblack": curses.COLOR_BLACK,
"brightred": curses.COLOR_RED,
"brightgreen": curses.COLOR_GREEN,
"brightyellow": curses.COLOR_YELLOW,
"brightblue": curses.COLOR_BLUE,
"brightmagenta": curses.COLOR_MAGENTA,
"brightcyan": curses.COLOR_CYAN,
"brightwhite": curses.COLOR_WHITE,
"white": curses.COLOR_WHITE,
}.get(color_name, curses.COLOR_WHITE)
def _custom_color_id(color_name):
if color_name not in CUSTOM_COLOR_RGB:
return None
if color_name in CUSTOM_COLOR_IDS:
return CUSTOM_COLOR_IDS[color_name]
can_customize = bool(getattr(curses, "can_change_color", lambda: False)())
color_slots = int(getattr(curses, "COLORS", 0) or 0)
if not can_customize or color_slots < 32:
return None
next_id = 16 + len(CUSTOM_COLOR_IDS)
if next_id >= color_slots:
return None
try:
curses.init_color(next_id, *CUSTOM_COLOR_RGB[color_name])
except curses.error:
return None
CUSTOM_COLOR_IDS[color_name] = next_id
return next_id
def apply_color_theme(stdscr):
theme = get_all_themes()[get_active_theme_name()]
pair_1 = _resolve_pair_colors(theme["pair_1_fg"], theme["pair_1_bg"], fallback_fg="white", fallback_bg="blue")
pair_2 = _resolve_pair_colors(theme["pair_2_fg"], theme["pair_2_bg"], fallback_fg="black", fallback_bg="cyan")
pair_3 = _resolve_pair_colors(theme["pair_3_fg"], theme["pair_3_bg"], fallback_fg="black", fallback_bg="white")
curses.init_pair(1, pair_1[0], pair_1[1])
curses.init_pair(2, pair_2[0], pair_2[1])
curses.init_pair(3, pair_3[0], pair_3[1])
stdscr.bkgd(" ", curses.color_pair(1))
def _resolve_pair_colors(fg_name, bg_name, fallback_fg, fallback_bg):
fg = _color_from_name(fg_name)
bg = _color_from_name(bg_name)
if fg == bg:
return _color_from_name(fallback_fg), _color_from_name(fallback_bg)
return fg, bg
def init_db():
con = db()
cur = con.cursor()
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS available integer")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS reserved integer DEFAULT 0")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS committed integer DEFAULT 0")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS unavailable integer DEFAULT 0")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS external_fulfillment boolean NOT NULL DEFAULT FALSE")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS barcode text")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS shopify_product_status text")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS shopify_description text")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS shopify_price text")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS shopify_compare_at_price text")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS shopify_unit_cost text")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS shopify_unit_cost_currency text")
cur.execute("ALTER TABLE items ADD COLUMN IF NOT EXISTS shopify_weight_grams integer")
cur.execute("UPDATE items SET reserved = COALESCE(reserved, 0)")
cur.execute("UPDATE items SET committed = COALESCE(committed, 0)")
cur.execute(
"""
UPDATE items
SET unavailable = COALESCE(unavailable, COALESCE(reserved, 0))
"""
)
cur.execute(
"""
UPDATE items
SET available = GREATEST(
menge - COALESCE(unavailable, 0) - COALESCE(committed, 0),
0
)
WHERE available IS NULL
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS shopify_orders (
order_id text PRIMARY KEY,
order_name text NOT NULL,
created_at timestamptz,
shipping_name text,
shipping_address1 text,
shipping_zip text,
shipping_city text,
shipping_country text,
shipping_email text,
shipping_phone text,
fulfillment_status text,
payment_status text,
updated_at timestamptz NOT NULL DEFAULT NOW()
)
"""
)
cur.execute("ALTER TABLE shopify_orders ADD COLUMN IF NOT EXISTS shipping_country text")
cur.execute("ALTER TABLE shopify_orders ADD COLUMN IF NOT EXISTS shipping_email text")
cur.execute("ALTER TABLE shopify_orders ADD COLUMN IF NOT EXISTS shipping_phone text")
cur.execute("ALTER TABLE shopify_orders ADD COLUMN IF NOT EXISTS payment_status text")
cur.execute(
"""
CREATE UNIQUE INDEX IF NOT EXISTS idx_shopify_orders_name
ON shopify_orders(order_name)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS shopify_order_items (
order_id text NOT NULL,
line_index integer NOT NULL,
order_line_item_id text,
sku text,
title text NOT NULL,
quantity integer NOT NULL,
fulfilled_quantity integer NOT NULL DEFAULT 0,
PRIMARY KEY (order_id, line_index)
)
"""
)
cur.execute("ALTER TABLE shopify_order_items ADD COLUMN IF NOT EXISTS order_line_item_id text")
cur.execute("ALTER TABLE shopify_order_items ADD COLUMN IF NOT EXISTS fulfilled_quantity integer NOT NULL DEFAULT 0")
ensure_shipping_history_schema(cur)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS service_runtime_state (
service text PRIMARY KEY,
version text,
status text NOT NULL DEFAULT 'unknown',
last_seen_at timestamptz,
last_started_at timestamptz,
last_finished_at timestamptz,
last_pull_at timestamptz,
last_push_at timestamptz,
last_error text,
updated_at timestamptz NOT NULL DEFAULT NOW()
)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS shopify_customers (
customer_id text PRIMARY KEY,
first_name text,
last_name text,
display_name text,
email text,
phone text,
default_name text,
default_address1 text,
default_zip text,
default_city text,
default_country text,
default_phone text,
updated_at timestamptz NOT NULL DEFAULT NOW()
)
"""
)
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS first_name text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS last_name text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS display_name text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS email text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS phone text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS default_name text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS default_address1 text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS default_zip text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS default_city text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS default_country text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS default_phone text")
cur.execute("ALTER TABLE shopify_customers ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT NOW()")
cur.execute("CREATE INDEX IF NOT EXISTS idx_shopify_customers_display_name ON shopify_customers(display_name)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_shopify_customers_email ON shopify_customers(email)")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS version text")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS status text NOT NULL DEFAULT 'unknown'")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS last_seen_at timestamptz")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS last_started_at timestamptz")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS last_finished_at timestamptz")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS last_pull_at timestamptz")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS last_push_at timestamptz")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS last_error text")
cur.execute("ALTER TABLE service_runtime_state ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT NOW()")
cur.execute(
"""
CREATE TABLE IF NOT EXISTS inventory_sessions (
session_id serial PRIMARY KEY,
session_name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT NOW(),
status text NOT NULL DEFAULT 'active'
)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS inventory_lines (
session_id integer NOT NULL REFERENCES inventory_sessions(session_id) ON DELETE CASCADE,
line_no integer NOT NULL,
sku text NOT NULL,
name text NOT NULL,
regal text,
fach text,
platz text,
soll_menge integer NOT NULL,
ist_menge integer,
PRIMARY KEY (session_id, line_no)
)
"""
)
con.commit()
cur.close()
con.close()
class DatabaseUnavailableError(RuntimeError):
pass
class DatabaseBusyError(RuntimeError):
pass
def _summarize_db_error(exc):
text = str(exc or "").strip()
lines = [line.strip() for line in text.splitlines() if line.strip()]
if not lines:
return "Datenbank ist nicht erreichbar."
return " | ".join(lines[:2])[:180]
def _execute_db_query(cur, query, params=None, deadlock_retries=1):
params = params or []
for attempt in range(deadlock_retries + 1):
try:
cur.execute(query, params)
return
except psycopg2.errors.DeadlockDetected as exc:
if attempt < deadlock_retries:
time.sleep(0.2 * (attempt + 1))
continue
raise DatabaseBusyError("Datenbank ist kurzzeitig blockiert. Bitte erneut versuchen.") from exc
def _probe_database_ready():
if _is_default_db_settings(SETTINGS):
return False, "Bitte zuerst DB Einstellungen in Shift+F11 speichern."
try:
init_db()
return True, ""
except Exception as exc:
return False, _summarize_db_error(exc)
def database_connection_dialog(stdscr, error_text):
message = (error_text or "Datenbank ist nicht erreichbar.").strip()
while True:
h, w = stdscr.getmaxyx()
width = min(max(78, int(w * 0.72)), w - 4)
height = 11
y = max(1, (h - height) // 2)
x = max(2, (w - width) // 2)
draw_shadow(stdscr, y, x, height, width)
win = curses.newwin(height, width, y, x)
win.keypad(True)
win.timeout(1000)
win.bkgd(" ", curses.color_pair(1))
win.erase()
win.box()
win.addstr(0, 2, " DB Problem ")
host_line = f"Host: {SETTINGS.get('db_host') or '-'} DB: {SETTINGS.get('db_name') or '-'}"
status_line = "Warte auf Verbindung, starte automatisch bei Erfolg."
footer = "Enter Neu versuchen F2 Einstellungen F9 Beenden"
wrapped_error = textwrap.wrap(message, width=max(20, width - 4)) or ["Datenbank ist nicht erreichbar."]
win.addstr(2, 2, _fit(host_line, width - 4))
for index, line in enumerate(wrapped_error[:3]):
win.addstr(4 + index, 2, _fit(line, width - 4))
win.addstr(height - 3, 2, _fit(status_line, width - 4))
win.attrset(curses.color_pair(3))
win.addstr(height - 2, 2, _fit(footer, width - 4))
win.attrset(curses.color_pair(1))
win.refresh()
key = win.getch()
if key == -1 or key in (10, 13, curses.KEY_ENTER):
ready, latest_error = _probe_database_ready()
if ready:
return True
if latest_error:
message = latest_error
continue
if key == curses.KEY_F2:
settings_dialog(stdscr)
ready, latest_error = _probe_database_ready()
if ready:
return True
if latest_error:
message = latest_error
continue
if key in (27, curses.KEY_F9):
return False
def db():
try:
return psycopg2.connect(
host=SETTINGS["db_host"],
dbname=SETTINGS["db_name"],
user=SETTINGS["db_user"],
password=SETTINGS["db_pass"],
cursor_factory=psycopg2.extras.RealDictCursor
)
except psycopg2.OperationalError as exc:
raise DatabaseUnavailableError(_summarize_db_error(exc)) from exc
def get_service_runtime_state(service=SHOPIFY_SYNC_SERVICE, max_age_seconds=SERVICE_RUNTIME_CACHE_SECONDS, force=False):
now = time.monotonic()
cached = _SERVICE_RUNTIME_CACHE["rows"].get(service)
if not force and cached is not None and now - _SERVICE_RUNTIME_CACHE["loaded_at"] < max_age_seconds:
return cached
con = None
cur = None
try:
con = db()
cur = con.cursor()
cur.execute(
"""
SELECT
service,
version,
status,
last_seen_at,
last_started_at,
last_finished_at,
last_pull_at,