-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
1804 lines (1558 loc) · 65.4 KB
/
util.py
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
import logging
logging_configured = False
def setup_logging():
global logging_configured
if not logging_configured:
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('rigs_pos.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)',
datefmt='%m/%d/%Y %H:%M:%S')
fh.setFormatter(formatter)
logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter_console = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)')
ch.setFormatter(formatter_console)
logger.addHandler(ch)
logger.propagate = False
logging_configured = True
logger = logging.getLogger('rigs_pos')
import json
import time
import subprocess
import threading
import sys
import random
import os
import uuid
from datetime import datetime, timedelta
import dbus
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.uix.textinput import TextInput
from kivymd.uix.gridlayout import MDGridLayout
from kivymd.app import MDApp
from kivymd.toast import toast
from kivymd.uix.boxlayout import BoxLayout
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.button import MDRaisedButton, MDFlatButton, MDIconButton
from kivymd.uix.gridlayout import GridLayout
from kivymd.uix.label import MDLabel
from kivy.uix.behaviors import ButtonBehavior
from barcode.upc import UniversalProductCodeA as upc_a
from open_cash_drawer import open_cash_drawer
from receipt_printer import ReceiptPrinter
from barcode_scanner import BarcodeScanner
from button_handlers import ButtonHandler
from database_manager import DatabaseManager
from history_manager import HistoryView, HistoryPopup, OrderDetailsPopup
from inventory_manager import InventoryManagementView, InventoryManagementRow
from label_printer import LabelPrintingView, LabelPrinter
from order_manager import OrderManager
from popups import PopupManager, FinancialSummaryWidget, Calculator
# from wrapper import Wrapper
from distributor_manager import DistPopup, DistView
import inspect
def log_caller_info(depth=1):
stack = inspect.stack()
if depth < len(stack):
caller_frame = stack[depth]
file_name = caller_frame.filename
line_number = caller_frame.lineno
function_name = caller_frame.function
logger.warn(f"Called from {file_name}, line {line_number}, in {function_name}")
class Utilities:
def __init__(self, ref):
self.app = ref
self.clock_in_file = ""
self.popup_manager = PopupManager(None)
self.font = "images/VarelaRound-Regular.ttf"
self.screen_brightness = 75
def adjust_screen_brightness(self, direction):
if self.screen_brightness < 20:
logger.info("Brightness is below minimum, setting to minimum of 20")
self.set_brightness(20)
return
elif self.screen_brightness > 80:
logger.info("Brightness is above maximum, setting to maximum of 80")
self.set_brightness(80)
return
if direction == "down":
if self.screen_brightness == 20:
logger.info("Brightness is already at minimum")
else:
new_value = max(self.screen_brightness - 10, 20)
self.set_brightness(new_value)
elif direction == "up":
if self.screen_brightness == 80:
logger.info("Brightness is already at maximum")
else:
new_value = min(self.screen_brightness + 10, 80)
self.set_brightness(new_value)
def set_brightness(self, value):
self.screen_brightness = value
command = ["sudo", "ddccontrol", "-r", "0x10", "-w", str(value), "dev:/dev/i2c-3"]
try:
subprocess.Popen(command)
except subprocess.CalledProcessError:
logger.warn(f"[Utilities] failed to set brightness\n{e}")
def check_if_update_was_applied(self):
try:
os.remove('update_applied')
return True
except FileNotFoundError:
return False
def get_update_details(self):
update_details = []
try:
with open('update/update_details', 'r') as f:
for line in f:
update_details.append(line)
os.remove('update/update_details')
return update_details
except:
pass
return None
def initialize_global_variables(self):
# self.app.admin = False
self.app.pin_store = "pin_store.json"
self.app.attendance_log = "attendance_log.json"
self.app.entered_pin = ""
self.app.is_guard_screen_displayed = False
self.app.is_lock_screen_displayed = False
self.app.disable_lock_screen = False
self.app.override_tap_time = 0
self.app.click = 0
self.app.current_context = "main"
self.app.theme_cls.theme_style = "Dark"
self.app.theme_cls.primary_palette = "Brown"
self.app.selected_categories = []
def instantiate_modules(self):
try:
self.initialize_receipt_printer()
except: # TODO: Something other than log the error
logger.info("Receipt Printer was not initialized 1")
self.app.barcode_scanner = BarcodeScanner(self.app)
try:
self.app.db_manager = DatabaseManager("/home/rigs/rigs_pos/db/inventory.db", self.app)
except:
self.app.db_manager = DatabaseManager("/home/x/work/python/rigs_pos/db/inventory.db", self.app)
finally: # TODO: Something other than log the error
logger.info("Receipt Printer was not initialized (in finally block)")
self.app.financial_summary = FinancialSummaryWidget(self.app)
self.app.order_manager = OrderManager(self.app)
self.app.history_manager = HistoryView(self.app)
# self.app.order_history_popup = OrderManager(self.app)
self.app.history_popup = HistoryPopup()
self.app.inventory_manager = InventoryManagementView()
self.app.inventory_row = InventoryManagementRow()
self.app.label_printer = LabelPrinter(self.app)
self.app.label_manager = LabelPrintingView(self.app)
self.app.pin_reset_timer = ReusableTimer(5.0, self.reset_pin)
self.app.calculator = Calculator()
self.app.dist_manager = DistView(self.app)
self.app.dist_popup = DistPopup()
self.app.button_handler = ButtonHandler(self.app)
self.app.popup_manager = PopupManager(self.app)
# self.app.wrapper = Wrapper()
self.app.categories = self.initialize_categories()
self.app.barcode_cache = self.initialize_barcode_cache()
self.app.inventory_cache = self.initialize_inventory_cache()
def initialize_receipt_printer(self):
try:
self.app.receipt_printer = ReceiptPrinter(
self.app, "/home/rigs/rigs_pos/receipt_printer_config.yaml"
)
except:
self.app.receipt_printer = ReceiptPrinter(
self.app, "/home/x/work/python/rigs_pos/receipt_printer_config.yaml"
)
def initialize_barcode_cache(self):
all_items = self.app.db_manager.get_all_items()
barcode_cache = {}
# print(len(barcode_cache))
for item in all_items:
barcode = item[0]
if barcode not in barcode_cache:
barcode_cache[barcode] = {"items": [item], "is_dupe": False}
else:
barcode_cache[barcode]["items"].append(item)
barcode_cache[barcode]["is_dupe"] = True
# print(len(barcode_cache))
return barcode_cache
def initialize_inventory_cache(self):
inventory = self.app.db_manager.get_all_items()
return inventory
def update_inventory_cache(self):
inventory = self.app.db_manager.get_all_items()
self.app.inventory_cache = inventory
def update_barcode_cache(self, item_details):
barcode = item_details["barcode"]
if barcode not in self.app.barcode_cache:
self.app.barcode_cache[barcode] = {
"items": [item_details],
"is_dupe": False,
}
else:
self.app.barcode_cache[barcode]["items"].append(item_details)
self.app.barcode_cache[barcode]["is_dupe"] = True
def initialize_categories(self):
categories = [
"Cdb",
"Rig",
"Nails",
"Tubes",
"Hand Pipes",
"Chillum",
"Ecig",
"Butane",
"Torch",
"Toro",
"Slides H",
"Quartz",
"Vaporizers",
"Lighter",
"9mm Thick",
"Cleaning",
"Edible",
"Bubbler",
"Sherlock",
"Spoon",
"Silicone",
"Scales",
"Slides",
"Imported Glass",
"Ash Catcher",
"Soft Glass",
"Vaporizers",
"Pendant",
"Smoker Accessory",
"Ecig Accessories",
"Happy Fruit",
"Concentrate Accessories",
"Conc. Devices, Atomizers",
"Erigs And Accessory",
"Mods Batteries Kits",
]
return categories
def store_user_details(self, name, pin, admin):
user_details = {"name": name, "pin": pin, "admin": admin}
temp_file_path = self.app.pin_store + ".tmp"
final_file_path = self.app.pin_store
try:
if os.path.exists(final_file_path):
with open(final_file_path, "r") as file:
try:
data = json.load(file)
except json.JSONDecodeError:
data = []
else:
data = []
data.append(user_details)
with open(temp_file_path, "w") as file:
json.dump(data, file, indent=4)
os.replace(temp_file_path, final_file_path)
except Exception as e:
logger.warn(f"[Utilities]: store_user_details\n {e}")
if os.path.exists(temp_file_path):
os.remove(temp_file_path)
def validate_pin(self, entered_pin):
if not os.path.exists(self.app.pin_store):
self.store_user_details("default", entered_pin, False)
return {"name": "default", "admin": False}, True
with open(self.app.pin_store, "r") as file:
users = json.load(file)
for user in users:
if user["pin"] == entered_pin:
return {"name": user["name"], "admin": user["admin"]}, True
return False
def time_until_end_of_shift(self):
now = datetime.now()
end_of_shift = datetime(now.year, now.month, now.day, 23)
if now.hour >= 23:
end_of_shift += timedelta(days=1)
seconds_until_end = (end_of_shift - now).total_seconds()
return seconds_until_end
# def time_until_end_of_shift(self): # testing
#
# hour = 11
# minute = 3
# now = datetime.now()
# end_of_shift = datetime(now.year, now.month, now.day, hour, minute)
#
# if now >= end_of_shift:
# end_of_shift += timedelta(days=1)
#
# seconds_until_end = (end_of_shift - now).total_seconds()
# return seconds_until_end
def read_formatted_clock_in_time(self, clock_in_file):
if os.path.exists(clock_in_file):
with open(clock_in_file, "r") as file:
data = json.load(file)
clock_in_iso = data.get("clock_in", "")
if clock_in_iso:
clock_in_time = datetime.fromisoformat(clock_in_iso)
return clock_in_time.strftime("%I:%M %p")
return ""
def clock_in(self, entered_pin):
user_details, authenticated = self.validate_pin(entered_pin)
if not authenticated:
return False
self.app.logged_in_user = user_details
today_str = datetime.now().strftime("%Y-%m-%d")
if not os.path.exists(self.clock_in_file):
session_id = str(uuid.uuid4())
self.clock_in_file = f"/home/rigs/rigs_pos/{user_details['name']}-{today_str}-{session_id}.json"
with open(self.clock_in_file, "w") as file:
json.dump(
{"clock_in": datetime.now().isoformat(), "session_id": session_id},
file,
)
self.update_attendance_log(
user_details["name"],
session_id=session_id,
clock_in=True,
)
log_in_time = self.read_formatted_clock_in_time(self.clock_in_file)
self.time_clock.text = f"Logged in as {self.app.logged_in_user['name']}\n[u]Tap here to log out[/u]"
self.clock_out_event = Clock.schedule_once(
self.auto_clock_out, self.time_until_end_of_shift()
)
def clock_out(self, timestamp=None, auto=False):
if hasattr(self, "clock_out_event"):
self.clock_out_event.cancel()
if os.path.exists(self.clock_in_file):
session_id = self.extract_session_id(self.clock_in_file)
os.remove(self.clock_in_file)
self.update_attendance_log(
name=self.app.logged_in_user["name"],
session_id=session_id,
clock_out=True,
)
current_user = self.app.logged_in_user["name"]
self.app.logged_in_user["name"] = "nobody"
self.app.admin = False
try:
self.app.popup_manager.clock_out_popup.dismiss()
except:
pass
timestamp = timestamp or datetime.now().isoformat()
self.trigger_guard_and_lock(
clock_out=True, current_user=current_user, timestamp=timestamp, auto=auto
)
def auto_clock_out(self, dt):
logger.warn(f"called auto clock out\nclock in file: {self.clock_in_file}")
if os.path.exists(self.clock_in_file):
logger.warn("path exists")
session_id = self.extract_session_id(self.clock_in_file)
os.remove(self.clock_in_file)
midnight = datetime.now().replace(
hour=0, minute=0, second=0, microsecond=0
) + timedelta(days=1)
formatted_midnight = midnight.isoformat()
self.update_attendance_log(
#self.app.attendance_log,
name=self.app.logged_in_user["name"],
session_id=session_id,
#"auto",
timestamp=formatted_midnight,
clock_out=True,
)
timestamp = datetime.now().isoformat()
self.app.utilities.trigger_guard_and_lock(
auto_clock_out=True, timestamp=timestamp
)
def update_attendance_log(
self, name, session_id, timestamp=None, clock_in=False, clock_out=False
):
log_caller_info(depth=2)
logger.warn(f"update_attendance_log called with: name={name}, session_id={session_id}, timestamp={timestamp}, clock_in={clock_in}, clock_out={clock_out}")
if timestamp is None:
timestamp = datetime.now().isoformat()
if clock_in:
self.app.db_manager.insert_attendance_log_entry(name, session_id, timestamp)
elif clock_out:
self.app.db_manager.update_attendance_log_entry(session_id, timestamp)
# def update_attendance_log(
# self, log_file, user_name, action, session_id, auto=False, timestamp=None
# ):
# if timestamp is None:
# timestamp = datetime.now().isoformat()
#
# entry = {
# "name": user_name,
# "timestamp": timestamp,
# "action": action if not auto else "auto",
# "session_id": session_id,
# }
# if not os.path.exists(log_file):
# with open(log_file, "w") as file:
# json.dump([entry], file, indent=4)
# else:
# with open(log_file, "r+") as file:
# log = json.load(file)
# log.append(entry)
# file.seek(0)
# json.dump(log, file, indent=4)
def delete_session_from_log(self, session_id):
try:
with open(self.app.attendance_log, "r+") as file:
log = json.load(file)
updated_log = [
entry for entry in log if entry["session_id"] != session_id
]
file.seek(0)
file.truncate()
json.dump(updated_log, file, indent=4)
except Exception as e:
logger.warn(f"Utilities: delete_session_from_log\n{e}")
def extract_session_id(self, filename):
with open(filename, "r") as file:
data = json.load(file)
return data["session_id"]
def load_attendance_data(self):
data = self.app.db_manager.retrieve_attendence_log_entries()
return data
def organize_sessions(self, data):
sessions = {}
for entry in data:
session_id, user, clock_in, clock_out = (
entry[0],
entry[1],
entry[2],
entry[3],
)
if user not in sessions:
sessions[user] = {}
if session_id not in sessions[user]:
sessions[user][session_id] = {
"clock_in": None,
"clock_out": None,
"session_id": session_id,
}
if clock_in:
sessions[user][session_id]["clock_in"] = clock_in
if clock_out:
sessions[user][session_id]["clock_out"] = clock_out
return sessions
def format_sessions_for_display(self, sessions):
formatted_data = []
for user, user_sessions in sessions.items():
for session_id, session_details in user_sessions.items():
if session_details["clock_out"]:
clock_in_time = datetime.fromisoformat(session_details["clock_in"])
clock_out_time = datetime.fromisoformat(
session_details["clock_out"]
)
duration = clock_out_time - clock_in_time
hours, remainder = divmod(duration.total_seconds(), 3600)
minutes = remainder // 60
formatted_session = {
"date": clock_in_time.strftime("%m/%d/%Y"),
"name": user,
"clock_in": clock_in_time.strftime("%H:%M"),
"clock_out": clock_out_time.strftime("%H:%M"),
"hours": int(hours),
"minutes": int(minutes),
"session_id": session_id,
}
formatted_data.append(formatted_session)
return formatted_data
# def display_attendance_log(self): # testing
# data = self.load_attendance_data()
# sessions = self.organize_sessions(data)
# display_data = self.format_sessions_for_display(sessions)
# for line in display_data:
# print(line)
def reset_pin_timer(self):
logger.warn("reset_pin_timer", self.app.pin_reset_timer)
if self.app.pin_reset_timer is not None:
self.app.pin_reset_timer.stop()
self.app.pin_reset_timer.start()
def reset_pin(self, dt=None):
# print(
# f"reset pin\n{self.app.entered_pin}\n{self.app.popup_manager.pin_input.text}"
# )
def update_ui(dt):
self.app.entered_pin = ""
if self.app.popup_manager.pin_input is not None:
self.app.popup_manager.pin_input.text = ""
Clock.schedule_once(update_ui)
def calculate_common_amounts(self, total):
amounts = []
for base in [1, 5, 10, 20, 50, 100]:
amount = total - (total % base) + base
if amount not in amounts and amount >= total:
amounts.append(amount)
return amounts
def update_clock(self, *args):
current_time = time.strftime("%l:%M %p")
current_date = time.strftime("%A, %B %d, %Y")
formatted_time = f"[size=36][b]{current_time}[/b][/size]"
formatted_date = f"[size=26]{current_date}[/size]"
self.app.clock_label.font_name = self.font
self.app.clock_label.text = f"{formatted_time}\n{formatted_date}\n"
# self.app.clock_label.color = self.get_text_color()
def update_lockscreen_clock(self, *args):
self.app.popup_manager.clock_label.text = time.strftime("%I:%M %p")
self.app.popup_manager.clock_label.color = self.get_text_color()
def get_text_color(self):
if self.app.theme_cls.theme_style == "Dark":
return (1, 1, 1, 1)
else:
return (0, 0, 0, 1)
def reset_to_main_context(self, instance):
self.app.current_context = "main"
try:
self.app.inventory_manager.detach_from_parent()
self.app.label_manager.detach_from_parent()
except Exception as e:
logger.warn(e)
def create_md_raised_button(
self,
text,
on_press_action,
size_hint=(None, None),
font_style="Body1",
height=50,
):
button = MDRaisedButton(
text=text,
on_press=on_press_action,
size_hint=size_hint,
font_style=font_style,
height=height,
)
return button
def dismiss_popups(self, *popups):
for popup_attr in popups:
if hasattr(self, popup_attr):
try:
popup = getattr(self, popup_attr)
if popup._is_open:
popup.dismiss()
except Exception as e:
logger.warn(e)
def update_display(self):
self.app.order_layout.clear_widgets()
for item_id, item_info in self.app.order_manager.items.items():
item_name = item_info["name"]
price = item_info["price"]
item_quantity = item_info["quantity"]
item_total_price = item_info["total_price"]
item_discount = item_info.get("discount", {"amount": 0, "percent": False})
price_times_quantity = price * item_quantity
if type(item_total_price) is float:
if item_quantity > 1:
if float(item_discount["amount"]) > 0:
item_display_text = f"{item_name}"
price_display_text = f"${price_times_quantity:.2f} - {float(item_discount['amount']):.2f}\n = ${item_total_price:.2f}"
quantity_display_text = f"{item_quantity}"
else:
item_display_text = f"{item_name}"
price_display_text = f"${item_total_price:.2f}"
quantity_display_text = f"{item_quantity}"
else:
if float(item_discount["amount"]) > 0:
item_display_text = f"{item_name}"
price_display_text = f"${price_times_quantity:.2f} - {float(item_discount['amount']):.2f}\n = ${item_total_price:.2f}"
quantity_display_text = ""
else:
item_display_text = f"{item_name}"
price_display_text = f"${item_total_price:.2f}"
quantity_display_text = ""
else:
return
blue_line = MDBoxLayout(size_hint_x=1, size_hint_y=None, height=1)
blue_line.md_bg_color = (0.56, 0.56, 1, 1)
blue_line2 = MDBoxLayout(size_hint_x=1, size_hint_y=None, height=1)
blue_line2.md_bg_color = (0.56, 0.56, 1, 1)
blue_line3 = MDBoxLayout(size_hint_x=1, size_hint_y=None, height=1)
blue_line3.md_bg_color = (0.56, 0.56, 1, 1)
item_layout = GridLayout(
orientation="lr-tb", cols=3, rows=2, size_hint=(1, 1)
)
item_label_container = BoxLayout(size_hint_x=None, width=550)
item_label = MDLabel(text=f"[size=20]{item_display_text}[/size]")
item_label_container.add_widget(item_label)
spacer = MDLabel(size_hint_x=1)
# item_layout.add_widget(spacer)
price_label_container = BoxLayout(size_hint_x=None, width=150)
price_label = MDLabel(
text=f"[size=20]{price_display_text}[/size]", halign="right"
)
price_label_container.add_widget(price_label)
quantity_label_container = BoxLayout(size_hint_x=None, width=50)
quantity_label = MDLabel(text=f"[size=20]{quantity_display_text}[/size]")
quantity_label_container.add_widget(quantity_label)
item_layout.add_widget(item_label_container)
item_layout.add_widget(quantity_label_container)
item_layout.add_widget(price_label_container)
item_layout.add_widget(blue_line)
item_layout.add_widget(blue_line2)
item_layout.add_widget(blue_line3)
item_button = MDFlatButton(size_hint=(1, 1))
item_button.add_widget(item_layout)
item_button.bind(
on_press=lambda x, item_button=item_button, item_id=item_id: self.app.popup_manager.show_item_details_popup(
item_id, item_button
)
)
self.app.order_layout.add_widget(item_button)
# self.app.order_layout.add_widget(blue_line)
def update_financial_summary(self):
subtotal = self.app.order_manager.subtotal
total_with_tax = self.app.order_manager.calculate_total_with_tax()
tax = self.app.order_manager.tax_amount
discount = self.app.order_manager.order_discount
self.app.financial_summary_widget.update_summary(
subtotal, tax, total_with_tax, discount
)
Clock.schedule_once(self.app.financial_summary.update_mirror_image, 0.1)
def manual_override(self, instance):
current_time = time.time()
if current_time - self.app.override_tap_time < 0.5:
sys.exit(42)
self.app.override_tap_time = current_time
def set_primary_palette(self, color_name):
self.app.theme_cls.primary_palette = color_name
self.save_settings()
def toggle_dark_mode(self):
if self.app.theme_cls.theme_style == "Dark":
self.app.theme_cls.theme_style = "Light"
else:
self.app.theme_cls.theme_style = "Dark"
self.save_settings()
def on_add_or_bypass_choice(self, choice_text, barcode):
if choice_text == "Add Custom Item":
self.app.popup_manager.show_custom_item_popup(barcode)
elif choice_text == "Add to Database":
self.app.popup_manager.show_add_to_database_popup(barcode)
def check_dual_pane_mode(self):
flag_file_path = "dual_pane_mode.flag"
if os.path.exists(flag_file_path):
self.dual_pane_mode = True
os.remove(flag_file_path)
def create_main_layout(self, dual_pane_mode=False):
if dual_pane_mode:
dual_pane_layout = GridLayout(orientation="lr-tb", cols=2)
self.main_layout = GridLayout(
cols=1, spacing=5, orientation="lr-tb", row_default_height=60
)
self.top_area_layout = GridLayout(
cols=4, rows=1, orientation="lr-tb", row_default_height=60, size_hint_x=0.92
)
right_area_layout = GridLayout(rows=2, orientation="tb-lr", padding=50)
self.app.order_layout = GridLayout(
orientation="tb-lr",
cols=2,
rows=10,
spacing=5,
row_default_height=60,
row_force_default=True,
size_hint_x=1 / 2,
)
self.clock_layout = self.create_clock_layout()
self.top_area_layout.add_widget(self.clock_layout)
self.center_container = GridLayout(
rows=2, orientation="tb-lr", size_hint_y=0.01, size_hint_x=0.4
)
trash_icon_container = MDBoxLayout(size_hint_y=None, height=100)
_blank = BoxLayout(size_hint_y=0.9)
self.app.trash_icon = MDIconButton(
icon="trash-can",
pos_hint={"top": 0.75, "right": 0},
on_press=lambda x: self.confirm_clear_order(),
)
trash_icon_container.add_widget(self.app.trash_icon)
print_icon_container = MDBoxLayout(size_hint_y=None, height=100)
self.app.print_icon = MDIconButton(
icon="printer",
pos_hint={"top": 0.75, "right": 0},
on_press=lambda x: self.print_draft_receipt(),
)
print_icon_container.add_widget(self.app.print_icon)
calc_icon_container = MDBoxLayout(size_hint_y=None, height=100)
self.app.calc_icon = MDIconButton(
icon="calculator",
pos_hint={"top": 0.75, "right": 0},
on_press=lambda x: self.app.calculator.show_calculator_popup(),
)
calc_icon_container.add_widget(self.app.calc_icon)
save_icon_container = MDBoxLayout(size_hint_y=None, height=100)
# _blank = BoxLayout(size_hint_y=0.9)
self.app.save_icon = MDIconButton(
icon="content-save",
pos_hint={"top": 0.90, "right": 0},
on_press=lambda x: self.app.financial_summary.save_order(),
)
save_icon_container.add_widget(self.app.save_icon)
top_center_container = MDBoxLayout(orientation="vertical", size_hint_y=0.2)
# center_container.add_widget(trash_icon_container)
self.time_clock = MDFlatButton(
text="",
size_hint_y=0.2,
on_press=lambda x: self.app.popup_manager.open_clock_out_popup(),
)
time_clock_container = GridLayout(orientation="lr-tb", cols=2)
_blank2 = MDBoxLayout(size_hint_y=0.8)
clock_icon = MDIconButton(
icon="clock",
pos_hint={"top": 1},
on_press=lambda x: self.app.popup_manager.open_clock_out_popup(),
)
brightness_plus_container = MDBoxLayout(size_hint_y=None, height=100)
# _blank = BoxLayout(size_hint_y=0.9)
self.app.brightness_plus_icon = MDIconButton(
icon="plus",
# pos_hint={"top": 0.75, "right": 0},
on_press=lambda x: self.adjust_screen_brightness(direction="up"),
)
brightness_plus_container.add_widget(self.app.brightness_plus_icon)
brightness_minus_container = MDBoxLayout(size_hint_y=None, height=100)
# _blank = BoxLayout(size_hint_y=0.9)
self.app.brightness_minus_icon = MDIconButton(
icon="minus",
# pos_hint={"top": 0.75, "right": 0},
on_press=lambda x: self.adjust_screen_brightness(direction="down"),
)
brightness_minus_container.add_widget(self.app.brightness_minus_icon)
time_clock_container.add_widget(self.time_clock)
# time_clock_container.add_widget(clock_icon)
top_center_container.add_widget(time_clock_container)
top_center_container.add_widget(_blank2)
# self.center_container.add_widget(self.mirror_image)
self.center_container.add_widget(top_center_container)
self.center_container.add_widget(_blank)
self.top_area_layout.add_widget(self.center_container)
right_area_layout.add_widget(self.app.order_layout)
financial_button = self.create_financial_layout()
financial_layout = MDGridLayout(size_hint_y=0.2, orientation="lr-tb", cols=2)
financial_layout.add_widget(MDLabel(size_hint_x=0.4))
financial_layout.add_widget(financial_button)
right_area_layout.add_widget(financial_layout)
self.top_area_layout.add_widget(right_area_layout)
sidebar = BoxLayout(orientation="vertical", size_hint_x=0.07)
lock_icon = MDIconButton(
icon="lock", on_press=lambda x: self.trigger_guard_and_lock(trigger=True)
)
self.cost_overlay_icon = MDButtonLabel(
on_press=lambda x: self.app.popup_manager.show_cost_overlay(),
text="",
halign="center",
)
sidebar.add_widget(trash_icon_container)
sidebar.add_widget(save_icon_container)
sidebar.add_widget(print_icon_container)
sidebar.add_widget(brightness_plus_container)
sidebar.add_widget(brightness_minus_container)
sidebar.add_widget(self.cost_overlay_icon)
sidebar.add_widget(MDBoxLayout())
sidebar.add_widget(calc_icon_container)
sidebar.add_widget(lock_icon)
# sidebar.add_widget(trash_icon)
self.top_area_layout.add_widget(sidebar)
self.main_layout.add_widget(self.top_area_layout)
# main_layout.add_widget(sidebar)
button_layout = GridLayout(
cols=5,
spacing=20,
padding=20,
size_hint_y=0.1,
size_hint_x=1,
orientation="lr-tb",
)
btn_pay = MDFlatButton(
text="[b][size=40]PAY[/b][/size]",
on_press=self.app.button_handler.on_button_press,
padding=(8, 8),
font_name=self.font,
font_style="H6",
size_hint_x=None,
_min_width=225,
# _min_height=100,
# line_color="white",
)
btn_custom_item = MDFlatButton(
text="[b][size=40]CUSTOM[/b][/size]",
on_press=self.app.button_handler.on_button_press,
padding=(8, 8),
font_name=self.font,
font_style="H6",
size_hint_x=None,
_min_width=225,
# _min_height=100,
# line_color="white",
)
btn_inventory = MDFlatButton(
text="[b][size=40]SEARCH[/b][/size]",
on_press=self.app.button_handler.on_button_press,
padding=(8, 8),
font_name=self.font,
font_style="H6",
size_hint_x=None,
_min_width=225,
# _min_height=100,
# line_color="white",
)
btn_tools = MDFlatButton(
text="[b][size=40]TOOLS[/b][/size]",
on_press=self.app.button_handler.on_button_press,
# on_press=lambda x: self.app.db_manager.retrieve_attendence_log_entries(),
padding=(8, 8),
font_style="H1",
font_name=self.font,
size_hint_x=None,
_min_width=225,
# _min_height=100,
# line_color="white",
)
_blank3 = MDBoxLayout(size_hint_x=None, width=500)
button_layout.add_widget(_blank3)
button_layout.add_widget(btn_pay)
button_layout.add_widget(btn_custom_item)
button_layout.add_widget(btn_inventory)
button_layout.add_widget(btn_tools)
self.main_layout.add_widget(button_layout)
Clock.schedule_interval(self.check_inactivity, 10)
Clock.schedule_interval(self.app.barcode_scanner.check_for_scanned_barcode, 0.1)
self.base_layout = FloatLayout()
try:
bg_image = Image(source="images/test.jpg", fit_mode="fill")
self.base_layout.add_widget(bg_image)
except Exception as e:
logger.warn(e)
with self.base_layout.canvas.before:
Color(0.78, 0.78, 0.78, 1)
self.rect = Rectangle(
size=self.base_layout.size, pos=self.base_layout.pos
)
def update_rect(instance, value):
instance.rect.size = instance.size
instance.rect.pos = instance.pos
self.base_layout.bind(size=update_rect, pos=update_rect)
self.base_layout.add_widget(self.main_layout)
if dual_pane_mode:
blank_layout = self.app.popup_manager.show_lock_screen(dual_pane=True)
dual_pane_layout.add_widget(self.base_layout)
dual_pane_layout.add_widget(blank_layout)
return dual_pane_layout
else:
return self.base_layout
def create_clock_layout(self):
self.clock_layout = GridLayout(
orientation="tb-lr",
rows=6,
size_hint_x=0.75,
size_hint_y=1,
padding=(60, 0, 0, -10),
)
mirror_image_container = MDBoxLayout(size_hint=(None, 0.1), width=200)
self.mirror_image = Image(source="cropped_mirror_snapshot.png")
mirror_image_container.add_widget(self.mirror_image)
top_container = BoxLayout(orientation="vertical", size_hint_y=0.1, padding=10)
saved_orders_container = MDBoxLayout(
size_hint_y=1, orientation="vertical", spacing=20, padding=(0, 0, 0, 100)
)
self.saved_order_title_container = MDBoxLayout(orientation="vertical")
self.saved_order_title = MDLabel(
text="", adaptive_height=False, size_hint_y=None, height=50
)