-
Notifications
You must be signed in to change notification settings - Fork 2
/
database_fetch.py
1013 lines (857 loc) · 44.5 KB
/
database_fetch.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 datetime
import random
import firebase_admin
from firebase_admin import credentials, initialize_app, db, auth
from firebase_admin.exceptions import FirebaseError
from beem import sms
class FirebaseManager:
def __init__(self):
self.cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json")
self.app_initialized = False
self.database_url = 'https://farmzon-abdcb.firebaseio.com/'
def remove_comma(self, number):
new_number = str(number).replace(',', '')
return int(new_number)
def initialize_firebase(self):
firebase_admin._apps.clear()
if not self.app_initialized:
print('buyer')
try:
initialize_app(self.cred, {'databaseURL': self.database_url})
self.app_initialized = True
except FirebaseError as e:
print(f"Failed to initialize Firebase: {e}")
return "No Internet!"
def user_login(self, phone, password):
self.initialize_firebase()
if self.app_initialized:
try:
user_ref = db.reference("Gerente").child("Company").child(phone).child('User_Info')
user_data = user_ref.get()
if user_data and user_data['user_password'] == password:
return {
"message": "Login successful!",
"status": "200",
"user_name": user_data.get('user_name'),
"premium": user_data.get('premium'),
"payment_token": user_data.get('payment_token'),
"direct_url": user_data.get('direct_url'),
"subscription_date": user_data.get('subscription_date'),
"end_of_subscription": user_data.get('end_of_subscription')
}
else:
return {"message": "Invalid phone number or password!", "status": "404"}
except FirebaseError as e:
print(f"Failed to login user: {e}")
return {"message": "Login failed due to a server error!", "status": "500"}
else:
return {"message": "Firebase initialization failed!", "status": "500"}
def get_user_company_info(self, phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Retrieve company information
company_ref = db.reference("Gerente").child("Company").child(phone).child('Info_Company')
company_info = company_ref.get()
# Retrieve user information
user_ref = db.reference("Gerente").child("Company").child(phone).child('User_Info')
user_info = user_ref.get()
# Retrieve user PRoducts
products_ref = db.reference("Gerente").child('Company').child(phone).child('Products')
products_info = products_ref.get()
if company_info and user_info:
return {
"user_info": user_info,
"company_info": company_info,
"product_info": products_info
}
else:
return {"message": "User or company information not found!"}
except FirebaseError as e:
print(f"Failed to retrieve user company info: {e}")
return {"message": "Failed to retrieve data due to a server error!"}
else:
return {"message": "Firebase initialization failed!"}
def add_buyer(self, user_phone, buyer_phone, buyer_name, item_id, quantity):
self.initialize_firebase()
if self.app_initialized:
try:
# Fetch the price of the product using product_id
# Reference to the entire database
ref = db.reference("Gerente").child("Company").child(user_phone)
# Fetch all products to find the item
products_ref = ref.child("Products")
products = products_ref.get()
if products:
for product_id, product_data in products.items():
items_ref = products_ref.child(product_id).child("items")
item_ref = items_ref.child(item_id)
item_data = item_ref.get()
if item_data:
# Increment total_amount and item_count for the buyer
price = item_data.get("price", 0)
# Remove the item from the product
item_ref.delete()
# Retrieve buyer data
buyer_ref = db.reference("Gerente").child("Company").child(user_phone).child(
'Buyers').child(
buyer_phone)
buyer_data = buyer_ref.get()
if buyer_data:
# Buyer already exists, update item_count and total_amount
new_item_count = int(buyer_data.get("item_count", 0)) + int(quantity)
new_total_amount = int(buyer_data.get("total_amount", 0)) + int(
(int(price) * int(quantity)))
else:
# New buyer, initialize item_count and total_amount
new_item_count = quantity
new_total_amount = int(price) * int(quantity)
# Set or update buyer data
buyer_ref.set({
"buyer_name": buyer_name,
"product_id": product_id,
"item_count": new_item_count,
"total_amount": new_total_amount
})
# Update product_count for the product
new_product_count = product_data.get("products_count", 0) - 1
products_ref.child(product_id).update({
"products_count": new_product_count
})
# Increment the total number of buyers in Info_Company
company_info_ref = db.reference("Gerente").child("Company").child(user_phone).child(
'Info_Company')
company_info = company_info_ref.get()
if company_info:
total_buyers = company_info.get("Total_buyers", 0)
if not buyer_data:
total_buyers += 1 # Only increment total buyers if it's a new buyer
company_info_ref.update({"Total_buyers": total_buyers})
return "Buyer added and item removed successfully!"
except FirebaseError as e:
print(f"Failed to add buyer: {e}")
return "Failed to add buyer!"
else:
return "Firebase initialization failed!"
def get_buyers(self, user_phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the entire database
ref = db.reference("Gerente").child("Company").child(user_phone).child('Buyers')
# Fetch all buyers
buyers_data = ref.get()
if buyers_data:
buyers_list = []
for buyer_phone, buyer_info in buyers_data.items():
buyers_list.append({
"buyer_phone": buyer_phone,
"buyer_name": buyer_info.get("buyer_name", ""),
"product_id": buyer_info.get("product_id", ""),
"item_count": buyer_info.get("item_count", 0),
"total_amount": buyer_info.get("total_amount", 0)
})
return buyers_list
else:
return []
except FirebaseError as e:
print(f"Failed to fetch buyers: {e}")
return []
else:
return "Firebase initialization failed!"
def get_orders(self, user_phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Get the current date
current_date = datetime.datetime.now().strftime("%Y-%m-%d")
# Reference to the delivery orders for the user
delivery_orders_ref = db.reference("Gerente").child("DeliveryOrders").child(user_phone).child(
current_date)
# Fetch all orders for the current date
orders = delivery_orders_ref.get()
if orders:
return {'message': "Orders retrieved successfully!", 'status': '200', 'orders': orders}
else:
return {'message': "No orders found for today!", 'status': '200', 'orders': {}}
except FirebaseError as e:
print(f"Failed to retrieve orders: {e}")
return {'message': "Failed to retrieve orders!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def get_orders_custom(self, user_phone, custom_date):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's delivery orders on the custom date
delivery_orders_ref = db.reference("Gerente").child("DeliveryOrders").child(user_phone).child(
custom_date)
delivery_orders_data = delivery_orders_ref.get()
if delivery_orders_data:
orders = []
for order_id, order_info in delivery_orders_data.items():
orders.append({
"order_id": order_id,
"item_id": order_info.get("item_id", ""),
"buyer_phone": order_info.get("buyer_phone", ""),
"buyer_name": order_info.get("buyer_name", ""),
"product_id": order_info.get("product_id", ""),
"product_name": order_info.get("product_name", ""),
"price": order_info.get("price", 0),
"order_date": order_info.get("order_date", ""),
"status": order_info.get("status", "pending")
})
return {
'message': "Orders retrieved successfully",
'status': '200',
'orders': orders
}
else:
return {
'message': "No orders found for the specified date",
'status': '404',
'orders': []
}
except FirebaseError as e:
print(f"Failed to retrieve orders: {e}")
return {'message': "Failed to retrieve orders!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def get_orders_Interval(self, user_phone, custom_range):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's delivery orders
delivery_orders_ref = db.reference("Gerente").child("DeliveryOrders").child(user_phone)
delivery_orders_data = delivery_orders_ref.get()
if not delivery_orders_data:
return {
'message': "No orders found",
'status': '404',
'orders': []
}
# Get current date
today = datetime.datetime.now()
# Define date range based on custom_range
if custom_range == 'Today':
start_date = today.date()
end_date = today.date()
elif custom_range == 'Week':
start_date = (today - datetime.timedelta(days=today.weekday())).date() # Monday of the current week
end_date = today.date() # Today
elif custom_range == 'Month':
start_date = today.replace(day=1).date() # First day of the current month
end_date = today.date() # Today
else:
return {
'message': "Invalid range",
'status': '400',
'orders': []
}
filtered_orders = []
# Filter orders within the date range
for date_str, orders in delivery_orders_data.items():
order_date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
if start_date <= order_date <= end_date:
for order_id, order_info in orders.items():
filtered_orders.append({
'order_id': order_id,
'order_date': date_str,
'order_info': order_info
})
if not filtered_orders:
return {
'message': "No orders found in the specified range",
'status': '404',
'orders': []
}
return {
'message': "Orders retrieved successfully",
'status': '200',
'orders': filtered_orders
}
except FirebaseError as e:
print(f"Failed to retrieve orders: {e}")
return {'message': "Failed to retrieve orders!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def get_order_info(self, user_phone, order_id):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's delivery orders
delivery_orders_ref = db.reference("Gerente").child("DeliveryOrders").child(user_phone)
delivery_orders_data = delivery_orders_ref.get()
if delivery_orders_data:
for date, orders in delivery_orders_data.items():
if order_id in orders:
order_info = orders[order_id]
return {
'message': "Order information retrieved successfully",
'status': '200',
'order_info': {
"order_id": order_id,
"bill_payment": order_info.get("bill_payment", ""),
"item_id": order_info.get("item_id", ""),
"buyer_phone": order_info.get("buyer_phone", ""),
"buyer_name": order_info.get("buyer_name", ""),
"product_id": order_info.get("product_id", ""),
"product_name": order_info.get("product_name", ""),
"price": order_info.get("price", 0),
"order_date": order_info.get("order_date", ""),
"status": order_info.get("status", "pending")
}
}
return {
'message': "Order not found",
'status': '404',
'order_info': {}
}
except FirebaseError as e:
print(f"Failed to retrieve order information: {e}")
return {'message': "Failed to retrieve order information!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def initialize_delivery_order(self, user_phone, product_letter, buyer_phone, buyer_name, business_name):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's products
ref = db.reference("Gerente").child("Company").child(user_phone)
# Reference to the specific product using the product_letter
product_ref = ref.child("Products").child(str(product_letter).capitalize())
product_data = product_ref.get()
if product_data:
# Fetch the first available item under this product letter
items_ref = product_ref.child("items")
items_data = items_ref.get()
if items_data:
# Get the first item (since all items under the product_letter have the same price)
first_item_id = next(iter(items_data))
first_item_data = items_data[first_item_id]
price = self.remove_comma(first_item_data.get("price", 0))
product_name = product_data.get("product_name", "")
# Generate a unique order ID
order_id = f"order_{random.randint(1000000, 9999999)}"
current_date = datetime.datetime.now().strftime("%Y-%m-%d")
# Reference to the delivery orders
delivery_orders_ref = db.reference("Gerente").child("DeliveryOrders").child(user_phone).child(
current_date).child(order_id)
# Set order details
delivery_orders_ref.set({
"item_id": first_item_id,
"buyer_phone": buyer_phone,
"buyer_name": buyer_name,
"product_id": product_letter, # Use the product letter as the identifier
"product_name": product_name,
"price": price,
"order_date": current_date,
"status": "pending"
})
# Add buyer information
self.app_initialized = False
self.add_buyer(user_phone, buyer_phone, buyer_name, first_item_id, 1)
# Increment the total number of orders for today in Info_Company
company_info_ref = db.reference("Gerente").child("Company").child(user_phone).child(
'Info_Company')
company_info = company_info_ref.get()
if company_info:
# Fetch all today's orders and count them
today_orders_ref = db.reference("Gerente").child("DeliveryOrders").child(user_phone).child(
current_date)
today_orders = today_orders_ref.get()
today_orders_count = len(today_orders) if today_orders else 0
# Calculate the new total income
current_total_income = company_info.get("Total_income", 0)
new_total_income = current_total_income + int(self.remove_comma(price))
# Update the Info_Company with new order count and total income
company_info_ref.update({
"Today_orders": today_orders_count,
"Total_income": new_total_income
})
# Send a confirmation SMS to the buyer
from beem import sms
sms.send_sms(
buyer_phone,
f"Dear {buyer_name}, thank you for purchasing from {business_name}. "
f"Your order has been received and will be delivered shortly. "
f"Order No: {order_id}. Welcome to {business_name} {user_phone}!"
)
return {'message': f"Delivery order {order_id} initialized successfully!", 'status': '200',
'order_id': f'{order_id}'}
return {"message": "No items found under this product!"}
return {"message": "Product not found!"}
except FirebaseError as e:
print(f"Failed to initialize delivery order: {e}")
return {'message': "Failed to initialize delivery order!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def set_payment(self, payment_token, direct_url, user_phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's info
user_info_ref = db.reference("Gerente").child("Company").child(user_phone).child('User_Info')
# Update the direct_url and payment_token
user_info_ref.update({
"payment_token": payment_token,
"direct_url": direct_url
})
return {'message': "Payment information updated successfully!", 'status': '200'}
except FirebaseError as e:
print(f"Failed to update payment information: {e}")
return {'message': "Failed to update payment information!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def check_payment(self, payment_token, user_phone, user_name, pay_phone):
from payment import pesapal as PP
if PP.get_payment_status(payment_token)['status_code'] == 1:
premium = True
subscription_date = datetime.datetime.now().strftime("%Y-%m-%d")
expiring_date = (datetime.datetime.now() + datetime.timedelta(days=30)).strftime("%Y-%m-%d")
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's info
user_info_ref = db.reference("Gerente").child("Company").child(pay_phone).child('User_Info')
# Update the direct_url and payment_token
user_info_ref.update({
"premium": premium,
"subscription_date": subscription_date,
"end_of_subscription": expiring_date
})
from beem import sms
sms.send_sms(user_phone,
f"Dear {user_name} your subscription fee of 5,000 TZS was paid on {subscription_date} until {expiring_date} , KARIBU PORTAL!")
return {'message': "Premium user", 'status': '200'}
except FirebaseError as e:
print(f"Failed to update payment information: {e}")
return {'message': "Failed to update payment information!", 'status': '100'}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!", 'status': '100'}
else:
return {'message': "Firebase initialization failed!", 'status': '100'}
else:
return {'message': "Firebase initialization failed!", "status": '500'}
def special_buyer(self, user_phone, buyer_phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the buyer's data
buyer_ref = db.reference("Gerente").child("Company").child(user_phone).child('Buyers').child(
buyer_phone)
buyer_data = buyer_ref.get()
if buyer_data:
item_count = buyer_data.get("item_count", 0)
if item_count > 5:
# Update the special buyer status
buyer_ref.update({"special_buyer": True})
# Increment the total number of special buyers in Info_Company
company_info_ref = db.reference("Gerente").child("Company").child(user_phone).child(
'Info_Company')
company_info = company_info_ref.get()
if company_info:
special_buyers = company_info.get("Special_buyers", 0) + 1
company_info_ref.update({"Special_buyers": special_buyers})
return {'message': "Buyer updated to special status", 'status': '200'}
else:
return {'message': "Buyer does not meet the criteria for special status", 'status': '200'}
else:
return {'message': "Buyer not found", 'status': '404'}
except FirebaseError as e:
print(f"Failed to update special buyer: {e}")
return {'message': "Failed to update special buyer!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def get_special_buyers(self, user_phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the buyers data
buyers_ref = db.reference("Gerente").child("Company").child(user_phone).child('Buyers')
buyers_data = buyers_ref.get()
if buyers_data:
special_buyers = {phone: info for phone, info in buyers_data.items() if
info.get("special_buyer", False)}
return {
'message': "Special buyers retrieved successfully",
'status': '200',
'special_buyers': special_buyers
}
else:
return {
'message': "No buyers found",
'status': '404',
'special_buyers': {}
}
except FirebaseError as e:
print(f"Failed to retrieve special buyers: {e}")
return {'message': "Failed to retrieve special buyers!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def get_normal_buyers(self, user_phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the buyers data
buyers_ref = db.reference("Gerente").child("Company").child(user_phone).child('Buyers')
buyers_data = buyers_ref.get()
if buyers_data:
normal_buyers = {phone: info for phone, info in buyers_data.items() if
not info.get("special_buyer", False)}
return {
'message': "Normal buyers retrieved successfully",
'status': '200',
'normal_buyers': normal_buyers
}
else:
return {
'message': "No buyers found",
'status': '404',
'normal_buyers': {}
}
except FirebaseError as e:
print(f"Failed to retrieve normal buyers: {e}")
return {'message': "Failed to retrieve normal buyers!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def get_products_counts(self, user_phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's products
products_ref = db.reference("Gerente").child("Company").child(user_phone).child('Products')
products_data = products_ref.get()
if products_data:
product_counts = {product_id: product_info.get("products_count", 0) for product_id, product_info in
products_data.items()}
return {
'message': "Product counts retrieved successfully",
'status': '200',
'product_counts': product_counts
}
else:
return {
'message': "No products found",
'status': '404',
'product_counts': {}
}
except FirebaseError as e:
print(f"Failed to retrieve product counts: {e}")
return {'message': "Failed to retrieve product counts!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def get_products_count(self, user_phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's products
products_ref = db.reference("Gerente").child("Company").child(user_phone).child('Products')
products_data = products_ref.get()
if products_data:
product_details = {}
for product_id, product_info in products_data.items():
product_details[product_id] = {
"product_name": product_info.get("product_name", ""),
"product_price": product_info.get("product_price", 0),
"products_count": product_info.get("products_count", 0)
}
return {
'message': "Product details retrieved successfully",
'status': '200',
'product_details': product_details
}
else:
return {
'message': "No products found",
'status': '404',
'product_details': {}
}
except FirebaseError as e:
print(f"Failed to retrieve product details: {e}")
return {'message': "Failed to retrieve product details!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def deliver_order(self, user_phone, order_id, distance_price):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's delivery orders
delivery_orders_ref = db.reference("Gerente").child("DeliveryOrders").child(user_phone)
delivery_orders_data = delivery_orders_ref.get()
if delivery_orders_data:
for date, orders in delivery_orders_data.items():
if order_id in orders:
order_info = orders[order_id]
if order_info.get("status") == "delivered":
return {
'message': f"Order {order_id} is already delivered",
'status': '200',
'order_id': order_id
}
# Calculate the bill payment
item_price = order_info.get("price", 0)
bill_payment = (int(item_price) + distance_price) * 0.10
# Update the order status to deliver
delivery_orders_ref.child(date).child(order_id).update({
"status": "delivered",
"bill_payment": bill_payment
})
# Update the user's bill payment
user_info_ref = db.reference("Gerente").child("Company").child(user_phone).child(
'Info_Company')
user_info = user_info_ref.get()
new_bill_payment = 0
if user_info:
current_bill_payment = user_info.get("bill_payment", 0)
new_bill_payment = int(current_bill_payment) + int(bill_payment)
user_info_ref.update({
"bill_payment": new_bill_payment
})
return {
'message': f"Order {order_id} marked as delivered and bill payment updated",
'status': '200',
'order_id': order_id,
'new_bill_payment': new_bill_payment
}
return {
'message': "Order not found",
'status': '404',
'order_id': order_id
}
except FirebaseError as e:
print(f"Failed to update order status: {e}")
return {'message': "Failed to update order status!"}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!"}
else:
return {'message': "Firebase initialization failed!"}
def add_products(self, product_name, phone, product_letter, price):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the user's products
products_ref = db.reference("Gerente").child("Company").child(phone).child('Products').child(
product_letter)
# Set the product details
products_ref.set({
"products_count": 0,
"product_letter": product_letter,
"product_price": price,
"product_name": product_name
})
# Update the total number of products in the company info
company_info_ref = db.reference("Gerente").child("Company").child(phone).child('Info_Company')
company_info = company_info_ref.get()
if company_info:
total_products = company_info.get('Total_products', 0) + 1
company_info_ref.update({
"Total_products": total_products
})
return {'message': "Product added successfully!", 'status': '200'}
except FirebaseError as e:
print(f"Failed to add product: {e}")
return {'message': "Failed to add product!", 'status': '500'}
except Exception as e:
print(f"Unexpected error: {e}")
return {'message': "Unexpected error occurred!", 'status': '500'}
else:
return {'message': "Firebase initialization failed!", 'status': '500'}
def generate_item_id(self, product_letter):
prefix = random.randint(0000, 9999)
return f"{prefix}{product_letter}"
def add_items(self, phone, product_letter, price, count):
self.initialize_firebase()
if self.app_initialized:
try:
# Loop to add multiple items based on the count parameter
for _ in range(count):
# Generate a unique item ID using the product letter
item_id = self.generate_item_id(product_letter)
# Reference to the item in the database
item_ref = db.reference("Gerente").child("Company").child(phone).child("Products").child(
product_letter).child("items").child(item_id)
# Set the item details
item_ref.set({
"item_id": item_id,
"price": self.remove_comma(price)
})
# Reference to the product to update its item count
product_ref = db.reference("Gerente").child("Company").child(phone).child("Products").child(
product_letter)
product_info = product_ref.get()
if product_info:
new_products_count = product_info.get("products_count", 0) + 1
product_ref.update({
"products_count": new_products_count
})
return {
"message": f"{count} items added successfully!",
"status": "200"
}
except FirebaseError as e:
print(f"Failed to add items: {e}")
return {
"message": "Failed to add items!",
"status": "500"
}
except Exception as e:
print(f"Unexpected error: {e}")
return {
"message": "Unexpected error occurred!",
"status": "500"
}
else:
return {
"message": "Firebase initialization failed!",
"status": "500"
}
def add_quick_items(self, phone, price, name):
"""
Add a quick product item to Firebase with specified phone, price, and company name.
Args:
phone (str): The phone number of the poster.
price (str): The price of the item (commas removed).
name (str): The name of the company posting the item.
Returns:
dict: A dictionary containing a status code (int) and a message (str).
"""
# Initialize Firebase if not already initialized
self.initialize_firebase()
# Check if Firebase is initialized
if not self.app_initialized:
return {"status": 101, "message": "Firebase initialization failed"} # Status 101: Initialization failure
try:
# Define potential product letter options and generate a random item ID
alpha_choices = ['a', 'b', 'c', 'd']
product_letter = random.choice(alpha_choices)
item_id = self.generate_item_id(product_letter)
# Define the reference path in the Firebase database
item_ref = db.reference("Gerente").child("Quick_product").child(item_id)
# Prepare data for the item
item_data = {
"item_id": item_id,
"price": self.remove_comma(price), # Remove any commas from the price
"posted_by": phone,
"company_name": name,
"claimed": False,
"paid": False,
"claimed_by": "",
"claimed_id": f'{product_letter}{item_id}{product_letter}' # Generate claimed ID
}
# Set the data for the item in Firebase
item_ref.set(item_data)
# Return success message with status 200 (Success)
return {"status": 200, "message": f"Quick item {item_id} added successfully"}
except ValueError as ve:
# Specific error for value issues (e.g., wrong data types or missing fields)
return {"status": 102, "message": f"Value error: {str(ve)}"} # Status 102: Value error
except ConnectionError:
# Specific error for connectivity issues with Firebase
return {"status": 103,
"message": "Connection error. Please check your internet connection."} # Status 103: Connection error
except Exception as e:
# General exception handler for unexpected errors
return {"status": 500, "message": f"Unexpected error: {str(e)}"} # Status 500: General error
def fetch_quick_items(self, phone):
self.initialize_firebase()
if self.app_initialized:
try:
# Reference to the Quick_product section
quick_items_ref = db.reference("Gerente").child("Quick_product")
# Fetch all quick items
all_quick_items = quick_items_ref.get()
# If quick items exist, filter them by the seller's phone
if all_quick_items:
seller_items = {
item_id: details
for item_id, details in all_quick_items.items()
if details.get('posted_by') == phone
}
# Check if seller has any quick items posted
if seller_items:
return {
"status": "success",
"code": 200,
"message": "Quick items fetched successfully.",
"data": seller_items
}
else:
return {
"status": "error",
"code": 404,
"message": "No quick items found for this seller."
}
else:
return {
"status": "error",
"code": 404,
"message": "No quick items available in the database."
}
except Exception as e:
return {
"status": "error",
"code": 500,
"message": f"An error occurred while fetching quick items: {str(e)}"
}
else:
return {
"status": "error",
"code": 500,
"message": "Failed to initialize the app."
}
# x = FirebaseManager.fetch_quick_items(FirebaseManager(), '0715700411')
# print(x)
# x = FirebaseManager.get_products_count(FirebaseManager(), '0715700411')
# print(x)
# print(FirebaseManager.user_login(FirebaseManager(), '0715700411', '9060'))
# print(FirebaseManager.get_user_company_info(FirebaseManager(), '0715700411'))
# FirebaseManager.add_buyer(FirebaseManager(), '0715700411', '0788204328', 'Aqulline Mbuya', '7330341A', '1')
# print(FirebaseManager.initialize_delivery_order(FirebaseManager(), '0715700411', '2777963A', '0789934496', 'RayMundi',
# 'SomeHoes'))
# print(FirebaseManager.get_orders(FirebaseManager(), '0715700411'))
# print(FirebaseManager.get_orders_custom(FirebaseManager(), '0715700411', '2024-06-25'))
# print(FirebaseManager.get_orders_Interval(FirebaseManager(), '0715700411', 'Month'))
# x = FirebaseManager.get_buyers(FirebaseManager(), '0715700411')