-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.py
More file actions
1865 lines (1564 loc) · 78.1 KB
/
api.py
File metadata and controls
1865 lines (1564 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import frappe
import json
from frappe.exceptions import DoesNotExistError, ValidationError, MandatoryError
@frappe.whitelist(allow_guest=True)
def create_purchase_order(data):
# Parse the JSON data if it is in string format
if isinstance(data, str):
data = json.loads(data)
results = []
if not data:
frappe.local.response['http_status_code'] = 400
results.append({"message": "No Purchase Order data provided", "status": "error"})
return results
for order in data:
try:
# Extract the purchase order name if available
purchase_order_name = order.get("name")
# Check if the purchase order exists
if purchase_order_name and frappe.db.exists("Purchase Order", purchase_order_name):
po_doc = frappe.get_doc("Purchase Order", purchase_order_name)
po_doc.update(order) # Update the Purchase Order document with the new data
po_doc.save(ignore_permissions=True)
action = "updated"
else:
# Create a new Purchase Order document
po_doc = frappe.get_doc({
"doctype": "Purchase Order",
**order
})
po_doc.insert(ignore_permissions=True)
po_doc.submit()
action = "created"
results.append({
"message": f"Purchase Order {action} successfully",
"purchase_order_id": po_doc.name,
"status": "success"
})
except MandatoryError as e:
frappe.log_error(message=str(e), title="Purchase Order Creation or Update Error")
frappe.local.response['http_status_code'] = 404
results.append({
"message": "Mandatory field missing / Not Found, Value Missing",
"error": str(e),
"status": "error"
})
except DoesNotExistError as e:
frappe.log_error(message=str(e), title="Purchase Order Creation or Update Error")
frappe.local.response['http_status_code'] = 400
results.append({
"message": "Resource not found",
"error": str(e),
"status": "error"
})
except Exception as e:
# Log error and append to results if there's an issue
frappe.log_error(message=str(e), title="Purchase Order Creation or Update Error")
results.append({
"message": "Error processing Purchase Order",
"purchase_order_id": purchase_order_name if purchase_order_name else "New",
"error": str(e),
"status": "error"
})
return results
import requests
import frappe
import json
from frappe import _
import json
from frappe.utils import cint
STANDARD_USERS = ("Guest", "Administrator")
from frappe.rate_limiter import rate_limit
from frappe.utils.password import get_password_reset_limit
from frappe.utils import (cint,get_formatted_email, nowdate, nowtime, flt, now_datetime)
from erpnext.accounts.utils import get_balance_on
from erpnext.stock.utils import get_stock_balance
from erpnext.stock.stock_ledger import get_previous_sle, get_stock_ledger_entries
from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice
from frappe.utils import add_to_date, now
from getpos.controllers import frappe_response
from erpnext.selling.doctype.customer.customer import get_customer_outstanding
from frappe.core.doctype.user.user import check_password
from getpos.controllers import frappe_response,handle_exception
@frappe.whitelist( allow_guest=True )
def login(usr, pwd):
try:
login_manager = frappe.auth.LoginManager()
login_manager.authenticate(user=usr, pwd=pwd)
login_manager.post_login()
user = frappe.get_doc('User', frappe.session.user)
if user.api_key and user.api_secret:
user.api_secret = user.get_password('api_secret')
else:
api_generate = generate_keys(frappe.session.user)
frappe.response["message"] = {
"success_key":1,
"message":"success",
"sid":frappe.session.sid,
"api_key":user.api_key if user.api_key else api_generate[1],
"api_secret": user.api_secret if user.api_secret else api_generate[0],
"username":user.username,
"email":user.email
}
except Exception as e:
frappe.clear_messages()
frappe.local.response["message"] = {
"success_key":0,
"message":"Incorrect username or password",
"error":e
}
return
def generate_keys(user):
user_details = frappe.get_doc('User', user)
api_secret = frappe.generate_hash(length=15)
# if not user_details.api_key:
api_key = frappe.generate_hash(length=15)
user_details.api_key = api_key
user_details.api_secret = api_secret
user_details.save(ignore_permissions=True)
if frappe.request.method == "GET":
frappe.db.commit()
return user_details.get_password("api_secret"), user_details.api_key
@frappe.whitelist(allow_guest=True)
@rate_limit(key='user', limit=get_password_reset_limit, seconds = 24*60*60, methods=['POST'])
def forgot_password(user):
if user=="Administrator":
return 'not allowed'
try:
user = frappe.get_doc("User", user)
if not user.enabled:
return 'disabled'
user.validate_reset_password()
reset_password(user,send_email=True)
return {
"success_key":1,
"message":"Password reset instructions have been sent to your email"
}
except frappe.DoesNotExistError:
frappe.clear_messages()
del frappe.local.response["exc_type"]
frappe.local.response["message"] = {
"success_key":0,
"message":"User not found"
}
from frappe.utils.data import sha256_hash
@frappe.whitelist(allow_guest=True)
def reset_password( user,send_email=False, password_expired=False):
from frappe.utils import random_string, get_url
# key = random_string(32)
key = frappe.generate_hash()
hashed_key = sha256_hash(key)
user.db_set("reset_password_key", hashed_key)
user.db_set("last_reset_password_key_generated_on", now_datetime())
url = "/update-password?key=" + key
if password_expired:
url = "/update-password?key=" + key + '&password_expired=true'
link = get_url(url)
if send_email:
password_reset_mail(user,link)
return link
@frappe.whitelist( allow_guest=True )
def password_reset_mail(user, link):
send_login_mail_2(user,("Password Reset"),
"reset_password", {"link": link}, now=True)
@frappe.whitelist()
def change_password(new_password,re_enter_password,current_password):
try:
user=frappe.get_doc("User",frappe.session.user)
if not new_password ==re_enter_password:
frappe.clear_messages()
frappe.local.response["message"] = {
"success_key": 0,
"message": "New Password and confirm password are not same"
}
frappe.local.response["http_status_code"] = 403
elif check_password(user.name,current_password, delete_tracker_cache=False):
user.new_password = new_password
user.flags.ignore_password_policy = True
user.save()
frappe.clear_messages()
frappe.local.response["message"] = {
"success_key": 1,
"message": "Password changed successfully"
}
frappe.local.response["http_status_code"] = 200
except Exception as e:
frappe.clear_messages()
frappe.local.response["message"] = {
"success_key": 0,
"message": "Please enter valid password"
}
frappe.local.response["http_status_code"] = 403
@frappe.whitelist( allow_guest=True )
def send_login_mail_2(user, subject, template, add_args, now=None):
"""send mail with login details"""
from frappe.utils.user import get_user_fullname
from frappe.utils import get_url
created_by = get_user_fullname(frappe.session['user'])
if created_by == "Guest":
created_by = "Administrator"
args = {
'first_name': user.first_name or user.last_name or "user",
'user': user.name,
'title': subject,
'login_url': get_url(),
'created_by': created_by
}
args.update(add_args)
sender = frappe.session.user not in STANDARD_USERS and get_formatted_email(frappe.session.user) or None
frappe.sendmail(recipients=user.email, sender=sender, subject = subject ,template= template , args = args, delayed=False)
@frappe.whitelist(allow_guest=True)
def get_abbr(string):
abbr = ''.join(c[0] for c in string.split()).upper()
return abbr
@frappe.whitelist(allow_guest=True)
def terms_and_conditions():
terms_and_condition = frappe.db.sql("""
SELECT terms
FROM `tabTerms and Conditions`
WHERE disabled = 0
""")[0][0]
return terms_and_condition
@frappe.whitelist(allow_guest=True)
def privacy_policy_and_terms():
privacy_policy_and_terms = frappe.db.sql("""
SELECT privacy_policy,terms_and_conditions
FROM `tabPrivacy Policy and Terms`
WHERE disabled = 0
""")
res = {"success_key":1,
"message":"success",
"Privacy_Policy":privacy_policy_and_terms[0][0],
"Terms_and_Conditions":privacy_policy_and_terms[0][1]}
if res["Privacy_Policy"]=="" or res["Terms_and_Conditions"]=="":
return {
"success_key":0,
"message":"no value found for privacy policy and terms"
}
return res
@frappe.whitelist()
def get_customer_list_by_hubmanager(hub_manager, last_sync = None):
res = frappe._dict()
base_url = frappe.db.get_single_value('nbpos Setting', 'base_url')
filters = {'hub_manager': hub_manager, "base_url": base_url}
conditions = "hub_manager = %(hub_manager)s "
if last_sync:
filters['last_sync'] = last_sync
conditions += "and modified >= %(last_sync)s"
customer_list = frappe.db.sql("""
SELECT
customer_name, email_id, mobile_no,
ward, ward_name, name, creation,
modified,disabled,
if((image = null or image = ''), null,
if(image LIKE 'http%%', image, concat(%(base_url)s, image))) as image,loyalty_program
FROM `tabCustomer`
WHERE {conditions}
""".format(conditions=conditions), values=filters, as_dict=1)
if len(customer_list) == 0:
frappe.clear_messages()
frappe.local.response["message"] = {
"success_key":1,
"message":"No values found for this hub manager"
}
else:
res["success_key"] = 1
res["message"] = "success"
res["customer_list"] = customer_list
return res
# Not using for Mobile App
@frappe.whitelist()
def get_item_list_by_hubmanager(hub_manager, last_sync = None):
res = frappe._dict()
item_list_based_stock_sync = []
if last_sync:
arr =last_sync.split(" ")
last_sync_date = arr[0]
if len(arr) < 2:
last_sync_time = '00:00:00'
else:
last_sync_time = arr[1]
base_url = frappe.db.get_single_value('nbpos Setting', 'base_url')
filters = {'hub_manager': hub_manager, "base_url": base_url}
conditions = "h.hub_manager = %(hub_manager)s "
item_list = get_item_list(filters, conditions)
for item in item_list:
if last_sync:
stock_detail = get_item_stock_balance(hub_manager, item.item_code, last_sync_date, last_sync_time)
if stock_detail:
item_list_based_stock_sync.append(item)
else:
stock_detail = get_item_stock_balance(hub_manager, item.item_code)
item.available_qty = stock_detail.get("available_qty")
item.stock_modified = str(stock_detail.get("posting_date"))+" "+str(stock_detail.get("posting_time"))
if last_sync:
filters['last_sync'] = last_sync
conditions += "and (i.modified >= %(last_sync)s or p.modified >= %(last_sync)s)"
item_list_syn_based = get_item_list(filters, conditions)
for i in item_list_based_stock_sync:
if i in item_list_syn_based:
item_list_syn_based.remove(i)
item_list = item_list_based_stock_sync + item_list_syn_based
for item in item_list:
stock_detail = get_item_stock_balance(hub_manager, item.item_code)
item.available_qty = stock_detail.get("available_qty")
item.stock_modified = str(stock_detail.get("posting_date"))+" "+str(stock_detail.get("posting_time"))
if len(item_list) == 0:
frappe.clear_messages()
frappe.local.response["message"] = {
"success_key":1,
"message":"No values found for this hub manager"
}
else:
res["success_key"] = 1
res["message"] = "success"
res["item_list"] = item_list
return res
else:
if len(item_list) == 0:
frappe.clear_messages()
frappe.local.response["message"] = {
"success_key":1,
"message":"No values found for this hub manager"
}
else:
res["success_key"] = 1
res["message"] = "success"
res["item_list"] = item_list
return res
@frappe.whitelist()
def get_item_list(filters, conditions, item_code = None):
return frappe.db.sql("""
SELECT
i.item_code, i.item_name, i.item_group, i.description,
i.has_variants, i.variant_based_on,
if((i.image = null or image = ''), null,
if(i.image LIKE 'http%%', i.image, concat(%(base_url)s, i.image))) as image,
p.price_list_rate, i.modified as item_modified, p.modified as price_modified
FROM `tabItem` i, `tabHub Manager Detail` h,`tabItem Price` p
WHERE h.parent = i.name and h.parenttype = 'Item'
and p.item_code = i.name and p.selling =1
and p.price_list_rate > 0
and {conditions}
""".format(conditions=conditions), values=filters, as_dict=1)
@frappe.whitelist()
def get_details_by_hubmanager(hub_manager):
try:
res = frappe._dict()
base_url = frappe.db.get_single_value('nbpos Setting', 'base_url')
filters = {'hub_manager': hub_manager, "base_url": base_url}
currency = frappe.get_doc("Global Defaults").default_currency
currency_symbol=frappe.get_doc("Currency",currency).symbol
conditions = "email = %(hub_manager)s "
hub_manager_detail = frappe.db.sql("""
SELECT
u.name, u.full_name,
u.email , if(u.mobile_no,u.mobile_no,'') as mobile_no,
if(u.user_image, if(u.user_image LIKE 'http%%', u.user_image, concat(%(base_url)s, u.user_image)), '') as image
FROM `tabUser` u
WHERE
{conditions}
""".format(conditions=conditions), values=filters, as_dict=1)
cash_balance = get_balance(hub_manager)
last_txn_date = get_last_transaction_date(hub_manager)
res["success_key"] = 1
res["message"] = "success"
res["name"] = hub_manager_detail[0]["name"]
res["full_name"] = hub_manager_detail[0]["full_name"]
res["email"] = hub_manager_detail[0]["email"]
res["mobile_no"] = hub_manager_detail[0]["mobile_no"]
res["hub_manager"] = hub_manager_detail[0]["name"]
res["series"] = ""
res["image"] = hub_manager_detail[0]["image"]
res["app_currency"] = currency_symbol
res["balance"] = cash_balance
res["last_transaction_date"] = last_txn_date if last_txn_date else ''
res["wards"] = []
return res
except Exception as e:
frappe.clear_messages()
frappe.local.response["message"] = {
"success_key":0,
"message":"No values found for this hub manager"
}
@frappe.whitelist()
def get_balance(hub_manager):
account = frappe.db.get_value('Account', {'hub_manager': hub_manager}, 'name')
account_balance = get_balance_on(account)
return account_balance if account_balance else 0.0
def add_items_in_order(sales_order, items, order_list):
sales_taxes = {}
for item in items:
item_tax_template = ""
if item.get('tax'):
item_tax_template = item.get('tax')[0].get('item_tax_template')
for tax in item.get('tax'):
if sales_taxes.get(tax.get('tax_type')):
tax_amount = tax.get('tax_amount') if tax.get('tax_amount') is not None else 0.0
sales_taxes[f"{tax.get('tax_type')}"] = flt(sales_taxes[f"{tax.get('tax_type')}"]) + flt(tax_amount)
else:
sales_taxes.update({f"{tax.get('tax_type')}": tax.get('tax_amount')})
sales_order.append("items", {
"item_code": item.get("item_code"),
"qty": item.get("qty"),
"rate": item.get("rate"),
"discount_percentage":100 if item.get("rate")==0 else 0,
"custom_parent_item":item.get("custom_parent_item"),
"custom_is_attribute_item":item.get("custom_is_attribute_item"),
"custom_is_combo_item":item.get("custom_is_combo_item"),
"allow_zero_evaluation_rate":item.get("allow_zero_evaluation_rate"),
"item_tax_template": item_tax_template if item_tax_template else "",
"custom_ca_id":item.get("custom_ca_id")
})
for key,value in sales_taxes.items():
sales_order.append("taxes", {"charge_type": "Actual", "account_head": key, "tax_amount": value, "description": key, })
if order_list.get('tax'):
for tax in order_list.get('tax'):
sales_order.append("taxes", {"charge_type": "Actual", "account_head": tax.get('tax_type'), "tax_amount": tax.get('tax_amount'),
"description": tax.get('tax_type'), "rate": tax.get('tax_rate')})
return sales_order
# def add_taxes(doc):
# all_taxes = frappe.get_all('Account',filters={'account_name':["in",["Output Tax SGST","Output Tax CGST"]]},
# fields=['name','account_name'])
# if all_taxes:
# for tax in all_taxes:
# doc.append('taxes',{'charge_type':'On Net Total',
# 'account_head': tax.name,
# 'rate':0,
# 'cost_center':'Main - NP',
# 'description': tax.account_name
# })
# return doc
def get_item_tax_template(name):
filters={'name': name}
tax = frappe.db.sql("""
SELECT
it.item_tax_template
FROM `tabItem` i , `tabItem Tax` it
WHERE i.name = it.parent and i.name = %(name)s
""",values=filters , as_dict = True)
if tax:
return tax
else:
return []
def get_combo_items(name):
combo_items = frappe.db.sql(''' Select
pi.parent_item,
pi.item_code ,
pi.item_name ,
pi.qty ,
pi.uom
from `tabSales Order` so , `tabPacked Item` pi
Where
so.name = %s and
so.name = pi.parent
''',(name), as_dict = True)
return combo_items
@frappe.whitelist()
def get_sales_order_list(hub_manager=None, page_no=1, from_date=None, to_date=None, mobile_no=None,docstatus=None):
res = frappe._dict()
base_url = frappe.db.get_single_value('nbpos Setting', 'base_url')
sales_history_count = cint(frappe.db.get_single_value('nbpos Setting', 'sales_history_count'))
limit = sales_history_count
conditions = ""
if mobile_no:
conditions+=f" and s.contact_mobile LIKE '%{str(mobile_no).strip()}%'"
if from_date and to_date:
conditions+=f" and s.transaction_date BETWEEN {frappe.db.escape(from_date)} AND {frappe.db.escape(to_date)}"
if docstatus:
conditions+="and s.docstatus={} ".format(docstatus)
page_no = cint(page_no) - 1
row_no = page_no * limit
conditions+=(f"ORDER BY s.creation DESC LIMIT {row_no}, {limit}")
order_list = frappe.db.sql(f"""
SELECT
s.name,s.docstatus, s.cost_center, s.transaction_date,
TIME_FORMAT(s.transaction_time, '%T') AS transaction_time,
s.ward, s.customer, s.customer_name,
s.total, s.order_type, s.custom_order_service_type,
s.custom_order_request,
s.custom_table_no, s.total_taxes_and_charges,
s.grand_total, s.mode_of_payment,
s.mpesa_no, s.contact_display AS contact_name,
s.contact_phone, s.contact_mobile, s.contact_email,
s.creation, s.loyalty_points, s.loyalty_amount,
s.discount_amount, s.additional_discount_percentage AS discount,
s.custom_redemption_account, s.coupon_code,
u.full_name AS hub_manager_name,
IF(c.image IS NULL OR c.image = '', NULL,
IF(c.image LIKE 'http%%', c.image, CONCAT('{base_url}', c.image))) AS image
FROM `tabSales Order` s
JOIN `tabUser` u ON s.hub_manager = u.name
JOIN `tabCustomer` c ON s.customer = c.name
WHERE s.hub_manager = {frappe.db.escape(hub_manager)}
{conditions}
""", as_dict=True)
for item in order_list:
if item.cost_center:
item['service_charge'] = frappe.db.get_value("Cost Center", item.cost_center, 'custom_service_charge')
service_charge_amount = frappe.db.sql("""
SELECT stc.tax_amount from `tabSales Order` so ,`tabSales Taxes and Charges` stc WHERE stc.parent=so.name and stc.charge_type="On Previous Row Total" and so.name = '{0}'
""".format(item.name),as_dict=1)
if service_charge_amount:
item['service_charge_amount'] = service_charge_amount[0]['tax_amount']
status_result = frappe.db.sql(f"""
SELECT si.status
FROM `tabSales Invoice` si
JOIN `tabSales Invoice Item` sii ON sii.parent = si.name
WHERE sii.sales_order = '{item.name}'
ORDER BY si.creation DESC
LIMIT 1
""", as_dict=True)
item['status'] = status_result[0]['status'] if status_result else "Sales Invoice is not created"
item_details = frappe.db.sql(f"""
SELECT
so.item_code, so.item_name, so.qty,
so.uom, so.rate, so.amount,
IF(i.image IS NULL OR i.image = '', NULL,
IF(i.image LIKE 'http%%', i.image, CONCAT(%s, i.image))) AS image
FROM `tabSales Order Item` so
JOIN `tabSales Order` s ON so.parent = s.name
JOIN `tabItem` i ON so.item_code = i.item_code
WHERE so.parent = %s
AND so.parenttype = 'Sales Order'
AND so.item_code != "Service Charge"
AND so.associated_item IS NULL
""", (base_url, item.name), as_dict=True)
associate_items = get_sub_items(item.name)
new_item_details = []
if associate_items:
for so_item in item_details :
so_item['sub_items'] = list(filter( lambda x : x.get("associated_item")== so_item.get("item_code"), associate_items ) )
new_item_details.append(so_item)
combo_items = get_combo_items(item.name)
for so_item in item_details:
so_item["combo_items"] = [x for x in combo_items if x.get("parent_item") == so_item.item_code]
item['items'] = item_details
if mobile_no:
number_of_orders = frappe.db.count('Sales Order', filters={
'hub_manager': hub_manager,
'contact_mobile': ('like', f'%{str(mobile_no).strip()}%')
})
else:
number_of_orders = get_sales_order_count(hub_manager)
number_of_orders = len(order_list) if from_date else number_of_orders
if not order_list and number_of_orders == 0:
frappe.clear_messages()
res["message"] = "No values found for this hub manager."
res["success_key"] = 1
else:
res["success_key"] = 1
res["message"] = "Success"
res['order_list'] = order_list
res['number_of_orders'] = number_of_orders
return res
@frappe.whitelist()
def get_sales_order_count(hub_manager):
number_of_orders = frappe.db.sql("""
SELECT
count(s.name)
FROM `tabSales Order` s, `tabUser` u
WHERE s.hub_manager = u.name and s.hub_manager = %s
and s.docstatus = 1
order by s.creation desc
""", (hub_manager))[0][0]
return number_of_orders
@frappe.whitelist()
def get_last_transaction_date(hub_manager):
account = frappe.db.get_value('Account', {'hub_manager': hub_manager, 'disabled': 0}, 'name')
transaction_date = frappe.db.get_list("GL Entry",
filters={
'account': account,
'voucher_type': ["!=",'Period Closing Voucher'],
'is_cancelled': 0
},
fields= ['posting_date'],
order_by = "posting_date desc",
as_list = 1
)
if transaction_date:
transaction_date = transaction_date[0][0]
else:
transaction_date = None
return transaction_date
@frappe.whitelist()
def get_item_stock_balance(hub_manager, item_code, last_sync_date=None, last_sync_time="00:00"):
res = frappe._dict()
warehouse = frappe.db.get_value('Warehouse', {'hub_manager': hub_manager}, 'name')
if last_sync_date and last_sync_time:
args = {
"item_code": item_code,
"warehouse":warehouse,
"posting_date": last_sync_date,
"posting_time": last_sync_time
}
last_entry = get_stock_ledger_entries(args, ">", "desc", "limit 1", for_update=False, check_serial_no=False)
if last_entry:
res['available_qty'] = get_stock_balance(item_code, warehouse, last_entry[0].posting_date, last_entry[0].posting_time)
res['posting_date'] = last_entry[0].posting_date
res['posting_time'] = last_entry[0].posting_time
else:
res['available_qty'] = get_stock_balance(item_code, warehouse)
args = {
"item_code": item_code,
"warehouse":warehouse,
"posting_date": nowdate(),
"posting_time": nowtime()
}
last_entry = get_previous_sle(args)
if last_entry:
res['posting_date'] = last_entry.get("posting_date")
res['posting_time'] = last_entry.get("posting_time")
return res
@frappe.whitelist()
def get_customer(mobile_no=None):
res=frappe._dict()
sql = frappe.db.sql(""" SELECT EXISTS(SELECT * FROM `tabCustomer` where mobile_no = '{0}')""".format(mobile_no))
result = sql[0][0]
if result == 1:
customer_detail = frappe.db.sql("""SELECT name,customer_name,customer_primary_contact,
mobile_no,email_id,primary_address,hub_manager,loyalty_program FROM `tabCustomer` WHERE
mobile_no = '{0}'""".format(mobile_no),as_dict=True)
loyalty_point_details = frappe._dict(
frappe.get_all(
"Loyalty Point Entry",
filters={
"customer": customer_detail[0]['name'],
"expiry_date": (">=", frappe.utils.getdate()),
},
group_by="company",
fields=["company", "sum(loyalty_points) as loyalty_points"],
as_list=1,
)
)
companies = frappe.get_all(
"Sales Invoice", filters={"docstatus": 1, "customer": customer_detail[0]['name']}, distinct=1, fields=["company"]
)
loyalty_points = 0
for d in companies:
if loyalty_point_details:
loyalty_points = loyalty_point_details.get(d.company)
conversion_factor = None
if customer_detail:
conversion_factor = frappe.db.get_value(
"Loyalty Program", {"name": customer_detail[0].loyalty_program}, ["conversion_factor"], as_dict=True
)
credit_limit = 0
outstanding_amount = 0
try:
customer = frappe.get_doc('Customer', customer_detail[0].name)
credit_limit=customer.custom_credit_limit
outstanding_amount = get_customer_outstanding(
customer_detail[0]['name'], frappe.get_doc("Global Defaults").default_company, ignore_outstanding_sales_order=False
)
except frappe.DoesNotExistError:
message = _("Customer not found.")
except Exception as e:
frappe.log_error(frappe.get_traceback(), _("Error fetching credit limit"))
message = _("An error occurred while fetching the credit limit.")
res['success_key'] = 1
res['message'] = "success"
res['customer'] = customer_detail
res['loyalty_points'] = loyalty_points
res['conversion_factor'] = conversion_factor.conversion_factor if conversion_factor else 0
res['loyalty_amount'] = loyalty_points * conversion_factor.conversion_factor if conversion_factor else 0
res['credit_limit'] = credit_limit
res['outstanding_amount'] = outstanding_amount
return res
else:
res["success_key"] = 0
res['mobile_no'] = mobile_no
res["message"] = "Mobile Number/Customer Does Not Exist"
return res
@frappe.whitelist()
def get_all_customer(search=None, from_date=None,customer_id=None):
res=frappe._dict()
customer = frappe.qb.DocType('Customer')
if search:
query = """SELECT name, customer_name, mobile_no, email_id
FROM `tabCustomer`
WHERE disabled = 0 AND mobile_no LIKE %s"""
params = ("%"+search+"%",)
else:
query = """SELECT name, customer_name, mobile_no, email_id , loyalty_program
FROM `tabCustomer`
WHERE disabled = 0 """
params = ()
if from_date:
query += "AND modified >= %s"
params += (from_date,)
if customer_id:
query += "AND name = %s"
params += (customer_id,)
customers = frappe.db.sql(query, params, as_dict=1)
for customer in customers:
loyalty_point_details = frappe._dict(
frappe.get_all(
"Loyalty Point Entry",
filters={
"customer": customer.name,
"expiry_date": (">=", frappe.utils.getdate()),
},
group_by="company",
fields=["company", "sum(loyalty_points) as loyalty_points"],
as_list=1,
)
)
companies = frappe.get_all(
"Sales Invoice", filters={"docstatus": 1, "customer": customer.name}, distinct=1, fields=["company"]
)
loyalty_points = 0
for d in companies:
if loyalty_point_details:
loyalty_points = loyalty_point_details.get(d.company)
customer['loyalty_points'] = loyalty_points
conversion_factor = None
conversion_factor = frappe.db.get_value(
"Loyalty Program", {"name": customer.loyalty_program}, ["conversion_factor"], as_dict=True
)
customer['conversion_factor'] = conversion_factor.conversion_factor if conversion_factor else 0
customer['loyalty_amount'] = loyalty_points * conversion_factor.conversion_factor if conversion_factor else 0
customer['credit_limit'] = 0
customer['outstanding_amount'] = 0
try:
customer['credit_limit']=customer.custom_credit_limit
customer['outstanding_amount'] = get_customer_outstanding(
customer.name, frappe.get_doc("Global Defaults").default_company, ignore_outstanding_sales_order=False
)
except frappe.DoesNotExistError:
message = _("Customer not found.")
except Exception as e:
frappe.log_error(frappe.get_traceback(), _("Error fetching credit limit"))
message = _("An error occurred while fetching the credit limit.")
if customer:
res['success_key'] = 1
res['message'] = "success"
res['customer'] = customers
return res
else:
res["success_key"] = 0
res["message"] = "No customer found"
res['customer']= customers
return res
@frappe.whitelist()
def create_customer():
customer_detail = frappe.request.data
customer_detail = json.loads(customer_detail)
res = frappe._dict()
try:
if customer_detail.get("mobile_no") and frappe.db.exists({"doctype":"Customer" , 'mobile_no': customer_detail.get("mobile_no") } ):
return frappe_response(400,"Customer already present with this mobile no.")
else:
customer = frappe.new_doc("Customer")
customer.customer_name = customer_detail.get("customer_name")
customer.mobile_no = customer_detail.get("mobile_no")
customer.email_id = customer_detail.get("email_id")
customer.customer_group = 'All Customer Groups'
customer.territory = 'All Territories'
customer.save(ignore_permissions=True)
frappe.db.commit()
res['success_key'] = 1
res['message'] = "success"
res["customer"] ={"name" : customer.name,
"customer_name": customer.customer_name,
"mobile_no" : customer.mobile_no,
"email_id":customer.email_id
}
return res
except Exception as e:
frappe.log_error(frappe.get_traceback(), "Error in create_customer")
return handle_exception(e)
def get_sub_items(name):
base_url = frappe.db.get_single_value('nbpos Setting', 'base_url')
filters={'name': name , 'base_url': base_url}
sub_items = frappe.db.sql("""
SELECT
soi.item_code , soi.item_name, soi.qty,soi.uom , soi.rate ,
soi.amount, soi.associated_item ,
if((image = NULL or image = ''), "",
if(image LIKE 'http%%', image, concat(%(base_url)s, image))) as image
FROM `tabSales Order` so , `tabSales Order Item` soi
WHERE so.name = soi.parent and so.name = %(name)s
""",values=filters , as_dict = True)
if sub_items:
return sub_items
else:
return ""
@frappe.whitelist()
def get_promo_code():
res = frappe._dict()
coupon_code = frappe.qb.DocType('Coupon Code')
pricing_rule = frappe.qb.DocType('Pricing Rule')
coupon_code =(
frappe.qb.from_(coupon_code).inner_join(pricing_rule) .on(coupon_code.pricing_rule == pricing_rule.name)
.select(coupon_code.name , coupon_code.coupon_code, coupon_code.pricing_rule,
coupon_code.maximum_use, coupon_code.used, coupon_code.description,
pricing_rule.valid_from , pricing_rule.valid_upto, pricing_rule.apply_on,
pricing_rule.price_or_product_discount, pricing_rule.min_qty,
pricing_rule.max_qty, pricing_rule.min_amt, pricing_rule.max_amt,
pricing_rule.rate_or_discount, pricing_rule.apply_discount_on,
pricing_rule.discount_amount, pricing_rule.rate, pricing_rule.discount_percentage )
.where( (pricing_rule.apply_on == 'Transaction')
& (pricing_rule.rate_or_discount == 'Discount Percentage') &
(pricing_rule.apply_discount_on == 'Grand Total') &
(pricing_rule.price_or_product_discount == "Price")
)
).run(as_dict=1)
if coupon_code:
res['success_key'] = 1
res['message'] = "success"
res['coupon_code'] = coupon_code
return res
else:
res["success_key"] = 0
res["message"] = "No Coupon Code in DB"
res['coupon_code']= coupon_code
return res
@frappe.whitelist(allow_guest=True)
def get_web_theme_settings():
theme_settings = frappe.get_doc("Web Theme Settings")
theme_settings_dict = {}
theme = frappe.get_meta("Web Theme Settings")
nbpos_setting = frappe.get_doc("nbpos Setting")
instance_url = nbpos_setting.base_url
image_fields = [
"web_logo_image",
"web_banner_image",
"web_outlet_details_banner_image",
"web_footer_logo"
]
for field in theme.fields:
value = theme_settings.get(field.fieldname)
if field.fieldname in image_fields and value:
if not value.startswith(instance_url):
value = f"{instance_url.rstrip('/')}/{value.lstrip('/')}"
theme_settings_dict[field.fieldname] = value
res = {
"data": theme_settings_dict
}
return res
@frappe.whitelist(allow_guest=True)
def get_theme_settings():
theme_settings = frappe.get_doc("Theme Settings")
theme_settings_dict = {}
theme = frappe.get_meta("Theme Settings")
nbpos_setting = frappe.get_doc("nbpos Setting")
instance_url = nbpos_setting.base_url
image_fields = [