-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·1933 lines (1667 loc) · 90.1 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
#!/home/viktor/Dokumente/Kreschendo/Projekte/FoodManagerMD/vpython/bin/python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.metrics import dp
from kivy.storage.jsonstore import JsonStore
from kivy.utils import platform
from kivy.uix.screenmanager import Screen
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.boxlayout import BoxLayout
from kivymd.dialog import MDDialog
from kivymd.label import MDLabel
from kivymd.snackbar import Snackbar
from kivymd.theming import ThemeManager
from kivymd.textfields import MDTextField
from datetime import datetime
from math import floor, ceil
import os
from shutil import copyfile
# from kivy.core.window import Window
# Window.size = (600, 800)
class WelcomeScreen(Screen):
pass
class ViewItemsScreen(Screen):
pass
class RecipesScreen(Screen):
pass
class OverViewScreen(Screen):
pass
class InputItemsScreen(Screen):
pass
class HistoryScreen(Screen):
pass
class BuyingItemsScreen(Screen):
pass
class AddRecipesScreen(Screen):
pass
class AboutScreen(Screen):
pass
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout):
''' Adds selection and focus behaviour to the view. '''
pass
class SelectableItemLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableItemLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableItemLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_item
self.selected = is_selected
if is_selected:
selection_item = rv.data[index]['text']
fmapp.change_item_image_info()
class SelectableAddItemToRecipeLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableAddItemToRecipeLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableAddItemToRecipeLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection
self.selected = is_selected
if is_selected:
selection = rv.data[index]['text']
fmapp.show_item_weight_recipe()
class SelectableRecipeItemLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableRecipeItemLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableRecipeItemLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_iteminrecipe
self.selected = is_selected
if is_selected:
selection_iteminrecipe = rv.data[index]['text']
# fmapp.show_item_weight_recipe()
class SelectableRecipeLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableRecipeLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableRecipeLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_recipe
self.selected = is_selected
if is_selected:
selection_recipe = rv.data[index]['text']
fmapp.show_items_in_recipe()
class SelectableRecipeAtHomeLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableRecipeAtHomeLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableRecipeAtHomeLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_viarecipe
self.selected = is_selected
if is_selected:
selection_viarecipe = rv.data[index]['text']
class SelectableItemAtHomeLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableItemAtHomeLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableItemAtHomeLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_itemathome
self.selected = is_selected
if is_selected:
selection_itemathome = rv.data[index]['text']
fmapp.show_item_weight_used_home(selectedItem=selection_itemathome)
class SelectableRecipeAddCartLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableRecipeAddCartLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableRecipeAddCartLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_recipetocart
self.selected = is_selected
if is_selected:
selection_recipetocart = rv.data[index]['text']
class SelectableItemAddCartLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableItemAddCartLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableItemAddCartLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_itemtocart
self.selected = is_selected
if is_selected:
selection_itemtocart = rv.data[index]['text']
fmapp.show_cartitem_weight_used_home(selection_itemtocart)
class SelectableCartViewLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableCartViewLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableCartViewLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_cartview
self.selected = is_selected
if is_selected:
selection_cartview = rv.data[index]['text']
class SelectableInCartItemLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableInCartItemLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableInCartItemLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_incartitem
self.selected = is_selected
if is_selected:
selection_incartitem = rv.data[index]['text']
class SelectableStagedItemLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableStagedItemLabel, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableStagedItemLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
global selection_stageditem
self.selected = is_selected
if is_selected:
selection_stageditem = rv.data[index]['text']
# APP CLASS
class FoodManagerApp(App):
theme_cls = ThemeManager()
title = "Food Manager"
theme_cls.theme_style = 'Dark'
icon = 'img/groceries.png'
theme_cls.primary_palette = 'Teal'
if platform == 'android':
dir_path = ''
else:
dir_path = f'{os.getcwd()}/'
edit_recipe_bool = False
edit_item_bool = False
menu_items = [
{'viewclass': 'MDMenuItem',
'text': 'Settings'},
{'viewclass': 'MDMenuItem',
'text': 'Themes'}
]
def permission_exception(function):
"""
A decorator that wraps the passed in function and throws a permission denied warning.
"""
# @functools.wraps(function)
def wrapper(self, *args, **kwargs):
try:
function(self, *args, **kwargs)
except:
self.show_permission_warning()
return wrapper
@permission_exception
def create_dir_structure(self):
if not os.path.exists(self.dir_path + 'data/'):
os.makedirs(self.dir_path + 'data/')
if not os.path.exists(self.dir_path + 'img/'):
os.makedirs(self.dir_path + 'img/')
@permission_exception
def create_backup_dirs(self):
if platform == 'android':
if not os.path.exists('/storage/emulated/0/FoodManager'):
os.makedirs('/storage/emulated/0/FoodManager/')
@permission_exception
def back_up(self):
self.create_backup_dirs()
if platform == 'android':
if os.path.exists('data/athome.json'):
copyfile(
'data/athome.json',
'/storage/emulated/0/FoodManager/athome.json'
)
if os.path.exists('data/cartitemlist.json'):
copyfile(
'data/cartitemlist.json',
'/storage/emulated/0/FoodManager/cartitemlist.json'
)
if os.path.exists('data/foodmanager.json'):
copyfile(
'data/foodmanager.json',
'/storage/emulated/0/FoodManager/foodmanager.json'
)
if os.path.exists('data/recipes.json'):
copyfile(
'data/recipes.json',
'/storage/emulated/0/FoodManager/recipes.json'
)
if os.path.exists('/storage/emulated/0/FoodManager/history.json'):
copyfile(
'data/history.json',
'/storage/emulated/0/FoodManager/history.json'
)
#########################################################
# WELCOME
#########################################################
@permission_exception
def restore_files(self):
if platform == 'android':
if os.path.exists('/storage/emulated/0/FoodManager/athome.json'):
copyfile('/storage/emulated/0/FoodManager/athome.json',
'data/athome.json')
if os.path.exists('/storage/emulated/0/FoodManager/cartitemlist.json'):
copyfile('/storage/emulated/0/FoodManager/cartitemlist.json',
'data/cartitemlist.json')
if os.path.exists('/storage/emulated/0/FoodManager/foodmanager.json'):
copyfile('/storage/emulated/0/FoodManager/foodmanager.json',
'data/foodmanager.json')
if os.path.exists('/storage/emulated/0/FoodManager/recipes.json'):
copyfile('/storage/emulated/0/FoodManager/recipes.json',
'data/recipes.json')
if os.path.exists('/storage/emulated/0/FoodManager/history.json'):
copyfile('/storage/emulated/0/FoodManager/history.json',
'data/history.json')
self.show_snackbar('Data restored!')
self.init_data()
self.refresh_all()
self.dialog.dismiss()
def show_restore_warning_dialog(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text="Are you sure you want to overwrite your internal data with external data from /storage/emulated/0/FoodManager?",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="Warning: Restore data?",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=True)
self.dialog.add_action_button("Yes",
action=lambda *x: self.restore_files())
self.dialog.add_action_button("No",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
#########################################################
# OVERVIEW
#########################################################
def view_home_items(self):
homeitemsInput = [drow[0] +
' | ' +
str(drow[1]['TotalWeight']) +
' (=' + str(drow[1]['ItemWeight']) +
' x ' + str(drow[1]['Count']) +
')' for drow in self.athome.find()]
FoodWeight, FoodCost = 0, 0
for itm in homeitemsInput:
FoodWeight += float(itm.split(' | ')[1].split('g (=')[0])
FoodCost += (float(self.store.get(itm.split(' | ')[0])['FoodCost']) *
float(itm.split(' | ')[1].split('g (=')[0]) /
float(self.store.get(itm.split(' | ')[0])['FoodWeight']))
homeInfoView_item_strings = ['Cost: {}€'.format(round(float(FoodCost), 2)),
'Weight: {}g'.format(FoodWeight)]
self.root.ids.overview_screen.ids.homeInfoView.data = [{'text': str(x)} for x in homeInfoView_item_strings]
homeitemsInput.sort()
self.root.ids.overview_screen.ids.homeitems.data = [{'text': str(x)} for x in homeitemsInput]
# self.root.ids.overview_screen.ids.homeitems.item_strings = homeitemsInput
# self.root.ids.buyingitems_screen.ids.actualitemsatHome.item_strings = homeitemsInput
self.root.ids.buyingitems_screen.ids.actualitemsatHome.data = [{'text': str(x)} for x in homeitemsInput]
def view_cart_items(self):
cartlistInput = [drow[0] +
' | ' +
str(drow[1]['TotalWeight']) +
' (=' + str(drow[1]['ItemWeight']) +
' x ' + str(drow[1]['Count']) +
')' for drow in self.cartlist.find()]
FoodWeight, FoodCost = 0, 0
for itm in cartlistInput:
FoodWeight += float(itm.split(' | ')[1].split('g')[0])
FoodCost += round(float(self.store.get(itm.split(' | ')[0])['FoodCost']) * float(itm.split(
' | ')[1].split('g')[0]) / float(self.store.get(itm.split(' | ')[0])['FoodWeight']), 2)
cartInfoView_item_strings = ['Cost: {}€'.format(round(float(FoodCost), 2)),
'Weight: {}g'.format(FoodWeight)]
self.root.ids.overview_screen.ids.cartInfoView.data = [{'text': str(x)} for x in cartInfoView_item_strings]
cartlistInput.sort()
self.root.ids.overview_screen.ids.buyitems.data = [{'text': str(x)} for x in cartlistInput]
self.root.ids.buyingitems_screen.ids.cartDB.data = [{'text': str(x)} for x in cartlistInput]
# self.root.ids.overview_screen.ids.buyitems.item_strings = cartlistInput
# self.root.ids.buyingitems_screen.ids.cartDB.item_strings = cartlistInput
def view_recipe_items(self):
availabelRecipes = []
recipeInput = []
counter = []
for drow in self.recipe.find():
for ahome in self.athome.find():
for its in list(set(drow[1]['Items'])):
if (ahome[0] == its.split(' | ')[0] and float(ahome[1]['TotalWeight'].split('g')[0]) >= float(
its.split(' | ')[1].split('g')[0])):
recipeInput.append(drow[0])
counter.append(
floor(
float(ahome[1]['TotalWeight'].split('g')[0]) / float(
its.split(' | ')[1].split('g')[0])))
for rec in set(recipeInput):
indices = [i for i, x in enumerate(recipeInput) if x == rec]
mins = [counter[i] for i in indices]
for rec2 in self.recipe.find():
if rec2[0] == rec and len(set(rec2[1]['Items'])) == float(recipeInput.count(rec)):
availabelRecipes.append(rec + ' x ' + str(min(mins)))
availabelRecipes.sort()
self.root.ids.overview_screen.ids.recitems.data = [{'text': str(x)} for x in availabelRecipes]
self.root.ids.buyingitems_screen.ids.actualrecipesatHome.data = [{'text': str(x)} for x in availabelRecipes]
def view_recipe_cart_items(self):
availabelRecipes = []
recipeInput = []
counter = []
for drow in self.recipe.find():
for acart in self.cartlist.find():
for its in list(set(drow[1]['Items'])):
if (acart[0] == its.split(' | ')[0] and float(acart[1]['TotalWeight'].split('g')[0]) >= float(
its.split(' | ')[1].split('g')[0])):
recipeInput.append(drow[0])
counter.append(
floor(
float(acart[1]['TotalWeight'].split('g')[0]) / float(
its.split(' | ')[1].split('g')[0])))
for rec in set(recipeInput):
indices = [i for i, x in enumerate(recipeInput) if x == rec]
mins = [counter[i] for i in indices]
for rec2 in self.recipe.find():
if rec2[0] == rec and len(set(rec2[1]['Items'])) == float(recipeInput.count(rec)):
availabelRecipes.append(rec + ' x ' + str(min(mins)))
availabelRecipes.sort()
self.root.ids.overview_screen.ids.cartitemsrecipes.data = [{'text': str(x)} for x in availabelRecipes]
# self.root.ids.overview_screen.ids.cartitemsrecipes.item_strings = availabelRecipes
def view_na_recipes(self):
cartRecs = [cartitemrecs['text'].split(' x ')[0] for cartitemrecs in
self.root.ids.overview_screen.ids.cartitemsrecipes.data]
homeRecs = [homeitemrecs['text'].split(' x ')[0] for homeitemrecs in
self.root.ids.overview_screen.ids.recitems.data]
cartRecs.extend(homeRecs)
recs = [recipe[0] for recipe in self.recipe.find()]
narecipes_item_strings = list(set(recs).difference(cartRecs))
self.root.ids.overview_screen.ids.narecipes.data = [{'text': str(x)} for x in narecipes_item_strings]
def show_cart_warning_dialog(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text="Are you sure you want to delete all cart items you have added so far?",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="Delete Cart Items?",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=False)
self.dialog.add_action_button("Yes",
action=lambda *x: self.manual_cart_deletion())
self.dialog.add_action_button("No",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
def manual_cart_deletion(self):
self.refresh_cart_list()
self.dialog.dismiss()
self.refresh_all()
def show_home_warning_dialog(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text="Are you sure you want to delete all home items you have added so far?",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="Delete Home Items?",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=False)
self.dialog.add_action_button("Yes",
action=lambda *x: self.manual_home_deletion())
self.dialog.add_action_button("No",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
def manual_home_deletion(self):
self.refresh_home_list()
self.dialog.dismiss()
self.refresh_all()
def show_home_dialog(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text="These are all your items at home.",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="Home Items",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=False)
self.dialog.add_action_button("Dismiss",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
def show_cart_dialog(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text="These are all your items which you want to buy.",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="Cart Items",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=False)
self.dialog.add_action_button("Dismiss",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
#########################################################
# INPUT ITEMS
#########################################################
def add_item(self, strFood, strWeight, strCost):
if not self.edit_item_bool:
if strFood and strWeight and strCost:
try:
float(strWeight)
float(strCost)
# self.store.put(strFood.replace(" ", "_"),
# FoodWeight=strWeight,
# FoodCost=strCost,
# TimeID=datetime.strftime(datetime.now(), '%d.%m.%Y %H:%M:%S'))
self.store.put(strFood,
FoodWeight=strWeight,
FoodCost=strCost,
TimeID=datetime.strftime(datetime.now(), '%d.%m.%Y %H:%M:%S'))
self.show_snackbar('Added ' + strFood + ' !')
self.root.ids.inputitems_screen.ids.itemname.text = ""
self.root.ids.inputitems_screen.ids.itemweight.text = ""
self.root.ids.inputitems_screen.ids.itemcost.text = ""
except Exception as e:
self.show_input_datatype_error_dialog(str(e))
else:
self.show_input_incomplete_error_dialog()
else:
if strFood and strWeight and strCost:
try:
self.show_warning_update_item_dialog(strFood, strWeight, strCost)
except Exception as e:
self.show_input_datatype_error_dialog(str(e))
else:
self.show_input_incomplete_error_dialog()
self.edit_item_bool = False
def show_input_datatype_error_dialog(self, text):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text=text,
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="Datatype Input Error",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=False)
self.dialog.add_action_button("Dismiss",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
def show_input_incomplete_error_dialog(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text="Please fill out every cell!",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="Incomplete Input Error",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=False)
self.dialog.add_action_button("Dismiss",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
#########################################################
# VIEW ITEMS
#########################################################
def change_item_image_info(self):
if selection_item:
self.root.ids.viewitems_screen.ids.itemID.text = selection_item
FoodCost = self.store.get(selection_item)['FoodCost']
FoodWeight = self.store.get(selection_item)['FoodWeight']
self.root.ids.viewitems_screen.ids.infoView.text = ''.join(
['Cost: {}€\n'.format(FoodCost), 'Weight: {}g\n'.format(FoodWeight)])
def update_item(self):
foodInput = [drow[0] for drow in self.store.find()]
foodInput.sort()
self.root.ids.viewitems_screen.ids.dbOutput.data = [{'text': str(x)} for x in foodInput]
def delete_item(self):
try:
if selection_item:
self.show_snackbar(
'Removed ' + selection_item)
recipeToDelete = [rec[0] for rec in self.recipe.find(
) for itm in rec[1]['Items'] if itm.split(' | ')[0] == selection_item]
for drec in recipeToDelete:
self.recipe.delete(drec)
if self.athome.exists(selection_item):
self.athome.delete(selection_item)
if self.cartlist.exists(selection_item):
self.cartlist.delete(selection_item)
if self.history.exists(selection_item):
self.history.delete(selection_item)
if self.store.exists(selection_item):
self.store.delete(selection_item)
self.root.ids.viewitems_screen.ids.searchItems.text = ""
self.dialog.dismiss()
self.refresh_all()
except Exception as e:
self.dialog.dismiss()
self.show_warning_no_item_selected_to_delete()
def show_warning_no_item_selected_to_delete(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text="No item was selected to be deleted.",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="No item selected!",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=True)
self.dialog.add_action_button("Dismiss",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
def filter_items(self, searchText):
lfoodInput = [drow[0].lower() for drow in self.store.find()]
foodInput = [drow[0] for drow in self.store.find()]
indices = [i for i, s in enumerate(lfoodInput) if searchText.lower() in s]
fitems = [foodInput[i] for i in indices]
fitems.sort()
self.root.ids.viewitems_screen.ids.dbOutput.data = [{'text': str(x)} for x in fitems]
def show_warning_delete_item_dialog(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text="Deleting an item will delete recipes, cart items and home items in which the item is present! Are you sure you want to proceed?",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="Warning Item Deletion!",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=True)
self.dialog.add_action_button("Yes",
action=lambda *x: self.delete_item())
self.dialog.add_action_button("No",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
#########################################################
# EDIT Items
#########################################################
def edit_item(self):
try:
self.root.ids.inputitems_screen.ids.itemname.text = selection_item
self.root.ids.inputitems_screen.ids.itemweight.text = self.store.get(selection_item)['FoodWeight']
self.root.ids.inputitems_screen.ids.itemcost.text = self.store.get(selection_item)['FoodCost']
self.root.ids.scr_mngr.transition.direction = 'left'
self.root.ids.scr_mngr.current = 'input'
self.edit_item_bool = True
except Exception as e:
self.show_warning_no_item_selected_to_edit()
def show_warning_no_item_selected_to_edit(self):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text=f"Select an item in the list to be edited.",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title="No item selected!",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=True)
self.dialog.add_action_button("Dismiss",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
def show_warning_update_item_dialog(self, name, weight, cost):
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text=f"Should the item {selection_item} be updated? {selection_item} will also be updated in the recipes items, at home items and in cart items.",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title=f"Update item {selection_item}?",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=True)
self.dialog.add_action_button("Yes",
action=lambda *x: self.update_edit_item(name, weight, cost, False))
self.dialog.add_action_button("No",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
def show_warning_edited_item_already_exists(self, name, weight, cost):
self.dialog.dismiss()
content = MDLabel(font_style='Body1',
theme_text_color='Secondary',
text=f"The item {name} already exists in the database. Are you sure you want to overwrite it?",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(title=f"Item {name} already exist.",
content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=True)
self.dialog.add_action_button("Yes",
action=lambda *x: self.update_edit_item(name, weight, cost, True))
self.dialog.add_action_button("No",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
def update_edit_item(self, name, weight, cost, overwritebool=False):
if not self.store.exists(name) or overwritebool:
if selection_item:
self.show_snackbar('Updated ' + selection_item)
# Update in store
if self.store.exists(selection_item):
self.store.delete(selection_item)
self.store.put(name,
FoodWeight=weight,
FoodCost=cost,
TimeID=datetime.strftime(datetime.now(), '%d.%m.%Y %H:%M:%S'))
# Update at home
if self.athome.exists(selection_item):
totalweight = float(self.athome.get(selection_item)['TotalWeight'].split('g')[0])
weight = float(weight)
count = round(totalweight/weight,1)
self.athome.delete(selection_item)
self.athome.put(name,
TotalWeight=str(totalweight)+'g',
ItemWeight=str(weight)+'g',
Count=count,
TimeID=datetime.strftime(datetime.now(), '%d.%m.%Y %H:%M:%S'))
# Update in cart
if self.cartlist.exists(selection_item):
totalweight = float(self.cartlist.get(selection_item)['TotalWeight'].split('g')[0])
weight = float(weight)
count = round(totalweight/weight,1)
self.cartlist.delete(selection_item)
self.cartlist.put(name,
TotalWeight=str(totalweight)+'g',
ItemWeight=str(weight)+'g',
Count=str(count),
TimeID=datetime.strftime(datetime.now(), '%d.%m.%Y %H:%M:%S'))
# Update in recipe
##################
# Convert to a dict
recipe_hash_table = {}
temp_recipes = self.recipe.find()
weight = float(weight)
for hrec in temp_recipes:
recipe_hash_table[hrec[0]] = hrec[1]['Items']
found = False
for recipe_name, item_list in recipe_hash_table.items():
new_item_list = []
for it in item_list:
item_name, recipe_weight, item_weight, count = self.get_item_attributes_from_recipe_string(it)
if item_name == selection_item:
count = round(recipe_weight / weight, 1)
it = self.set_recipe_string_from_item_attributes(name, recipe_weight, weight, count)
found = True
new_item_list.append(it)
if found:
self.recipe.delete(recipe_name)
self.recipe.put(recipe_name,
Items=new_item_list,
TimeID=datetime.strftime(datetime.now(), '%d.%m.%Y %H:%M:%S'))
found = False
# Update in history
if self.history.exists(selection_item):
totalweight = float(self.history.get(selection_item)['TotalWeight'].split('g')[0])
weight = float(weight)
count = round(totalweight/weight,1)
self.history.delete(selection_item)
self.history.put(name,
TotalWeight=str(totalweight)+'g',
ItemWeight=str(weight)+'g',
Count=count,
TimeID=datetime.strftime(datetime.now(), '%d.%m.%Y %H:%M:%S'))