-
Notifications
You must be signed in to change notification settings - Fork 0
/
DO_Processing1.py
1136 lines (1040 loc) · 52.6 KB
/
DO_Processing1.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 cv2
import numpy as np
from imutils.perspective import four_point_transform
import pytesseract
from pytesseract import Output
import re
from datetime import datetime
from datetime import date
import time
import mysql.connector as mysql
from secondTerminal import Term
import yaml
from fuzzywuzzy import fuzz
from dateutil.parser import parse
from regexGen import *
class DO:
def __init__(self, debugEnable, showQuantityCrop, insertConfirm):
with open('templateDO7.yaml', 'r') as file:
self.companyYaml = yaml.safe_load(file)
self.db = mysql.connect(
host="localhost",
user="lokcharming",
passwd="asdfasdf",
database="ERP"
)
self.myCursor = self.db.cursor()
self.board = np.zeros((360,900,3), np.uint8)
self.debugEnable = debugEnable
if self.debugEnable == True:
self.secondGnome = Term(width=105,height=31)
self.debugString = ''
self.showQuantityCrop = showQuantityCrop
self.insertConfirm = insertConfirm
self.po_number = ''
self.field = []
self.rePattern = []
self.queried = False
self.numFieldFound = 0
self.fieldFound = []
self.resStr = []
self.numField = 0
self.companyNameFoundFromPO = False
self.companyNameFromPO = ''
self.companyNameFoundFromYaml = False
self.companyNameFromYaml = ''
self.companyNameRegex =''
self.itemDetails = [] # item_id, quantity, part_number
self.itemDetected = [] # item_id, quantity, part_number
self.itemQuantityToBeDetected = [] # item_id, quantity, part_number
self.partNumberRegex = []
self.startSearchItem = False
self.startSearchQuantity = False
self.doNumFound = False
self.do_date = ''
self.dateFound = False
self.companyNameMatched = False
self.echoOnce = False
self.goodsreceiptsnotesExist = False
self.grnItemList = []
self.grnItemStringList = []
self.userName = 'Chia Ming Lok'
self.grn = {
"id": 'NULL',
"grn_number": 'NULL',
"po_number": 'NULL',
"supplier_id": 'NULL',
"supplier_do_number": 'NULL',
"supplier_inv_number": 'NULL',
"supplier_inv_date": 'NULL',
"currency_rate": 'NULL',
"recieve_by": 'NULL',
"status": 'NULL',
"created_at": 'NULL',
"updated_at": 'NULL',
"deleted_at": 'NULL',
"k1_id": 'NULL'
}
self.grnItem ={
"id": 'NULL',
"grn_id": 'NULL',
"po_item_id": 'NULL',
"wo_number": 'NULL',
"item_id": 'NULL',
"ordered_quantity": 'NULL',
"recieving_quantity": 'NULL',
"status": 'NULL',
"created_at": 'NULL',
"updated_at": 'NULL',
"deleted_at": 'NULL',
"supinvunitprice": 'NULL',
"supinvtotal": 'NULL'
}
self.siStringList = []
self.siList = []
self.stock_inventories ={
"id": 'NULL',
"inventory_id": 'NULL',
"safety_quantity": 'NULL',
"current_quantity": 'NULL',
"converted_quantity": 'NULL',
"location_id": 'NULL',
"location_id2": 'NULL',
"stock_item_category_id": 'NULL',
"uom_converter_id": 'NULL',
"change_log": 'NULL',
"created_at": 'NULL',
"updated_at": 'NULL',
"deleted_at": 'NULL'
}
self.silStringList = []
self.silList = []
self.stock_inventory_locations={
"id": 'NULL',
"stock_inventory_id": 'NULL',
"location_id": 'NULL',
"current_quantity": 'NULL',
"converted_quantity": 'NULL',
"inventory_id": 'NULL',
"created_at": 'NULL',
"updated_at": 'NULL',
"deleted_at": 'NULL'
}
self.sitStringList = []
self.sitList = []
self.stock_inventory_transactions={
"id": 'NULL',
"inventory_id": 'NULL',
"transaction_id": 'NULL',
"po_number": 'NULL',
"supplier_do": 'NULL',
"quantity": 'NULL',
"station_id": 'NULL',
"transaction_by": 'NULL',
"transaction_reference_id": 'NULL',
"stock_inventory_location_id": 'NULL',
"remark": 'NULL',
"created_at": 'NULL',
"updated_at": 'NULL',
"deleted_at": 'NULL'
}
def run(self, frame):
if self.companyNameMatched == False:
ocr_text = pytesseract.image_to_string(frame)
if self.companyNameFoundFromPO == False:
self.searchCompanyFromPO(ocr_text)
if self.companyNameFoundFromYaml == False:
self.searchCompanyFromYaml(ocr_text)
if self.companyNameFoundFromYaml == True and self.companyNameFoundFromPO == True:
if self.companyNameFromYaml == self.companyNameFromPO:
self.register(self.companyNameFromYaml)
self.cvBoardInitialize()
self.companyNameMatched = True
self.debugString += "Company Found From PO number matched with DO\n"
if self.debugEnable == True:
self.secondGnome.echo("Company Found From PO number matched with DO")
else:
self.debugString += "Company Found From PO number not matched with DO\n"
if self.debugEnable == True:
self.secondGnome.echo("Company Found from PO number not matched with DO")
self.companyNameFoundFromYaml = False
self.companyNameFoundFromPO = False
self.companyNameFromPO = ''
self.companyFromYaml = ''
else:
if (self.numFieldFound != self.numField and self.numField != 0) \
or self.dateFound == False:
#ocr_text = pytesseract.image_to_string(warped)
ocr_text = pytesseract.image_to_string(frame)
if self.dateFound == False:
self.searchDate(ocr_text)
else:
self.search(ocr_text)
else:
if self.echoOnce == False:
self.echoOnce = True
#self.startSearchQuantity = True
self.debugString += "Start Search Quantity\n"
if self.debugEnable == True:
self.secondGnome.echo("Start Search Quantity")
if self.startSearchQuantity:
self.getQuantity(frame)
if self.queried == False and (self.numFieldFound == self.numField and self.numField != 0) and self.dateFound == True:
self.debugString += "Checking Database...\n"
if self.debugEnable == True:
self.secondGnome.echo("checkDatabase")
self.checkDatabase()
def searchCompanyFromYaml(self, text):
self.companyID = 0 # my own index, not same with the database company id
for i in self.companyYaml['companies']:
comStr = re.search(i[1], text)
if comStr != None:
#print("Company id ", i[0])
#print("Company is ", i[2])
self.companyNameFromYaml = i[2]
self.companyNameFoundFromYaml = True
echoStr = 'Company Detected: '+self.companyNameFromYaml
self.debugString += echoStr
self.debugString += "\n"
if self.debugEnable == True:
self.secondGnome.echo(echoStr)
self.companyID = i[0]
break
#print(comStr.group())
#self.register(self.companyName)
#self.cvBoardInitialize(board)
def searchCompanyFromPO(self, text):
poLike = re.search('T-P[0,O]-(\d{8})',text)
if poLike != None:
query = 'select id, supplier_id from purchase_orders where po_number=\''+poLike.group(1)+'\''
self.myCursor.execute(query)
descr = self.myCursor.description
qResults = self.myCursor.fetchall()
if qResults:
self.mySqlTable(qResults, descr)
self.poId = qResults[0][0]
self.companyID = qResults[0][1]
query = 'select name from suppliers where id='+str(self.companyID)
self.myCursor.execute(query)
descr = self.myCursor.description
qResults = self.myCursor.fetchall()
if qResults:
self.mySqlTable(qResults, descr)
self.companyNameFromPO = qResults[0][0]
echoStr = "company Name From PO num = "+self.companyNameFromPO
self.debugString += echoStr
self.debugString += "\n"
if self.debugEnable == True:
self.secondGnome.echo(echoStr)
self.companyNameFoundFromPO = True
self.po_number = poLike.group(1)
else:
self.debugString += "no PO record\n"
if self.debugEnable == True:
self.secondGnome.echo("no PO record")
def register(self, compName):
for key, rePattern in self.companyYaml[compName]['regex'].items():
self.field.append(key)
self.rePattern.append(rePattern)
self.fieldFound.append(0)
self.numField += 1
self.resStr.append('')
def search(self, text):
for i in range(0, len(self.fieldFound)):
if self.fieldFound[i] == 0: # not found
find = re.search(self.rePattern[i], text)
if find != None:
if self.field[i] == 'do_num':
self.resStr[i] = self.companyYaml[self.companyNameFromYaml]['do_prefix'] + find.group(1)
self.doNumFound = True
else:
self.resStr[i] = find.group(1)
self.fieldFound[i] = 1
self.numFieldFound += 1
echoStr = self.field[i] + ': ' + self.resStr[i]
self.debugString += echoStr
self.debugString += "\n"
if self.debugEnable == True:
self.secondGnome.echo(echoStr)
self.cvBoardShowRes(i)
def searchDate(self, text):
for i in self.companyYaml['date_format']:
dateMatch = re.findall(i[0], text)
if dateMatch != None:
for j in dateMatch:
datestr = j
datestr = datestr.replace(" ", "")
try:
realDate = datetime.strptime(datestr, i[1]).date()
self.do_date = realDate.strftime('%Y-%m-%d')
echoStr = "do_date = "+self.do_date
self.debugString += echoStr
self.debugString += "\n"
if self.debugEnable == True:
self.secondGnome.echo(echoStr)
except ValueError:
pass
if self.do_date != '':
self.dateFound = True
def next(self):
self.debugString = ''
self.po_number = ''
self.field.clear()
self.rePattern.clear()
self.queried = False
self.numFieldFound = 0
self.fieldFound.clear()
self.resStr.clear()
self.numField = 0
self.doNumFound = False
self.companyNameFoundFromYaml = False
self.companyNameFromYaml = ''
self.companyNameFoundFromPO = False
self.companyNameFromPO = ''
self.itemDetails.clear()
self.itemDetected.clear()
self.itemQuantityToBeDetected.clear()
self.partNumberRegex.clear()
self.startSearchItem = False
self.startSearchQuantity = False
self.do_date = ''
self.dateFound = False
self.companyNameMatched = False
self.board = np.zeros((360,900,3), np.uint8)
self.echoOnce = False
if self.debugEnable == True:
self.secondGnome.send('clear')
self.grnItemList.clear()
self.grnItemStringList.clear()
self.goodsreceiptsnotesExist = False
self.sitStringList.clear()
self.siStringList.clear()
self.silStringList.clear()
self.sitList.clear()
self.siList.clear()
self.silList.clear()
def checkDatabase(self):
self.queried = True
Q1 = "select id, grn_number, po_number, supplier_id, \
supplier_do_date, recieve_by, created_at, updated_at\
from goodsreceiptsnotes where supplier_do_number='"
query = Q1+self.resStr[0]+'\''
self.debugString += query
self.debugString += "\n"
if self.debugEnable == True:
self.secondGnome.echo(query)
self.myCursor.execute(query)
descr = self.myCursor.description
qResults = self.myCursor.fetchall()
if qResults:
self.mySqlTable(qResults, descr)
if len(qResults) > 1:
self.debugString += "more than one record\n"
if self.debugEnable == True:
self.secondGnome.echo('more than one record')
else:
self.debugString += "Record Found\n"
if self.debugEnable == True:
self.secondGnome.echo('Record Found')
self.goodsreceiptsnotesExist = True
self.grn_id = qResults[0][0]
self.grn_number = qResults[0][1]
self.grn["id"] = self.grn_id
self.grn["grn_number"] = self.grn_number
self.grn["po_number"] = qResults[0][2]
self.grn["supplier_id"] = qResults[0][3]
self.grn["supplier_do_number"] = self.resStr[0]
self.grn["supplier_do_date"] = qResults[0][4]
self.grn["recieve_by"] = qResults[0][5]
self.grn["created_at"] = qResults[0][6]
self.grn["updated_at"] = qResults[0][7]
self.grnString = ''
for key, value in self.grn.items():
self.grnString += '{:^19}: {}\n'.format(key, value)
self.grnString = self.grnString[:self.grnString.rfind('\n')]
tempItemId = []
query = "select id, po_item_id, item_id, ordered_quantity, recieving_quantity,\
created_at, updated_at from goodrecieptsnoteitems where grn_id='"+str(self.grn_id)+"'"
#secondGnome.echo(query)
self.myCursor.execute(query)
exist = self.myCursor.fetchall()
if exist:
for result in exist:
grnItemString = ''
self.grnItem["id"] = result[0]
self.grnItem["grn_id"] = self.grn_id
self.grnItem["po_item_id"] = result[1]
self.grnItem["item_id"] = result[2]
tempItemId.append(result[2])
self.grnItem["ordered_quantity"] = result[3]
self.grnItem["recieving_quantity"] = result[4]
self.grnItem["created_at"] = result[5]
self.grnItem["updated_at"] = result[6]
self.grnItemList.append(self.grnItem)
for key, value in self.grnItem.items():
grnItemString += '{:^19}: {}\n'.format(key, value)
grnItemString = grnItemString[:grnItemString.rfind('\n')]
self.grnItemStringList.append(grnItemString)
for index, itemId in enumerate(tempItemId):
query = "select description from inventories where id="+itemId
self.myCursor.execute(query)
res = self.myCursor.fetchall()
self.grnItemStringList[index] = ' ' + res[0][0] + '\n' + self.grnItemStringList[index]
#stock_inventory_transactions
for index, inv_id in enumerate(tempItemId):
query = "select * from stock_inventory_transactions where\
po_number="+self.grn["po_number"]+\
" and inventory_id="+inv_id+\
" and supplier_do='"+self.grn["supplier_do_number"]+"'"
self.myCursor.execute(query)
res = self.myCursor.fetchall()
if res:
i = 0
sitString = ''
for key, value in self.stock_inventory_transactions.items():
value = res[0][i]
self.stock_inventory_transactions[key] = value
i += 1
sitString += '{:^19}: {}\n'.format(key, value)
sitString = sitString[:sitString.rfind('\n')]
self.sitList.append(self.stock_inventory_transactions)
self.sitStringList.append(sitString)
query = "select * from stock_inventories where inventory_id="+inv_id
self.myCursor.execute(query)
res = self.myCursor.fetchall()
if res:
i = 0
siString = ''
for key, value in self.stock_inventories.items():
value = res[0][i]
self.stock_inventories[key] = value
i += 1
siString += '{:^19}: {}\n'.format(key, value)
siString = siString[:siString.rfind('\n')]
self.sitList.append(self.stock_inventories)
self.siStringList.append(siString)
query = "select * from stock_inventory_locations\
where stock_inventory_id="+str(self.stock_inventories["id"])
self.myCursor.execute(query)
qres = self.myCursor.fetchall()
if qres:
i = 0
silString = ''
for key, value in self.stock_inventory_locations.items():
value = qres[0][i]
self.stock_inventory_locations[key] = value
i += 1
silString += '{:^19}: {}\n'.format(key, value)
silString = silString[:silString.rfind('\n')]
self.silList.append(self.stock_inventory_locations)
self.silStringList.append(silString)
else:
self.debugString += "No record found\n"
if self.debugEnable == True:
self.secondGnome.echo('No record found !!!')
self.debugString += "Loading item details base on PO ...\n"
if self.debugEnable == True:
self.secondGnome.echo('Loading item details based on PO ...')
self.loadItemDetails()
self.startSearchQuantity = True
self.goodsreceiptsnotesExist = False
"""
self.debugString += "Loading item details base on PO ...\n"
if self.debugEnable == True:
self.secondGnome.echo('Loading item details based on PO ...')
self.loadItemDetails()
self.startSearchItem = True
"""
def insertDatabase(self):
if self.goodsreceiptsnotesExist == False:
self.myCursor.execute("select id, grn_number from goodsreceiptsnotes order by grn_number desc limit 1")
qResults = self.myCursor.fetchall()
self.grn_id = qResults[0][0]+1
self.grn_number = str(int(qResults[0][1])+1)
self.debugString += "inserting goodsreceiptsnotes\n"
if self.debugEnable == True:
self.secondGnome.echo("inserting goodsreceiptsnotes")
nowDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
val = (self.grn_id, self.grn_number, self.do_date, self.resStr[0],\
self.poId, self.companyID, nowDateTime, nowDateTime)
self.debugString += "INSERT INTO goodsreceiptsnotes(id, grn_number, supplier_do_date, supplier_do_number, \
po_number, supplier_id, created_at, updated_at) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)\n"
self.debugString += str(val)
self.debugString += '\n'
if self.debugEnable == True:
self.secondGnome.echo(str(val))
Q3 = "insert into\
goodsreceiptsnotes(id, grn_number, supplier_do_date, supplier_do_number,\
po_number, supplier_id, created_at, updated_at)\
VALUES (%s,%s,%s,%s,%s,%s,%s,%s)"
self.myCursor.execute(Q3, val)
if self.insertConfirm == False:
self.db.commit()
#self.myCursor.execute("select id, grn_number from goodsreceiptsnotes order by grn_number desc limit 1")
#qResults = self.myCursor.fetchall()
#self.grn_id = qResults[0][0]
self.grn["id"] = self.grn_id
#else:
#self.grn["id"] = "AUTO_INCREMENT"
self.grn["grn_number"] = self.grn_number
self.grn["po_number"] = self.poId
self.grn["supplier_id"] = self.companyID
self.grn["supplier_do_number"] = self.resStr[0]
self.grn["supplier_do_date"] = self.do_date
self.grn["recieve_by"] = self.userName
self.grn["created_at"] = nowDateTime
self.grn["updated_at"] = nowDateTime
self.grnString = ''
for key, value in self.grn.items():
self.grnString += '{:^19}: {}\n'.format(key, value)
self.grnString = self.grnString[:self.grnString.rfind('\n')]
# insert grnItem only when grn not in database
# itemDetails[0] = purchase_order_items.id
# itemDetails[1] = purchase_order_items.item_id
# itemDetails[2] = purchase_order_items.quantity
# itemDetails[3] = inventories.part_number
# itemDetails[3] = inventories.description
#print("self.itemDetected")
#print(self.itemDetected)
first = True
firstStockInventoryTransaction = True
for index, item in enumerate(self.itemDetected):
if self.itemQuantityToBeDetected[index][0] == False:
query = "select id, grn_id, ordered_quantity, recieving_quantity from goodrecieptsnoteitems where po_item_id='"+str(item[0])+"'"
#secondGnome.echo(query)
self.myCursor.execute(query)
exist = self.myCursor.fetchall()
#print(exist)
if not exist:
if first == True:
self.myCursor.execute("select id from goodrecieptsnoteitems order by id desc limit 1")
qResults = self.myCursor.fetchall()
self.grn_item_id = qResults[0][0]+1
first = False
else:
# need to increment by ourselves because database is not committed until user confirm
self.grn_item_id += 1
self.debugString += "inserting goodrecieptsnoteitems\n"
if self.debugEnable == True:
self.secondGnome.echo("inserting goodrecieptsnoteitems")
nowDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#if self.insertConfirm == False:
Q6 = "insert into goodrecieptsnoteitems(id, grn_id, po_item_id, item_id,\
ordered_quantity,recieving_quantity, created_at, updated_at)\
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)"
val1 = (self.grn_item_id, self.grn_id, item[0], item[1], item[2], self.itemQuantityToBeDetected[index][1], nowDateTime, nowDateTime)
self.debugString += Q6
self.debugString += '\n'
self.debugString += str(val1)
self.debugString += '\n'
if self.debugEnable == True:
self.secondGnome.echo(str(val1))
self.myCursor.execute(Q6, val1)
if self.insertConfirm == False:
self.db.commit()
#self.myCursor.execute("select id from goodrecieptsnoteitems order by id desc limit 1")
#qResults = self.myCursor.fetchall()
#self.grn_item_id = qResults[0][0]
self.grnItem["id"] = self.grn_item_id
#else:
# self.grnItem["id"] = "AUTO_INCREMENT"
grnItemString = item[4] + '\n'
self.grnItem["grn_id"] = self.grn_id
self.grnItem["po_item_id"] = item[0]
self.grnItem["item_id"] = item[1]
self.grnItem["ordered_quantity"] = item[2]
self.grnItem["recieving_quantity"] = self.itemQuantityToBeDetected[index][1]
self.grnItem["created_at"] = nowDateTime
self.grnItem["updated_at"] = nowDateTime
self.grnItemList.append(self.grnItem)
for key, value in self.grnItem.items():
grnItemString += '{:^19}: {}\n'.format(key, value)
grnItemString = grnItemString[:grnItemString.rfind('\n')]
self.grnItemStringList.append(grnItemString)
# insert stock_inventory_transactions
if firstStockInventoryTransaction == True:
self.myCursor.execute("select id from stock_inventory_transactions order by id desc limit 1")
res = self.myCursor.fetchall()
self.stock_inventory_transactions_id = res[0][0] + 1
firstStockInventoryTransaction = False
else:
self.stock_inventory_transactions_id += 1
nowDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.stock_inventory_transactions["id"] = self.stock_inventory_transactions_id
self.stock_inventory_transactions["inventory_id"] = self.grnItem["item_id"]
self.stock_inventory_transactions["transaction_id"] = 1 # do is to be 1
self.stock_inventory_transactions["po_number"] = self.grn["po_number"]
self.stock_inventory_transactions["supplier_do"] = self.grn["supplier_do_number"]
self.stock_inventory_transactions["quantity"] = self.grnItem["recieving_quantity"]
self.stock_inventory_transactions["station_id"] = 'NULL'
self.stock_inventory_transactions["transaction_by"] = 'NULL' # user code
self.stock_inventory_transactions["transaction_reference_id"] = 'NULL'
self.stock_inventory_transactions["stock_inventory_location_id"] = 'NULL'
self.stock_inventory_transactions["remark"] = 'NULL'
self.stock_inventory_transactions["created_at"] = nowDateTime
self.stock_inventory_transactions["updated_at"] = nowDateTime
self.stock_inventory_transactions["deleted_at"] = 'NULL'
self.sitList.append(self.stock_inventory_transactions)
sitString = ''
query = "INSERT INTO stock_inventory_transactions("
valS="("
valT=[]
for key, value in self.stock_inventory_transactions.items():
query += key
query += ", "
valS += "%s,"
valT.append(value)
sitString += '{:^19}: {}\n'.format(key, value)
sitString = sitString[:sitString.rfind('\n')]
self.sitStringList.append(sitString)
valT = tuple(valT)
query = query[:-2]
valS = valS[:-1]
query += ") VALUES"
query += valS
query += ")"
self.myCursor.execute(query, valT)
if self.insertConfirm == False:
self.db.commit()
# Update stock_inventories
query = "select * from stock_inventories where inventory_id="+self.grnItem["item_id"]
self.myCursor.execute(query)
res = self.myCursor.fetchall()
if res:
i = 0
for key, value in self.stock_inventories.items():
value = res[0][i]
i += 1
self.stock_inventories[key] = value
curQty = int(float(self.stock_inventories["current_quantity"]))
rcvQty = int(float(self.grnItem["recieving_quantity"]))
curQty += rcvQty
newCurQty = str(curQty)+".0000"
nowDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.stock_inventories["current_quantity"] = newCurQty
self.stock_inventories["updated_at"] = nowDateTime
self.siList.append(self.stock_inventories)
val = (self.stock_inventories["current_quantity"],\
self.stock_inventories["updated_at"])
query = "UPDATE stock_inventories SET current_quantity=%s, updated_at=%s \
where inventory_id="+self.stock_inventories["inventory_id"]
self.myCursor.execute(query, val)
if self.insertConfirm == False:
self.db.commit()
siString = ''
for key, value in self.stock_inventories.items():
siString += '{:^19}: {}\n'.format(key, value)
siString = siString[:siString.rfind('\n')]
self.siStringList.append(siString)
# Update stock_inventory_locations
query = "select * from stock_inventory_locations where stock_inventory_id="+self.stock_inventories["id"]
self.myCursor.execute(query)
res = self.myCursor.fetchall()
if res:
i = 0
for key, value in self.stock_inventory_locations.items():
value = res[0][i]
i += 1
self.stock_inventory_locations[key] = value
curQty = int(float(self.stock_inventory_locations["current_quantity"]))
rcvQty = int(float(self.grnItem["recieving_quantity"]))
curQty += rcvQty
newCurQty = str(curQty)+".0000"
nowDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.stock_inventory_locations["current_quantity"] = newCurQty
self.stock_inventory_locations["updated_at"] = nowDateTime
self.silList.append(self.stock_inventories)
val = (self.stock_inventory_locations["current_quantity"],\
self.stock_inventory_locations["updated_at"])
query = "UPDATE stock_inventory_locations SET current_quantity=%s, updated_at=%s \
where stock_inventory_id="+self.stock_inventories["id"]
self.myCursor.execute(query, val)
if self.insertConfirm == False:
self.db.commit()
silString = ''
for key, value in self.stock_inventory_locations.items():
silString += '{:^19}: {}\n'.format(key, value)
silString = silString[:silString.rfind('\n')]
self.silStringList.append(silString)
else:
# prompt user to insert new stock_inventories
self.debugString += "no stock_inventory record\n"
else:
#loop through po_item_id, compare recieving_quantity with ordered_quantity
total = 0
accumulate = 0
for res in exist:
accumulate += res[3]
echoStr = "id:"+str(res[0])+", grn_id:"+str(res[1])+", ordered_quantity:"+str(res[2])+", recieving_quantity:"+str(res[3])
self.debugString += echoStr
self.debugString += '\n'
if self.debugEnable == True:
self.secondGnome.echo(echoStr)
total = exist[0][2]
if accumulate != total:
self.debugString += "insert"
# insert
if first == True:
self.myCursor.execute("select id from goodrecieptsnoteitems order by id desc limit 1")
qResults = self.myCursor.fetchall()
self.grn_item_id = qResults[0][0]+1
first = False
else:
self.grn_item_id += 1
self.debugString += "inserting goodrecieptsnoteitems\n"
if self.debugEnable == True:
self.secondGnome.echo("inserting goodrecieptsnoteitems")
nowDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#if self.insertConfirm == False:
Q6 = "insert into goodrecieptsnoteitems(id, grn_id, po_item_id, item_id,\
ordered_quantity,recieving_quantity, created_at, updated_at)\
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)"
val1 = (self.grn_item_id, self.grn_id, item[0], item[1], item[2], self.itemQuantityToBeDetected[index][1], nowDateTime, nowDateTime)
self.debugString += Q6
self.debugString += '\n'
self.debugString += str(val1)
self.debugString += '\n'
if self.debugEnable == True:
self.secondGnome.echo(str(val1))
self.myCursor.execute(Q6, val1)
if self.insertConfirm == False:
self.db.commit()
#self.myCursor.execute("select id from goodrecieptsnoteitems order by id desc limit 1")
#qResults = self.myCursor.fetchall()
#self.grn_item_id = qResults[0][0]
self.grnItem["id"] = self.grn_item_id
#else:
# self.grnItem["id"] = "AUTO_INCREMENT"
grnItemString = item[4] + '\n'
self.grnItem["grn_id"] = self.grn_id
self.grnItem["po_item_id"] = item[0]
self.grnItem["item_id"] = item[1]
self.grnItem["ordered_quantity"] = item[2]
self.grnItem["recieving_quantity"] = self.itemQuantityToBeDetected[index][1]
self.grnItem["created_at"] = nowDateTime
self.grnItem["updated_at"] = nowDateTime
self.grnItemList.append(self.grnItem)
for key, value in self.grnItem.items():
grnItemString += '{:^19}: {}\n'.format(key, value)
grnItemString = grnItemString[:grnItemString.rfind('\n')]
self.grnItemStringList.append(grnItemString)
else:
self.debugString += "recieving_quantity equal ordered_quantity"
else:
self.debugString += 'goodsreceiptsnotes record exist\n'
if self.debugEnable == True:
self.secondGnome.echo("goodsreceiptsnotes record exist")
def confirm(self):
if self.insertConfirm == True:
"""
# insert goodsreceiptsnotes
nowDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
val = (self.grn_number, self.do_date, self.resStr[0],\
self.poId, self.companyID, nowDateTime, nowDateTime)
self.debugString += "INSERT INTO goodsreceiptsnotes(grn_number, supplier_do_date, supplier_do_number, \
po_number, supplier_id, created_at, updated_at) VALUES (%s,%s,%s,%s,%s,%s,%s)\n"
self.debugString += str(val)
self.debugString += '\n'
if self.debugEnable == True:
self.secondGnome.echo(str(val))
Q3 = "insert into\
goodsreceiptsnotes(grn_number, supplier_do_date, supplier_do_number,\
po_number, supplier_id, created_at, updated_at)\
VALUES (%s,%s,%s,%s,%s,%s,%s)"
self.myCursor.execute(Q3, val)
self.db.commit()
self.myCursor.execute("select id, grn_number from goodsreceiptsnotes order by grn_number desc limit 1")
qResults = self.myCursor.fetchall()
self.grn_id = qResults[0][0]
self.grn["id"] = self.grn_id
# insert goodrecieptsnoteitems
for item in self.grnItemList:
if self.debugEnable == True:
self.secondGnome.echo("inserting goodrecieptsnoteitems")
nowDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Q6 = "insert into goodrecieptsnoteitems(grn_id, po_item_id, item_id,\
ordered_quantity,recieving_quantity, created_at, updated_at)\
VALUES(%s,%s,%s,%s,%s,%s,%s)"
val1 = (self.grn_id, item["po_item_id"], item["item_id"], item["ordered_quantity"], item["recieving_quantity"], nowDateTime, nowDateTime)
self.debugString += Q6
self.debugString += '\n'
self.debugString += str(val1)
self.debugString += '\n'
if self.debugEnable == True:
self.secondGnome.echo(str(val1))
self.myCursor.execute(Q6, val1)
self.db.commit()
self.myCursor.execute("select id from goodrecieptsnoteitems order by id desc limit 1")
qResults = self.myCursor.fetchall()
self.grn_item_id = qResults[0][0]
self.grnItem["id"] = self.grn_item_id
"""
self.db.commit()
def loadItemDetails(self):
# itemDetails[0] = purchase_order_items.id
# itemDetails[1] = purchase_order_items.item_id
# itemDetails[2] = purchase_order_items.quantity
# itemDetails[3] = inventories.part_number
# itemDetails[4] = inventories.description
Q4 = "drop temporary table if exists tempPO;"
Q5 = "create temporary table tempPO select poi.id, poi.item_id, poi.quantity, i.part_number, i.description\
from purchase_order_items poi inner join inventories i on poi.item_id=i.id \
where poi.po_id=(select id from purchase_orders where po_number='"+self.po_number+"') order by poi.id;"
Q6 = "select * from tempPO;"
self.myCursor.execute(Q4)
self.myCursor.execute(Q5)
self.myCursor.execute(Q6)
descr = self.myCursor.description
res = self.myCursor.fetchall()
if res:
self.mySqlTable(res, descr)
for row in res:
if len(self.itemDetails) != 0:
occured = False
for item in self.itemDetails:
# check if there is same item_id
if row[1] == item[1]:
occured = True
break
if occured == False:
self.itemDetails.append(row)
else:
self.itemDetails.append(row)
# print("Load")
# print(self.itemDetails)
else:
self.debugString += 'No PO record or No part_number record\n'
if self.debugEnable == True:
self.secondGnome.echo("No PO record or No part_number record !!!")
def searchItem(self, text):
record = []
# itemDetails[0] = purchase_order_items.id
# itemDetails[1] = purchase_order_items.item_id
# itemDetails[2] = purchase_order_items.quantity
# itemDetails[3] = inventories.part_number
for index, item_detail in enumerate(self.itemDetails):
match = re.search(genRegexCapitalInsensitive(self.itemDetails[index][3]), text)
#secondGnome.echo(genRegexCapitalInsensitive(self.itemDetails[index][2]))
if match != None:
self.itemDetected.append(item_detail)
echoStr = 'Found item with id '+str(item_detail[1])\
+' \''+item_detail[3]+'\''
#echoStr = 'Found item with id '+str(detail[index][0])
self.debugString += echoStr
self.debugString += '\n'
if self.debugEnable == True:
self.secondGnome.echo(echoStr)
#score = fuzz.ratio(item_detail[2], text)
#if score > conf:
#record.append(index)
else:
record.append(index) ## remaining
#if len(record
#for i in record:
#self.itemDetected.append(self.itemDetails[i])
#print("Detected")
#print(self.itemDetected)
temp = self.itemDetails.copy()
self.itemDetails.clear()
for i in record:
self.itemDetails.append(temp[i])
def getQuantity(self, img):
data = pytesseract.image_to_data(img, output_type='dict')
stringLoc = []
quantityY = []
quantityX = 0
quantityW = 0
# Sorting string according to y coordinate to stringLoc
# stringLoc = [text, (x,y,w,h)]
for i in range(0, len(data['text'])):
x = data['left'][i]
y = data['top'][i]
w = data['width'][i]
h = data['height'][i]
text = data['text'][i]
text = "".join(text).strip()
for ele in self.companyYaml['quantity_format']:
match = re.search(ele[0], text)
if match != None:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
#self.secondGnome.echo("found x")
#secondGnome.echo(match.group())
#print(text)
quantityX = x - 20
quantityW = w + 50
#print("x = ", quantityX)
#print("w = ", quantityW)
break
if text.isspace() == False:
if len(stringLoc)==0:
stringLoc.append([text,[x,y,w,h]])
else:
inserted = False
for i in stringLoc:
if y >= i[1][1]-3 and y<=i[1][1]+3:
i[0] = i[0]+" "+text
i[1][2] += w
inserted = True
break
if inserted == False:
stringLoc.append([text,[x,y,w,h]])
# Find ITEM #############################################################
record = []
# itemDetails[0] = purchase_order_items.id
# itemDetails[1] = purchase_order_items.item_id
# itemDetails[2] = purchase_order_items.quantity
# itemDetails[3] = inventories.part_number
for index, item_detail in enumerate(self.itemDetails):
itemRegex = genRegexCapitalInsensitive(self.itemDetails[index][3])
itemFound = False
for j in stringLoc:
match = re.search(itemRegex, j[0])
if match != None:
itemFound = True
self.itemDetected.append(item_detail)
self.itemQuantityToBeDetected.append([True,0])
echoStr = 'Found item with id '+str(item_detail[1])\
+' \''+item_detail[3]+'\''
if self.debugEnable == True:
self.secondGnome.echo(echoStr)
break
if itemFound == False:
record.append(index) ## remaining
temp = self.itemDetails.copy()
self.itemDetails.clear()
for i in record:
self.itemDetails.append(temp[i])
########################################################################
# Find Y
for item_index, i in enumerate(self.itemDetected):
for j in stringLoc:
if self.itemQuantityToBeDetected[item_index][0] == True:
match = re.search(genRegexCapitalInsensitive(i[3]), j[0])
if match != None:
# [y, h] of item