-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1517 lines (1293 loc) · 61.7 KB
/
main.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 kivy
kivy.require('2.1.0')
from kivy.config import Config
#Config.set('graphics', 'width', 1080)
#Config.set('graphics', 'height', 2340)
#Config.set('input', 'mouse', 'mouse,multitouch_on_demand') # eliminate annoying circle drawing on right click
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
from kivy.uix.scrollview import ScrollView
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.dropdown import DropDown
from kivy.uix.textinput import TextInput
from kivy.properties import StringProperty, ListProperty, ObjectProperty
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.settings import SettingsWithSpinner, SettingPath
from functools import partial
from kivy.clock import Clock
from kivy.utils import platform
##from kivy.resources import resource_add_path, resource_find
from database import DataBase, CustomerDataBase
from update_settings import update_settings
from update_settings_string_path import update_settings as update_settings_string_path
import string
import random
import os
import time
import gc
from fpdf import FPDF
Builder.load_file('kvFiles/heading.kv')
Builder.load_file('kvFiles/previous_screen.kv')
Builder.load_file('kvFiles/help_page.kv')
Builder.load_file('kvFiles/summary_page.kv')
Builder.load_file('kvFiles/main_store_window.kv')
Builder.load_file('kvFiles/each_item_box_template.kv')
Builder.load_file('kvFiles/adding_new_item_window.kv')
Builder.load_file('kvFiles/updating_item_details_window.kv')
Builder.load_file('kvFiles/customer_info.kv')
Builder.load_file('kvFiles/customer_checkout.kv')
Builder.load_file('kvFiles/filechooser.kv')
NoCamera = True
if platform == 'android':
from android.permissions import request_permissions, Permission
request_permissions([
Permission.INTERNET,
Permission.CAMERA,
Permission.WRITE_EXTERNAL_STORAGE,
Permission.READ_EXTERNAL_STORAGE,
])
NoCamera = False
if not NoCamera: Builder.load_file('kvFiles/camera_window.kv')
class Heading(BoxLayout):
def __init__(self, sm, **kwargs):
super(Heading, self).__init__(**kwargs)
self.sm = sm
def GoToHelp(self):
self.sm.current_screen.HelpPage()
chars = string.ascii_uppercase + string.digits + string.ascii_lowercase
def RandomId(max_limit=6, min_limit=2):
size = random.randint(min_limit, max_limit)
return ''.join(random.choice(chars) for _ in range(size))
def WrongItemPopUp(popup_text):
content = Button(text='Close',
size_hint_y=0.1)
pop = Popup(title=popup_text,
content=content,
size_hint=(0.5,0.5),
auto_dismiss = True)
content.bind(on_press=pop.dismiss)
pop.open()
class QuitTheApp:
def QuitApp(self, instance):
App.get_running_app().stop()
def AppQuit(self):
#print(self.QuitApp('x'))
content = SetCustomerPopupBox()
pop = Popup(title='Quit App?',
content=content,
size_hint=(0.5,0.5),
auto_dismiss = False)
content.ids.CustomerPopupBox_btn1.bind(on_press=partial(self.QuitApp))
content.ids.CustomerPopupBox_btn1.bind(on_release=pop.dismiss)
content.ids.CustomerPopupBox_btn2.bind(on_release= pop.dismiss)
pop.open()
return
# https://stackoverflow.com/a/59805349
class Chooser(TextInput):
choiceslist = ListProperty([])
def __init__(self, sm, **kwargs):
self.choiceslist = kwargs.pop('choiceslist', []) # list of choices
super(Chooser, self).__init__(**kwargs)
self.multiline = False
self.cursor_color = [0,0,0,1]
self.size_hint = (0.9, 0.9)
self.halign = 'left'
self.bind(text=self.on_text)
self.bind(focus=self.on_focus)
self.dropdown = None
self.suggestion_text = None
self.sm = sm
def open_dropdown(self, *args):
if self.dropdown:
self.dropdown.open(self)
def keyboard_on_key_down(self, window, keycode, text, modifiers):
if self.suggestion_text and keycode[0] == ord('\r'): # enter selects current suggestion
self.suggestion_text = ' ' # setting suggestion_text to '' screws everything
self.text = self.values[0]
if self.dropdown:
self.dropdown.dismiss()
self.dropdown = None
else:
super(Chooser, self).keyboard_on_key_down(window, keycode, text, modifiers)
def on_focus(self, instance, text):
if self.dropdown:
self.dropdown.dismiss()
self.dropdown = None
self.dropdown = DropDown()
for val in self.choiceslist:
self.dropdown.add_widget(Button(text=val[0], size_hint_y=None, height=48, on_release=partial(self.do_choose, val[1])))
self.dropdown.open(self)
def on_text(self, chooser, text):
if self.dropdown:
self.dropdown.dismiss()
self.dropdown = None
if text == '':
return
values = []
for addr in self.choiceslist:
if addr[0].startswith(text):
values.append(addr)
self.values = values
if len(values) > 0:
if len(self.text) < len(self.values[0][0]):
self.suggestion_text = self.values[0][0][len(self.text):]
else:
self.suggestion_text = ' ' # setting suggestion_text to '' screws everything
self.dropdown = DropDown()
for val in self.values:
self.dropdown.add_widget(Button(text=val[0], size_hint_y=None, height=48, on_release=partial(self.do_choose, val[1])))
self.dropdown.open(self)
def do_choose(self, butt, instancee):
self.text = butt
if self.dropdown:
self.dropdown.dismiss()
self.dropdown = None
self.sm.current_screen.ShowItemDetails()
class ItemBoxTemplate(BoxLayout):
def __init__(self,db,sm,**kwargs):
super(ItemBoxTemplate, self).__init__(**kwargs)
self.db = db
self.sm = sm
def PopupCallBack(self, instance):
self.db.DeleteItem(self.ids.item_id.text)
self.parent.remove_widget(self)
def PopUp(self, popup_text):
content = SetCustomerPopupBox()
pop = Popup(title=popup_text,
content=content,
size_hint=(0.5,0.5),
auto_dismiss = False)
content.ids.CustomerPopupBox_btn1.bind(on_press=self.PopupCallBack)
content.ids.CustomerPopupBox_btn1.bind(on_release=pop.dismiss)
content.ids.CustomerPopupBox_btn2.bind(on_release=pop.dismiss)
pop.open()
return
def RemoveItem(self):
tmp_image_path = self.ids.image.source
if tmp_image_path != 'imgs/test.jpg':
try:
os.remove(tmp_image_path)
except:
self.PopUp("Warning: Can't delete image. Probably, image does not exist. Do you want to force delete the item?")
return
self.db.DeleteItem(self.ids.item_id.text)
self.parent.remove_widget(self)
self.sm.current_screen.ids.choose_item_id.choiceslist = self.db.id_list()
return
def ValidateEnteredItemNumber(self, new_item_numbers):
try:
new_item_numbers = int(new_item_numbers) if new_item_numbers is not None and len(new_item_numbers.strip())>0 else 0
except:
WrongItemPopUp("Count can't be fraction.")
return 0
if new_item_numbers < 0: WrongItemPopUp("Only positive number is allowed.")
return new_item_numbers
def CheckNegativeCount(self):
if self.CheckCountNegative:
WrongItemPopUp("Item stock already empty.")
else:
self.db.update_item_count(self.ids.item_id.text, self.updated_item_numbers)
self.ids.item_number.text = str(self.updated_item_numbers)
return 1
def buttonAddClicked(self, item_id, new_item_numbers):
new_item_numbers = self.ValidateEnteredItemNumber(new_item_numbers)
if new_item_numbers > 0:
self.updated_item_numbers, self.CheckCountNegative = self.db.validate_item_count(item_id, new_item_numbers, action='Add')
self.CheckNegativeCount()
self.ids.NumberOfItems.text = '1'
def buttonDeleteClicked(self, item_id, new_item_numbers):
new_item_numbers = self.ValidateEnteredItemNumber(new_item_numbers)
if new_item_numbers > 0:
self.updated_item_numbers, self.CheckCountNegative = self.db.validate_item_count(item_id, new_item_numbers, action='Delete')
self.CheckNegativeCount()
self.ids.NumberOfItems.text = '1'
def DetailsUpdateScreen(self):
get_screen_ids = self.sm.get_screen('details_update').ids
get_screen_ids.update_item_window_.text = 'Update item details'
get_screen_ids.update_item_remove_btn.disabled = True
get_screen_ids.update_item_save_btn.disabled = False
self.sm.current = 'details_update'
get_screen_ids.choose_item_id.text = self.ids.item_id.text
get_screen_ids.choose_item_id_box_id.disabled = True
get_screen_ids.update_item_details_data_box.disabled = False
#self.sm.current_screen.ShowItemDetails()
item = self.db.get_item_properties(self.ids.item_id.text)
get_screen_ids.update_item_name.text = item[1]
get_screen_ids.update_item_number.text = str(item[2])
get_screen_ids.update_item_cost.text = str(item[3])
get_screen_ids.update_image.source = item[4]
class TakePicture(Screen):
def __init__(self, sm, **kwargs):
super(TakePicture, self).__init__(**kwargs)
self.which_window = 'new_item_add'
self.sm = sm
def SaveImage(self):
timestr = time.strftime("%Y%m%d_%H%M%S")
self.image_pathh = os.path.join(App.get_running_app().image_storage_path, "IMG_{}.jpg".format(timestr))
iimg = self.ids.camera_img.export_as_image()
iimg.save(self.image_pathh)
##self.ids.camera_img.export_to_png(self.image_pathh)
self.NewImagePathUpdate(self.which_window)
def NewImagePathUpdate(self, which_window_):
all_ids_in_path = self.sm.get_screen(which_window_).ids
#if which_window_ == 'details_update': all_ids_in_path = all_ids_in_path.update_item_box_template.ids
all_ids_in_path.image_path.text = self.image_pathh
all_ids_in_path.image_path.disabled = True
self.ReturnBack()
def ReturnBack(self):
self.ids.camera_img.play = False
self.sm.current = self.which_window
self.sm.current_screen.ids.image_path.focus = not self.sm.current_screen.ids.image_path.focus
def QuitWholeApp(self):
QuitTheApp().AppQuit()
class Filechooser(BoxLayout):
def __init__(self, **kwargs):
super(Filechooser, self).__init__(**kwargs)
self.ids.let_choose.path = '/storage/emulated/0/' if platform == 'android' else '.'
class LetsSelectFile:
def __init__(self, sm, **kwargs):
self.sm = sm
def GetFilePath(self, filechooser, instance):
filepath_select = filechooser.ids.let_choose.selection[0]
self.sm.current_screen.ids.image_path.text = filepath_select
self.sm.current_screen.ids.image_path.focus = not self.sm.current_screen.ids.image_path.focus
def FileChooserClick(self):
content = Filechooser()
pop = Popup(title='Choose a file',
content=content,
size_hint=(0.9,0.8),
auto_dismiss = True)
content.ids.close_btn.bind(on_release=pop.dismiss)
content.ids.confirm_btn.bind(on_press=partial(self.GetFilePath, content))
content.ids.confirm_btn.bind(on_release=pop.dismiss)
pop.open()
return
class HelpPageScreen(Screen):
def __init__(self,sm,**kwargs):
super(HelpPageScreen, self).__init__(**kwargs)
self.sm = sm
self.ids.heading.add_widget(Heading(self.sm))
def HelpPage(self):
#sm.get_screen('help_page').ids.help_page.goto('additem')
self.sm.current = 'help_page'
def QuitWholeApp(self):
QuitTheApp().AppQuit()
class MainStoreWindow(Screen):
def __init__(self, db, sm, **kwargs):
super(MainStoreWindow, self).__init__(**kwargs)
self.db = db
self.sm = sm
self.ids.heading.add_widget(Heading(self.sm))
def HelpPage(self):
self.sm.get_screen('help_page').ids.help_page.goto('mainstore')
self.sm.current = 'help_page'
def InitializeScreen(self):
if 'choose_item_id' not in self.ids:
chooser = Chooser(self.sm,choiceslist=self.db.id_list(), hint_text='enter item name/id', size_hint=(0.5,None), height=30, pos_hint={'center_x':0.5, 'center_y':0.5})
self.ids.search_item_id.add_widget(chooser)
self.ids['choose_item_id'] = chooser
else:
self.ids.choose_item_id.choiceslist = self.db.id_list()
self.ids.choose_item_id.text = ''
def ShowItemDetails(self):
tmp_item_search = self.ids.choose_item_id.text.strip() + 'MainStore'
self.ids.item_scroll.scroll_to(self.ids.items_grid_layout.ids[tmp_item_search])
def AllItemGridLayout(self):
self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
self.layout.bind(minimum_height=self.layout.setter('height'))
self.ids['items_grid_layout'] = self.layout
self.ids.item_scroll.add_widget(self.layout)
def ShowItemTemplates(self):
self.AllItemGridLayout()
for item in self.items:
InstantItemBoxTemplate = ItemBoxTemplate(self.db, self.sm)
self.layout.ids[item[0]+'MainStore'] = InstantItemBoxTemplate
InstantItemBoxTemplate.ids.item_id.text = item[0]
InstantItemBoxTemplate.ids.item_name.text = item[1]
InstantItemBoxTemplate.ids.item_number.text = str(item[2])
InstantItemBoxTemplate.ids.item_cost.text = str(item[3])
InstantItemBoxTemplate.ids.image.source = item[4]
self.layout.add_widget(InstantItemBoxTemplate)
def AddItemBtn(self):
self.sm.current = 'new_item_add'
def DetailsUpdateScreen(self):
get_screen_ids = self.sm.get_screen('details_update').ids
get_screen_ids.update_item_window_.text = 'Update item details'
get_screen_ids.update_item_remove_btn.disabled = True
get_screen_ids.update_item_refresh_btn.disabled = False
get_screen_ids.choose_item_id_box_id.disabled = False
get_screen_ids.update_item_save_btn.disabled = False
get_screen_ids.update_item_details_data_box.disabled = False
self.sm.current = 'details_update'
def DeleteItemScreen(self):
get_screen_ids = self.sm.get_screen('details_update').ids
get_screen_ids.update_item_window_.text = 'Delete item'
get_screen_ids.update_item_save_btn.disabled = True
get_screen_ids.update_item_details_data_box.disabled = True
get_screen_ids.update_item_remove_btn.disabled = False
get_screen_ids.update_item_refresh_btn.disabled = True
self.sm.current = 'details_update'
def CustomerInfoPage(self):
self.sm.current = 'customer_info'
self.sm.current_screen.ids.checkout_button.disabled = True
self.sm.current_screen.ids.checkout_back_button.disabled = True
self.sm.current_screen.ids.checkout_item_box.disabled = True
self.sm.current_screen.ids.checkout_item_box_viewport.text = '***** This will show the checkout items list during checkout. *****'
def CustomerCheckOut(self):
self.sm.current = 'customer_checkout'
def ItemSummaryPage(self):
self.sm.current = 'summary_page'
def QuitWholeApp(self):
QuitTheApp().AppQuit()
class AddItemWindow(Screen):
item_namee = ObjectProperty()
item_id = ObjectProperty()
item_number = ObjectProperty()
item_cost = ObjectProperty()
image = ObjectProperty()
def __init__(self, db, sm, **kwargs):
super(AddItemWindow, self).__init__(**kwargs)
self.ItemSummaryList = {}
self.db = db
self.sm = sm
self.ids.heading.add_widget(Heading(self.sm))
def HelpPage(self):
self.sm.get_screen('help_page').ids.help_page.goto('additem')
self.sm.current = 'help_page'
def ID_list(self):
self.item_id_list_db = self.db.id_list()
return
def GenerateRandomId(self):
self.ids.item_id.text = RandomId(min_limit=5, max_limit=20)
def CameraClick(self):
if NoCamera:
WrongItemPopUp('Need camera permission. Enable camera permission from phone settings for this app.')
self.ids.camera_take_picture.disabled = True
else:
self.sm.get_screen('take_picture').which_window = 'new_item_add'
self.sm.current = 'take_picture'
def CheckLength_name(self, max_length = 20):
if len(self.ids.item_name.text.strip()) > max_length:
WrongItemPopUp(f'Maximum {max_length} character allowed.')
self.ids.item_name.do_undo()
def CheckLength_id(self, max_length = 20):
if len(self.ids.item_id.text.strip()) > max_length:
WrongItemPopUp(f'Maximum {max_length} character allowed.')
self.ids.item_id.do_undo()
def CheckItemsEligibility(self):
item_id, item_name, item_numbers, item_cost, item_img_path = \
self.item_id.text.strip(), self.item_namee.text.strip(), self.item_number.text.strip(),\
self.item_cost.text.strip(), self.image.text.strip()
#check_item_id_database = True if item_id in self.item_id_list_db else False
check_item_id_database = self.db.check_item_eligibility(item_id)
if not item_id:
WrongItemPopUp('Item id is mandatory. Supply an appropriate unique item id.')
return
if check_item_id_database or (item_id+'ItemsAdded' in self.ItemSummaryList):
WrongItemPopUp('Item id already exists. Provide new id.')
return
if not item_name:
WrongItemPopUp('Item name is mandatory. Supply an appropriate item name.')
return
if item_img_path.startswith('imgs/app/'):
WrongItemPopUp('Not allowed path. Access denied. Path is reserved for default app images only.')
return
if not item_numbers: item_numbers = '0'
if not item_img_path: item_img_path = 'imgs/test.jpg'
if not item_cost: item_cost = '0'
try:
item_numbers = int(item_numbers)
item_cost = float(item_cost)
except:
WrongItemPopUp('Item count and cost should be number.')
return
if item_img_path.split('.')[-1] not in ['png', 'jpg', 'jpeg']:
WrongItemPopUp('Only png and jpeg images are allowed.')
return
check_new_item = (item_id, item_name, item_numbers, item_cost, item_img_path)
KEY = check_new_item[0]+'ItemsAdded'
self.ItemSummaryList[KEY] = check_new_item
self.AddItemWidget(KEY)
self.reset()
return
def UpdateLists(self, myid): # This function is for AddItemWidgetLabelV2
pass
def Submit(self):
if len(self.ItemSummaryList) > 0:
self.db.add_new_items(list(self.ItemSummaryList.values()))
self.add_new_item_widget_main_store()
self.ReturnBack()
else:
WrongItemPopUp('Click on "Add to bucket" and then "Save".')
return
def add_new_item_widget_main_store(self):
get_all_items_screen_grid = self.sm.get_screen('all_items').ids.items_grid_layout
for item_ii in self.ItemSummaryList:
item_i = self.ItemSummaryList[item_ii]
InstantItemBoxTemplate = ItemBoxTemplate(self.db, self.sm)
InstantItemBoxTemplate.ids.item_id.text = item_i[0]
InstantItemBoxTemplate.ids.item_name.text = item_i[1]
InstantItemBoxTemplate.ids.item_number.text = str(item_i[2])
InstantItemBoxTemplate.ids.item_cost.text = str(item_i[3])
InstantItemBoxTemplate.ids.image.source = item_i[4]
get_all_items_screen_grid.add_widget(InstantItemBoxTemplate)
get_all_items_screen_grid.ids[item_i[0]+'MainStore'] = InstantItemBoxTemplate
def ReturnBack(self):
self.ItemSummaryList.clear()
self.reset()
self.sm.current = "all_items"
self.ids.add_item_label_box.clear_widgets()
def reset(self):
self.item_id.text = ''
self.item_namee.text = ''
self.item_number.text = '0'
self.item_cost.text = '0'
self.image.text = ' '
self.image.disabled = False
self.ids.camera_take_picture.disabled = False
self.ids.lets_choose_file.source = ''
def CutTexts(self, txt, max_limit = 15):
if len(txt) > max_limit:
txt = txt[:max_limit+1] + '...'
else:
txt = txt + ' '*(18-len(txt))
return txt
def AddItemWidget(self, KEY):
# https://stackoverflow.com/a/61707198
scroll_vp_height = self.ids.add_item_label.viewport_size[1]
scroll_height = self.ids.add_item_label.height
label = AddItemWidgetLabelV2(self.sm)
label.my_id = KEY
item = self.ItemSummaryList[KEY]
label.ids.add_item_widget_label.text = self.CutTexts(item[0]) + ': ' + self.CutTexts(item[1])
self.ids.add_item_label_box.add_widget(label)
if scroll_vp_height > scroll_height:
scroll_fact = self.ids.add_item_label.scroll_y
bottom = scroll_fact * (scroll_vp_height-scroll_height)
Clock.schedule_once(partial(self.adjust_scroll, bottom+label.height))
def adjust_scroll(self, bottom, dt):
scroll_vp_height = self.ids.add_item_label.viewport_size[1]
scroll_height = self.ids.add_item_label.height
self.ids.add_item_label.scroll_y = bottom / (scroll_vp_height-scroll_height)
def FileChooserClick(self):
content = LetsSelectFile(self.sm)
content.FileChooserClick()
def QuitWholeApp(self):
QuitTheApp().AppQuit()
class AddItemWidgetLabelV2(BoxLayout):
def __init__(self, sm, **kwargs):
super(AddItemWidgetLabelV2, self).__init__(**kwargs)
self.sm = sm
def CheckoutDeleteItemFromList(self):
# Do not change the order. The function should be called exactly in this order.
self.sm.current_screen.UpdateLists(self.my_id)
self.sm.current_screen.ItemSummaryList.pop(self.my_id)
self.parent.remove_widget(self)
class SummaryScreen(Screen):
def __init__(self, db, customer_db, sm, **kwargs):
super(SummaryScreen, self).__init__(**kwargs)
self.db = db
self.sm = sm
self.customer_db = customer_db
self.ids.heading.add_widget(Heading(self.sm))
def HelpPage(self):
self.sm.current = 'help_page'
def InitializeScreen(self):
self.summary_items = self.db.ReturnCompleteList()
self.summary_customers = self.customer_db.SummaryAllCustomers()
total_regi_item = len(self.summary_items)
total_regi_cus = len(self.summary_customers)
total_regi_stock = 0
total_regi_stock_cost = 0
total_item_sell_today = 0
total_item_sell_tomonth = 0
total_item_sell_today_worth = 0
total_item_sell_tomonth_worth = 0
self.ids.total_sellSummary_today.text ='--- All sell today/month (item: count) --- \n'
for stock in self.summary_items:
total_regi_stock += stock[2]
total_regi_stock_cost += stock[2]*stock[3]
total_item_sell_today += stock[5]
total_item_sell_tomonth += stock[6]
total_item_sell_today_worth += stock[5]*stock[3]
total_item_sell_tomonth_worth += stock[6]*stock[3]
if stock[5]>0 or stock[6]>0:
self.ids.total_sellSummary_today.text += 'o ' + stock[1][:15] + ': ' + str(stock[5]) + '/' + str(stock[6]) + '\n'
self.ids.total_registered_item.text = f'Total item catagory : {total_regi_item}'
self.ids.total_registered_stock.text = f'Total stock number : {total_regi_stock}'
self.ids.total_registered_customer.text = f'Total registered customer : {total_regi_cus}'
self.ids.total_registered_stock_cost.text = f'--------- \nAggregate assets worth : {total_regi_stock_cost}'
self.ids.total_sell_day.text = f'Total item sold today : {total_item_sell_today}'
self.ids.total_sell_month.text = f'Total item sold this month : {total_item_sell_tomonth}'
self.ids.total_income_day.text = f'Total income today : {total_item_sell_today_worth}'
self.ids.total_income_month.text = f'Total income this month : {total_item_sell_tomonth_worth}'
def PrintSummary(self):
if self.summary_items:
# Create a popup for orientation
pdf = FPDF(orientation='P', unit='mm', format='A4')
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(0, 10, txt='******** Welcome to Inventory Manager ********', ln=1, align='C')
Header_list = ['ID', 'NAME', 'COUNT', 'COST', 'IMAGE']
col_width = pdf.w / (float(len(Header_list)) + 0.5)
spacing = 1.5
row_height = pdf.font_size * spacing
pdf.cell(0, 10, txt='-------- Summary of all items in stock ---------', ln=1, align='C')
pdf.cell(0, 10, txt=time.strftime("%d-%m-%Y %H:%M:%S"), ln=1, align='R')
pdf.ln(row_height)
pdf.cell(0, 10, txt='='*80, ln=1, align='C')
for hdr_fld in Header_list:
pdf.cell(col_width, row_height, txt=str(hdr_fld), border=0)
pdf.ln(row_height)
pdf.cell(0, 10, txt='='*80, ln=1, align='C')
pdf.ln(row_height)
for item in self.summary_items:
for col in item:
tmp_txt = str(col)
if len(tmp_txt)>8: tmp_txt = tmp_txt[:9] + '...'
pdf.cell(col_width, row_height, txt=tmp_txt, border=0)
pdf.ln(row_height)
#row_item = ''.join([str(col).strip().rjust(20) + " " for col in item])
#pdf.cell(0, 10, txt = row_item, ln=1, align='C')
filepath_pdf = os.path.join(App.get_running_app().save_documents_dir, 'ItemsSummary_'+time.strftime("%Y%m%d_%H%M%S")+'.pdf')
pdf.output(filepath_pdf)
WrongItemPopUp(f"Items summary: {filepath_pdf}")
else:
WrongItemPopUp("No item exists.")
def ReturnBack(self):
self.sm.current = 'all_items'
def QuitWholeApp(self):
QuitTheApp().AppQuit()
class UpdateItemDetails(Screen):
def __init__(self, db, sm, **kwargs):
super(UpdateItemDetails, self).__init__(**kwargs)
self.db = db
self.sm = sm
self.ids.heading.add_widget(Heading(self.sm))
def HelpPage(self):
self.sm.get_screen('help_page').ids.help_page.goto('updateitem')
self.sm.current = 'help_page'
def InitializeScreen(self):
if 'choose_item_id' not in self.ids:
chooser = Chooser(self.sm, choiceslist=self.db.id_list(), hint_text='enter item name/id', size_hint=(0.5,None), height=30, pos_hint={'center_x':0.5, 'center_y':0.5})
self.ids.choose_item_id_.add_widget(chooser)
self.ids['choose_item_id'] = chooser
else:
self.ids.choose_item_id.choiceslist = self.db.id_list()
def FileChooserClick(self):
content = LetsSelectFile(self.sm)
content.FileChooserClick()
def ShowItemDetails(self):
item = self.db.get_item_properties(self.ids.choose_item_id.text.strip())
self.ids.update_item_name.text = item[1]
self.ids.update_item_number.text = str(item[2])
self.ids.update_item_cost.text = str(item[3])
self.ids.update_image.source = item[4]
if self.ids.new_image_path_here.source: self.ids.compare_old_image.source = item[4]
def CheckNumericStock(self, new_stock):
itemm_stock = None
if new_stock and new_stock.strip():
try:
itemm_stock = int(float(new_stock))
if itemm_stock < 0:
WrongItemPopUp('Number of items should be postive.')
return (None, True)
except:
WrongItemPopUp('Stock number should be a number.')
return (None, True)
return (itemm_stock, False)
def CheckNumericCost(self, new_cost):
itemm_cost = None
if new_cost and new_cost.strip():
try:
itemm_cost = float(new_cost)
if itemm_cost < 0:
WrongItemPopUp('Item cost should be postive.')
return (None, True)
except:
WrongItemPopUp('Item cost should be number.')
return (None, True)
return (itemm_cost, False)
def CheckItem_Update(self, new_stock, new_cost, new_name, new_image):
item_id = self.ids.choose_item_id.text.strip()
if len(item_id) > 0:
item = self.db.get_item_properties(item_id)
if item is None:
WrongItemPopUp('Item id does not exist.')
self.ResetDetails()
return
else:
WrongItemPopUp('Empty item id.')
self.ResetDetails()
return
new_name = None if len(new_name.strip())<1 else new_name.strip()
new_image = None if len(new_image.strip())<1 else new_image.strip()
newStock = self.CheckNumericStock(new_stock)
newCost = self.CheckNumericCost(new_cost)
if newStock[1] or newCost[1]:
return
new_item_details = [new_name, newStock[0], newCost[0], new_image, item[0]]
if all(x is None for x in new_item_details[:-1]):
WrongItemPopUp('Nothing to save.')
else:
for i, x in enumerate(new_item_details[:-1]):
if x is None:
new_item_details[i] = item[i+1]
elif i == 1:
new_item_details[i] += item[2]
# Updating database and main window widgets
self.db.UpdateNewItemDetails(tuple(new_item_details))
self.update_item_widget_main_store(new_item_details)
WrongItemPopUp("Update sucessful.")
self.RefreshScreen()
self.ResetDetails()
self.ids.choose_item_id.text = ''
return
def update_item_widget_main_store(self, new_item):
get_all_items_screen_grid = self.sm.get_screen('all_items').ids.items_grid_layout
need_update_ids = get_all_items_screen_grid.ids[new_item[-1]+'MainStore'].ids
need_update_ids.item_name.text = new_item[0]
need_update_ids.item_number.text = str(new_item[1])
need_update_ids.item_cost.text = str(new_item[2])
need_update_ids.image.source = new_item[3]
def ReturnBack(self):
self.ResetDetails()
self.ids.choose_item_id.text = ''
self.RefreshScreen()
self.sm.current = 'all_items'
def ResetDetails(self):
self.ids.update_item_name.text = ''
self.ids.update_item_number.text = ''
self.ids.update_item_cost.text = ''
self.ids.update_image.source = ''
def RefreshScreen(self):
self.ids.update_item_name_new.text = ''
self.ids.image_path.text = ' '
self.ids.update_item_number_new.text = ''
self.ids.update_item_cost_new.text = ''
self.ids.camera_take_picture.disabled = False
self.ids.new_image_path_here.source = ''
self.ids.compare_old_image.source = ''
def CameraClick(self):
if NoCamera:
WrongItemPopUp('Need camera permission. Enable camera permission from phone settings for this app.')
self.ids.camera_take_picture.disabled = True
else:
self.sm.get_screen('take_picture').which_window = 'details_update'
self.sm.current = 'take_picture'
def delete_item_widget_main_store(self, item_id):
get_all_items_screen_grid = self.sm.get_screen('all_items').ids.items_grid_layout
get_all_items_screen_grid.remove_widget(get_all_items_screen_grid.ids[item_id+'MainStore'])
def DeleteThings(self, item_id, item_name):
self.db.DeleteItem(item_id)
self.delete_item_widget_main_store(item_id)
self.ids.choose_item_id.choiceslist.remove((item_id, item_id))
self.ids.choose_item_id.choiceslist.remove((item_name, item_id))
self.ResetDetails()
self.ids.choose_item_id.text = ''
WrongItemPopUp("Delete sucessful.")
def PopupCallBackDeleteItemWindow(self, item_id, item_name, instance):
self.DeleteThings(item_id, item_name)
def PopUpDeleteItemWindow(self, popup_text, item_id, item_name):
content = SetCustomerPopupBox()
pop = Popup(title=popup_text,
content=content,
size_hint=(0.5,0.5),
auto_dismiss = False)
content.ids.CustomerPopupBox_btn1.bind(on_press=partial(self.PopupCallBackDeleteItemWindow, item_id, item_name))
content.ids.CustomerPopupBox_btn1.bind(on_release=pop.dismiss)
content.ids.CustomerPopupBox_btn2.bind(on_release= pop.dismiss)
pop.open()
return
def DeleteFullItem(self):
item_id = self.ids.choose_item_id.text.strip()
if len(item_id) > 0:
item = self.db.get_item_properties(item_id)
if item is None:
WrongItemPopUp('Item id does not exist.')
self.ResetDetails()
return
else:
WrongItemPopUp('Empty item id.')
self.ResetDetails()
return
if item[4] != 'imgs/test.jpg':
try:
os.remove(item[4])
except:
self.PopUpDeleteItemWindow("Can't delete image. Do you want to force delete?", item_id, item[1])
return
self.DeleteThings(item_id, item[1])
return
def QuitWholeApp(self):
QuitTheApp().AppQuit()
class CustomerCheckout(Screen):
def __init__(self, db, sm, **kwargs):
super(CustomerCheckout, self).__init__(**kwargs)
self.ItemSummaryList = {}
self.TrackItemCountList = {}
self.DoClean = True
self.sm = sm
self.db = db
self.ids.heading.add_widget(Heading(self.sm))
def HelpPage(self):
self.sm.get_screen('help_page').ids.help_page.goto('customercheckout')
self.DoClean = False
self.sm.current = 'help_page'
def InitializeScreen(self):
if 'choose_item_id' not in self.ids:
chooser = Chooser(self.sm,choiceslist=self.db.id_list(), hint_text='enter item name/id', size_hint=(0.5,None), pos_hint={'center_x':0.5, 'center_y':0.5})
self.ids.choose_item_id_.add_widget(chooser)
self.ids['choose_item_id'] = chooser
else:
self.ids.choose_item_id.choiceslist = self.db.id_list()
if self.DoClean:
self.ItemSummaryList.clear()
self.TrackItemCountList.clear()
def ShowItemDetails(self):
item = self.db.get_item_properties(self.ids.choose_item_id.text.strip())
self.ids.checkout_item_name.text = item[1]
self.ids.checkout_item_cost.text = str(item[3])
self.ids.checkout_image.source = item[4]
temp_item_count = item[2]
if item[0] in self.TrackItemCountList:
temp_item_count = self.TrackItemCountList[item[0]]
self.ids.checkout_item_number.text = str(temp_item_count)
def ValidateEnteredItemNumber(self, new_item_numbers):
try:
new_item_numbers = int(new_item_numbers) if new_item_numbers is not None and len(new_item_numbers.strip())>0 else 0
except:
WrongItemPopUp("Count can't be non-number or fraction.")
return 0
if new_item_numbers == 0:
WrongItemPopUp("No item to add in the list. Count should be greater than 0.")
return new_item_numbers
def ValidateInputDiscount(self, discount_percent):
discount_percent = discount_percent
if (discount_percent is not None) and (discount_percent.strip()):
try:
discount_percent = float(discount_percent)
if discount_percent < 0:
WrongItemPopUp('Price and discount should be postive.')
return None
except:
WrongItemPopUp("Price and discount should be number.")
return None
else:
discount_percent = 0
return discount_percent
def CalculateFinalCost(self, item_current_cost, discount_percent):
discount_amount = item_current_cost * discount_percent / 100
final_cost_per_item = item_current_cost - discount_amount
return final_cost_per_item
def AddClicked(self):
item_id = self.ids.choose_item_id.text.strip()
if len(item_id) > 0:
item = self.db.get_item_properties(item_id)
if item is None:
WrongItemPopUp('Item id does not exist.')
self.ResetDetails()
return
else:
WrongItemPopUp('Empty item id.')
self.ResetDetails()
return
checkout_item_count = self.ValidateEnteredItemNumber(self.ids.Checkout_count.text)
if checkout_item_count == 0: return 0
tmp_item_cnt = int(self.ids.checkout_item_number.text)
if int(item[2]) == 0:
if checkout_item_count < 0:
WrongItemPopUp("Trying to add extra item in original stock. Not allowed.")
else:
WrongItemPopUp("Item stock already empty.")
#self.RefreshScreen()
return 0
elif (tmp_item_cnt - checkout_item_count < 0):
if tmp_item_cnt == 0:
WrongItemPopUp("No more item of this catagory in stock. All are sold.")
else:
WrongItemPopUp("Not enough items in stock.")
#self.RefreshScreen()
return 0
elif (checkout_item_count < 0) and ((abs(checkout_item_count) + tmp_item_cnt) > int(item[2])):
WrongItemPopUp("Trying to add extra item in original stock. Not allowed.")
return 0
else:
discount_percent = self.ValidateInputDiscount(self.ids.Checkout_discount.text )
if discount_percent is not None:
final_cost = checkout_item_count * self.CalculateFinalCost(item[3], discount_percent)
for_later = (item[0], item[1], checkout_item_count, item[3], discount_percent, final_cost)
while True:
KEY = item[0] + '_' + RandomId(max_limit=10) + 'ItemsAdded'
if KEY not in self.ItemSummaryList: break
self.ItemSummaryList[KEY] = for_later
self.TrackItemCountList[item[0]] = tmp_item_cnt - checkout_item_count
else:
return 0
self.AddItemWidget(KEY)
self.RefreshScreen()
return 1
def UpdateLists(self, myid): # This function is for AddItemWidgetLabelV2
update_count = self.ItemSummaryList[myid]
if update_count[0] in self.TrackItemCountList:
self.TrackItemCountList[update_count[0]] += update_count[2]
def AddClickedPopup(self, item_name, item_count, item_price, item_discount):
item_name = item_name.strip() if (item_name and len(item_name.strip()) > 0) else 'Unknown'
checkout_item_count = self.ValidateEnteredItemNumber(item_count)
if checkout_item_count == 0: return 0
item_price = self.ValidateInputDiscount(item_price)
item_discount = self.ValidateInputDiscount(item_discount)
if (item_price is not None) and (item_discount is not None):
final_cost = checkout_item_count * self.CalculateFinalCost(item_price, item_discount)
for_later = ('unknown', item_name, checkout_item_count, item_price, item_discount, final_cost)
while True:
KEY = RandomId(max_limit=10) + 'ItemsAdded'
if KEY not in self.ItemSummaryList: break
self.ItemSummaryList[KEY] = for_later
else:
return 0
self.AddItemWidget(KEY)
return 1
def PopupCallBack(self, pop, instance):
name = pop.content.ids.ExtraItemCheckout_item_name.text
count = pop.content.ids.ExtraItemCheckout_item_count.text
price = pop.content.ids.ExtraItemCheckout_item_price.text