forked from PhilDaintree/CounterLogicPOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounterLogic.py
executable file
·3065 lines (2624 loc) · 132 KB
/
CounterLogic.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygtk # python interface to GTK GUI widgets
pygtk.require('2.0')
import gtk # needed for GUI
import sqlite3 # needed for database storage in CounterLogic.sqlite file
import xmlrpclib # needed for querying webERP stock on hand query
import httplib # required for longer timeout on stock on hand query
import datetime # for formatting and handling dates
import gettext #translation system
import usb.core # required for receipt printing
import usb.util # required for receipt printing
#import usb.backend.libusb1 # required to ensure we only use libusb-1.0 under *nix
import subprocess #needed for the system command to run the Linker script
import os #needed to get the path of where the application is running from
import sys #needed to exit application
#import serial # needed for EFTPOS integration option to send data to the EFTPOS terminal
Version = '0.33'
gtk.rc_parse('CounterLogic.rc')
if getattr(sys, 'frozen', False):
InstallDirectory = os.path.dirname(sys.executable)
elif __file__:
InstallDirectory = sys.path[0]
print InstallDirectory
#Language = 'zh_CN' #change this for alternative language
Language = 'en_GB' #change this for alternative language
#Language = 'es_ES' #change this for alternative language
Lang = gettext.translation('messages', InstallDirectory + '/Languages',languages=[Language],fallback=True)
Lang.install()
class TimeoutTransport(xmlrpclib.Transport): # required to extend timeout on xml-rpc calls
timeout = 30.0
def set_timeout(self, timeout):
self.timeout = timeout
def make_connection(self, host):
h = httplib.HTTPConnection(host, timeout=self.timeout)
return h
class CounterLogic: #The main application class - all happens here
def delete_event(self, widget, event, data=None):
# Change FALSE to TRUE and the main window will not be destroyed
# with a "delete_event".
return False
def Dont_delete_event(self, widget, event, data=None):
# Change FALSE to TRUE and the main window will not be destroyed
# with a "delete_event".
return True
def destroy(self, widget, data=None):
print _("destroy signal occurred")
gtk.main_quit()
def SearchItems (self, widget, data=None):
# Populate it with data from the database
result = self.db.cursor()
if self.SearchField=="Item Code":
#Manny mod
#result.execute("SELECT stockmaster.stockid, barcode, description, taxcatid FROM stockmaster WHERE stockid LIKE ? LIMIT 40",('___' + self.Search_Entry.get_text(),))
result.execute("SELECT stockmaster.stockid, barcode, description, taxcatid FROM stockmaster WHERE stockid LIKE ? LIMIT 40",('%' + self.Search_Entry.get_text() + '%',))
elif self.SearchField=="Bar Code":
result.execute("SELECT stockmaster.stockid, barcode, description, taxcatid FROM stockmaster WHERE barcode LIKE ? LIMIT 40",('%' + self.Search_Entry.get_text() + '%',))
elif self.SearchField=="Description":
result.execute("SELECT stockmaster.stockid, barcode, description, taxcatid FROM stockmaster WHERE description LIKE ? LIMIT 150",('%' + self.Search_Entry.get_text() + '%',))
#Clear any data in the ListStore
self.ItemSearch_ListStore.clear()
#Now populate it with the new result set
i=0
for Row in result:
Price = self.GetPrice(Row['stockid'],Row['taxcatid'],1)
self.ItemSearch_ListStore.append((Row['stockid'],Row['barcode'],Row['description'],Price))
i+=1
if i==0:
MessageBox = gtk.MessageDialog(self.MainWindow, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('No items were found for this search.'))
def RadioButtonClicked (self, widget, data=None):
#sets the SearchField system parameter based on the Radio Button Clicked
#Could be SearchField = 'Item Code' or 'Bar Code' or 'Description'
self.SearchField = data
self.Search_Entry.grab_focus()
def SelectedItem (self, treeview, SelectedItem_Path, ViewColumn, Data=None):
#When an item is selected - double clicked or space on row selected
SelectedItem_Iter = self.ItemSearch_ListStore.get_iter(SelectedItem_Path)
self.ScanCode_Entry.set_text(self.ItemSearch_ListStore.get_value(SelectedItem_Iter, self.ItemSearch['StockID']))
self.PopulateScannedItem(self.MainWindow)
self.ItemSearch_Dialog.destroy()
def OpenSearchItemsDialog(self, widget, data=None):
self.ItemSearch_Dialog = gtk.Dialog(_("Item Search"),self.MainWindow,gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
RowHBox = gtk.HBox(homogeneous=False, spacing=5)
#Pack the RowHBox into the VerticalBox below the menu
self.ItemSearch_Dialog.vbox.pack_start(RowHBox, False, False, 2)
RowHBox.show()
Search_Label = gtk.Label(_("Enter Search:"))
Search_Label.show()
RowHBox.pack_start(Search_Label,False,False, 2)
self.SearchField = 'Item Code' #set as default to search by Item Code
self.Search_Entry = gtk.Entry()
self.Search_Entry.set_width_chars(20)
self.Search_Entry.set_editable(True)
self.Search_Entry.connect('changed', self.SearchItems)
self.Search_Entry.show()
RowHBox.pack_start(self.Search_Entry,False,False, 2)
RadioBox = gtk.HBox(False, 10)
RadioBox.set_border_width(10)
RowHBox.pack_start(RadioBox, True, True, 0)
RadioBox.show()
Search_Radio = gtk.RadioButton(None, _('Seach Item _Code'))
Search_Radio.connect('toggled', self.RadioButtonClicked, 'Item Code')
RadioBox.pack_start(Search_Radio, True, True, 0)
Search_Radio.set_active(True)
Search_Radio.show()
Search_Radio = gtk.RadioButton(Search_Radio, _('Search _Bar code'))
Search_Radio.connect('toggled', self.RadioButtonClicked, 'Bar Code')
RadioBox.pack_start(Search_Radio, True, True, 0)
Search_Radio.show()
Search_Radio = gtk.RadioButton(Search_Radio, _('Search _Description'))
Search_Radio.connect('toggled', self.RadioButtonClicked, 'Description')
RadioBox.pack_start(Search_Radio, True, True, 0)
Search_Radio.show()
separator = gtk.HSeparator()
RowHBox.pack_start(separator, False, True, 0)
separator.show()
self.ItemSearch = dict()
self.ItemSearch['StockID'] = 0
self.ItemSearch['BarCode'] = 1
self.ItemSearch['Description'] = 2
self.ItemSearch['Price'] = 3
#Define a list store to hold the ItemSearch
self.ItemSearch_ListStore = gtk.ListStore(str,str,str,float)
#Define a Tree View to display them
ItemSearch_TreeView = gtk.TreeView(self.ItemSearch_ListStore)
ItemSearch_TreeView.connect('row_activated', self.SelectedItem, None)
#Define the columns to hold the data
StockID_col = gtk.TreeViewColumn(_('Item Code'))
BarCode_col = gtk.TreeViewColumn(_('Bar Code'))
Description_col = gtk.TreeViewColumn(_('Description'))
Price_col = gtk.TreeViewColumn(_('Price'))
#Add the colums to the TreeView
ItemSearch_TreeView.append_column(StockID_col)
ItemSearch_TreeView.append_column(BarCode_col)
ItemSearch_TreeView.append_column(Description_col)
ItemSearch_TreeView.append_column(Price_col)
#Define the cells to hold the data
StockID_cell = gtk.CellRendererText()
StockID_cell.set_property('width',180)
StockID_col.pack_start(StockID_cell,True)
StockID_col.set_attributes(StockID_cell, text=self.ItemSearch['StockID'])
BarCode_cell = gtk.CellRendererText()
BarCode_cell.set_property('width',180)
BarCode_col.pack_start(BarCode_cell,True)
BarCode_col.set_attributes(BarCode_cell, text=self.ItemSearch['BarCode'])
Description_cell = gtk.CellRendererText()
Description_cell.set_property('width',400)
Description_col.pack_start(Description_cell,True)
Description_col.set_attributes(Description_cell, text=self.ItemSearch['Description'])
Price_cell = gtk.CellRendererText()
Price_cell.set_property('width',80)
Price_cell.set_property('xalign', 1)
Price_col.pack_start(Price_cell,True)
Price_col.set_cell_data_func(Price_cell, self.FormatDecimalPlaces, self.ItemSearch['Price'])
ItemSearch_TreeView.show()
ItemSearch_ScrolledWindow = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
ItemSearch_ScrolledWindow.set_border_width(10)
ItemSearch_ScrolledWindow.set_policy (gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
ItemSearch_ScrolledWindow.set_size_request(1000,600)
ItemSearch_ScrolledWindow.add (ItemSearch_TreeView)
ItemSearch_ScrolledWindow.show()
self.ItemSearch_Dialog.vbox.pack_start(ItemSearch_ScrolledWindow, True)
Response = self.ItemSearch_Dialog.run()
if Response == gtk.RESPONSE_ACCEPT:
CurrentSelection = ItemSearch_TreeView.get_selection()
(model, ItemIter) = CurrentSelection.get_selected()
if ItemIter != None:
self.ScanCode_Entry.set_text(self.ItemSearch_ListStore.get_value(ItemIter, self.ItemSearch['StockID']))
self.PopulateScannedItem(self.MainWindow)
self.ItemSearch_Dialog.destroy()
elif Response == gtk.RESPONSE_REJECT:
self.ItemSearch_Dialog.destroy()
def PopulateScannedItem (self, widget, data=None):
result = self.db.cursor()
GotAnItem=False
if len(self.ScanCode_Entry.get_text()) > 0:
print self.ScanCode_Entry.get_text()
#check against the database to retrieve the item based on a bar code scan
result.execute("SELECT stockid, description, taxcatid, decimalplaces, discountcategory FROM stockmaster WHERE barcode=?",(self.ScanCode_Entry.get_text(),))
for Row in result:
GotAnItem=True #as we found a result
self.AddItemToSale(Row)
if GotAnItem==False:
#OK so try to see if the scanned code was the item code not a bar code
result.execute("SELECT stockid, description, taxcatid, decimalplaces, discountcategory FROM stockmaster WHERE stockid=?",(self.ScanCode_Entry.get_text(),))
for Row in result:
GotAnItem=True #as we found a result
self.AddItemToSale(Row)
if GotAnItem==False:
self.ScanResult_Label.set_label(_('There is no item for ') + self.ScanCode_Entry.get_text())
self.ScanCode_Entry.set_text('')
def AddItemToSale(self, Row):
DuplicateItem = False
#Loop through the ListStore to see if the item is already on the sale */
SaleLine_TreeIter = self.SaleEntryGrid_ListStore.get_iter_first()
while SaleLine_TreeIter:
StockID = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['SKU'])
Quantity = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['Quantity'])
if Row['stockid']==StockID:
DuplicateItem=True
Quantity = Quantity+1
self.SaleEntryGrid_ListStore.set_value(SaleLine_TreeIter,self.Col['Quantity'],Quantity)
#Now recheck the price given the increased quantity - discountmatrix quantity break may kick in
Price = self.GetPrice(Row['stockid'],Row['taxcatid'],Quantity)
if Price < self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['SellPrice']) and self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['ManualPrice']) == False:
self.SaleEntryGrid_ListStore.set_value(SaleLine_TreeIter,self.Col['SellPrice'],Price)
#end if the scanned item is already on the sale
SaleLine_TreeIter = self.SaleEntryGrid_ListStore.iter_next(SaleLine_TreeIter)
# end loop through all items in the SalesEntryGrid_ListStore
if DuplicateItem==False: #The scanned item was not already on the sale
#Now get the price ... if we canp
Price = self.GetPrice(Row['stockid'],Row['taxcatid'],1)
NewRowIter = self.SaleEntryGrid_ListStore.append((Row['stockid'],Row['description'],Price,1,Price,Row['decimalplaces'],Row['taxcatid'], False, Row['discountcategory'],''))
self.ScanCode_Entry.set_text('')
self.RecalculateSaleTotal()
self.ScanResult_Label.set_label(_('Item') + ' ' + Row['stockid'] + ' ' + _('has been added to the sale.') + ' ')
self.ScanCode_Entry.grab_focus()
def GetPrice (self, StockID, TaxCatID, Quantity):
result = self.db.cursor()
#First look for a price for the specific customer
SQLParameters = (StockID, self.CustomerDetails['salestype'], self.CustomerDetails['debtorno'])
result.execute("SELECT MIN(price) AS lowestprice FROM prices WHERE stockid=? AND typeabbrev=? AND debtorno=?",SQLParameters)
FoundPrice = False
for Row in result:
if Row['lowestprice'] != None:
FoundPrice = True
Price = Row['lowestprice']
if FoundPrice == False:
SQLParameters = (StockID, self.CustomerDetails['salestype'])
result.execute("SELECT MIN(price) AS lowestprice FROM prices WHERE stockid=? AND typeabbrev=?",SQLParameters)
for Row in result:
if Row['lowestprice'] != None:
FoundPrice = True
Price = Row['lowestprice']
if FoundPrice == False:
SQLParameters = (StockID, self.DefaultSalesType)
result.execute("SELECT MIN(price) AS lowestprice FROM prices WHERE stockid=? AND typeabbrev=?",SQLParameters)
for Row in result:
if Row['lowestprice'] != None:
FoundPrice = True
Price = Row['lowestprice']
if FoundPrice == True:
# Now check the discountmatrix - to see if any discount should be applied
SQLParameters = (StockID, self.CustomerDetails['salestype'], Quantity)
result.execute("SELECT MAX(discountrate) as maxdiscount FROM discountmatrix INNER JOIN stockmaster ON discountmatrix.discountcategory=stockmaster.discountcategory WHERE stockmaster.stockid=? AND salestype=? AND quantitybreak<=?", SQLParameters)
for Row in result:
if Row['maxdiscount'] != None:
Price *= (1-Row['maxdiscount'])
# now apply the taxes to the price retrieved to get the gross tax inclusive price
Price *= (1+self.TaxRate[TaxCatID])
#add 1 hundredth of a cent to ensure always rounding up to the next whole cent
Price += 0.001
#round the price to 2 decimal places
Price =round(Price,2)
return Price
else:
return 0
def GetCustomerDetails(self, DebtorNo, BranchCode):
CustomerDetails = dict()
result = self.db.cursor()
result.execute("SELECT debtorsmaster.debtorno, name, currcode, salestype, holdreason, dissallowinvoices, paymentterms, discount, creditlimit, discountcode, taxgroupid FROM debtorsmaster INNER JOIN holdreasons ON debtorsmaster.holdreason=holdreasons.reasoncode INNER JOIN custbranch ON debtorsmaster.debtorno=custbranch.debtorno WHERE custbranch.debtorno=? AND custbranch.branchcode=? ",(DebtorNo, BranchCode))
Row = result.fetchone()
if Row != None:
if Row['dissallowinvoices']==1:
CustomerDetails = False
MessageBox = gtk.MessageDialog(self.MainWindow, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('The customer selected is on hold with credit control another customer must be selected') + ' ' + DebtorNo)
MessageBox.run()
MessageBox.destroy()
else:
CustomerDetails['debtorno'] = Row['debtorno']
CustomerDetails['name'] = Row['name']
CustomerDetails['currcode'] = Row['currcode']
CustomerDetails['salestype'] = Row['salestype']
CustomerDetails['holdreason'] = Row['holdreason']
CustomerDetails['paymentterms'] = Row['paymentterms']
CustomerDetails['discount'] = Row['discount']
CustomerDetails['creditlimit'] = Row['creditlimit']
CustomerDetails['discountcode'] = Row['discountcode']
CustomerDetails['taxgroupid'] = Row['taxgroupid']
CustomerDetails['branchcode'] = BranchCode
# Need to get the tax details and make a dict of the taxes too
result.execute("SELECT taxauthority, taxcatid FROM taxgrouptaxes INNER JOIN taxauthorities ON taxgrouptaxes.taxauthid=taxauthorities.taxid INNER JOIN taxauthrates ON taxauthorities.taxid=taxauthrates.taxauthority INNER JOIN locations ON taxauthrates.dispatchtaxprovince=locations.taxprovinceid WHERE locations.loccode=? AND taxgrouptaxes.taxgroupid=? ORDER BY taxcatid,calculationorder",(self.Config['Location'], CustomerDetails['taxgroupid']))
#self.TaxRate is an associative array with the key being the tax category and the value being the tax rate applicable for the tax category ... this could be the sum of any number of tax authorities rates
self.TaxRate = dict()
#Taxes is an assoc array with the key the tax category again but this time contains an array of the taxes applicable and the rate of each
self.Taxes = dict()
i=0
for Row in result:
try:
self.TaxRate[Row['taxcatid']]==None
except KeyError:
self.TaxRate[Row['taxcatid']]=0
self.Taxes[Row['taxcatid']]=dict()
i+=1
self.Taxes[Row['taxcatid']][Row['taxauthority']]=dict()
#Need to deal with none - where the Location is invalid or no tax details have been imported
if i==0:
CustomerDetails = False
MessageBox = gtk.MessageDialog(self.MainWindow, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('Either the tax rates are not set up or the inventory location set up in the option dialog are incorrect. Please correct the options, then logout and back in to try again.'))
MessageBox.run()
MessageBox.destroy()
print _('Could not get tax set up - possibly incorrect location in options dialog')
return CustomerDetails
result.execute("SELECT taxauthority, taxcatid, taxrate, taxontax FROM taxgrouptaxes INNER JOIN taxauthorities ON taxgrouptaxes.taxauthid=taxauthorities.taxid INNER JOIN taxauthrates ON taxauthorities.taxid=taxauthrates.taxauthority INNER JOIN locations ON taxauthrates.dispatchtaxprovince=locations.taxprovinceid WHERE locations.loccode=? AND taxgrouptaxes.taxgroupid=? ORDER BY taxcatid,calculationorder",(self.Config['Location'], CustomerDetails['taxgroupid']))
#now go around again same query but with taxrate and taxOntax and calculate tax rates
#Figure out the effective overall tax percentage for each tax category
#Also record the rate for each tax authority/tax category required for stockmovetaxes
for Row in result:
print 'TaxCatID = ' + str(Row['taxcatid']) + ' rate = ' + str(Row['taxrate'])
if Row['taxontax']==1: #if tax on tax add taxrate x current total of taxes
self.TaxRate[Row['taxcatid']] += (Row['taxrate']*self.TaxRate[Row['taxcatid']])
self.TaxRate[Row['taxcatid']] += Row['taxrate'] # add all taxes together for this taxgroup
print _('New tax rate for this customer tax group/ location, for tax category') + ' ' + str(Row['taxcatid']) + ' = ' + str(self.TaxRate[Row['taxcatid']])
self.Taxes[Row['taxcatid']][Row['taxauthority']]['Rate'] = Row['taxrate']
self.Taxes[Row['taxcatid']][Row['taxauthority']]['TaxOnTax'] = Row['taxontax']
self.Taxes[Row['taxcatid']][Row['taxauthority']]['Amount'] = 0
print _('New tax rate for this customer tax group/ location') + ' = ' + str(self.TaxRate[Row['taxcatid']])
return CustomerDetails
else:
MessageBox = gtk.MessageDialog(self.MainWindow, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('Customer details could not be retrieved for the customer') + ' ' + DebtorNo)
MessageBox.run()
MessageBox.destroy()
CustomerDetails['debtorno'] = 'ANGRY'
CustomerDetails['name'] = 'Not setup correctly'
CustomerDetails['currcode'] = 'USD'
CustomerDetails['salestype'] = ''
CustomerDetails['holdreason'] = ''
CustomerDetails['paymentterms'] = ''
CustomerDetails['discount'] = 0
CustomerDetails['creditlimit'] = 100
CustomerDetails['discountcode'] = ''
CustomerDetails['taxgroupid'] = ''
CustomerDetails['branchcode'] = 'ANGRY'
return CustomerDetails
print _('Customer is not valid - all sales must have a valid customer')
def RecalculateSaleTotal (self):
SaleLine_TreeIter = self.SaleEntryGrid_ListStore.get_iter_first()
self.SaleTotal = 0
self.TaxTotal = 0
result = self.db.cursor()
while SaleLine_TreeIter:
Quantity = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['Quantity'])
TaxCatID = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['TaxCatID'])
StockID = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['SKU'])
if self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['ManualPrice']) == False:
Price = self.GetPrice(StockID,TaxCatID,Quantity)
self.SaleEntryGrid_ListStore.set_value(SaleLine_TreeIter, self.Col['SellPrice'],Price)
else:
Price = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['SellPrice'])
LineTotal = Price * Quantity
self.SaleEntryGrid_ListStore.set_value(SaleLine_TreeIter,self.Col['LineTotal'],LineTotal)
try:
LineTaxRate = self.TaxRate[TaxCatID]
except:
LineTaxRate = 0
self.TaxTotal += (LineTotal*LineTaxRate/(1+LineTaxRate))
self.SaleTotal += LineTotal
SaleLine_TreeIter = self.SaleEntryGrid_ListStore.iter_next(SaleLine_TreeIter)
# end loop through all items in the SalesEntryGrid_ListStore
self.SaleTotal_Value.set_label('<b>' + "{0: .2f}".format(self.SaleTotal) + '</b>')
self.SaleTax_Value.set_label("{0: .2f}".format(self.TaxTotal))
def EditedSellPrice (self,cell, path, NewText, Data=None):
if float(NewText)< 0:
MessageBox = gtk.MessageDialog(self.MainWindow, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('Prices must be positive numbers'))
MessageBox.run()
MessageBox.destroy()
else:
self.SaleEntryGrid_ListStore[path][self.Col['SellPrice']] = float(NewText)
self.SaleEntryGrid_ListStore[path][self.Col['ManualPrice']] = True
self.RecalculateSaleTotal()
def EditedQuantity (self, cell, path, NewText, Data=None):
self.SaleEntryGrid_ListStore[path][self.Col['Quantity']] = float(NewText)
self.RecalculateSaleTotal()
def EditedRemarks (self, cell, path, NewText, Data=None):
self.SaleEntryGrid_ListStore[path][self.Col['Remarks']] = NewText
def ProcessKeyPress(self, CurrentTreeView, KeyPressed ):
#What to do when the user presses a key while focus is on the TreeView SaleEntryGrid
CurrentTreePath, CurrentRow = self.SaleEntryGrid_TreeView.get_cursor()
if CurrentTreePath != None: #the CurrentTreePath is None if the focus was not on a line in the TreeView
SaleEntryGrid_TreeIter = self.SaleEntryGrid_ListStore.get_iter(CurrentTreePath)
Quantity = self.SaleEntryGrid_ListStore.get_value(SaleEntryGrid_TreeIter,self.Col['Quantity'])
KeyName = gtk.gdk.keyval_name(KeyPressed.keyval)
print "Key %s (%d) was pressed" % (KeyName, KeyPressed.keyval)
if KeyPressed.keyval == 65451: # + key pressed
Quantity = Quantity + 1
self.SaleEntryGrid_ListStore.set_value(SaleEntryGrid_TreeIter,self.Col['Quantity'],Quantity)
elif KeyPressed.keyval == 65453: # - key pressed
Quantity = Quantity - 1
self.SaleEntryGrid_ListStore.set_value(SaleEntryGrid_TreeIter,self.Col['Quantity'],Quantity)
if Quantity <=0:
self.SaleEntryGrid_ListStore.remove(SaleEntryGrid_TreeIter)
#end case KeyPressed.str
elif KeyPressed.keyval == 65535: #delete key was pressed
self.SaleEntryGrid_ListStore.remove(SaleEntryGrid_TreeIter)
self.ScanCode_Entry.grab_focus()
#end when pressed Delete
elif KeyPressed.keyval == 65364: #down key was pressed
self.SaleEntryGrid_TreeView.set_cursor((CurrentRow+1,),focus_column=None, start_editing=False)
#end when pressed down
elif KeyPressed.keyval == 65362: #up key was pressed
self.SaleEntryGrid_TreeView.set_cursor((CurrentRow-1,),focus_column=None, start_editing=False)
#end when pressed Up
elif KeyPressed.keyval == 65289: #TAB key was pressed
self.ScanCode_Entry.grab_focus()
#end when TAB key pressed
self.RecalculateSaleTotal()
return True
def SearchCustomers (self, widget, data=None):
# Populate it with data from the database
result = self.db.cursor()
if self.SearchCustomerField=="Customer Code":
result.execute("SELECT debtorsmaster.debtorno, debtorsmaster.name, branchcode, brname FROM debtorsmaster INNER JOIN custbranch ON debtorsmaster.debtorno=custbranch.debtorno WHERE debtorsmaster.debtorno LIKE ? AND debtorsmaster.currcode=?",('%' + self.SearchCustomer_Entry.get_text() + '%',self.CustomerDetails['currcode']))
elif self.SearchCustomerField=="Customer Name":
result.execute("SELECT debtorsmaster.debtorno, debtorsmaster.name, branchcode, brname FROM debtorsmaster INNER JOIN custbranch ON debtorsmaster.debtorno=custbranch.debtorno WHERE debtorsmaster.name LIKE ?",('%' + self.SearchCustomer_Entry.get_text() + '%',))
#Clear any data in the ListStore
self.CustomerSearch_ListStore.clear()
#Now populate it with the new result set
for Row in result:
self.CustomerSearch_ListStore.append((Row['debtorno'],Row['name'],Row['branchcode'],Row['brname']))
def CustomerRadioButtonClicked(self,widget,SearchCriteria):
self.SearchCustomerField = SearchCriteria
self.SearchCustomer_Entry.grab_focus()
def SelectedCustomer (self, treeview, SelectedCustomer_Path, ViewColumn, Data=None):
#When a customer is selected - double clicked or space on row selected
SelectedCustomer_Iter = self.CustomerSearch_ListStore.get_iter(SelectedCustomer_Path)
self.CustomerDetails = self.GetCustomerDetails(self.CustomerSearch_ListStore.get_value(SelectedCustomer_Iter, self.CustomerSearch['DebtorNo']),self.CustomerSearch_ListStore.get_value(SelectedCustomer_Iter, self.CustomerSearch['BranchCode']))
#Prices could be completely different so need to lookup/apply appropriate discounts again
#Loop around the current order and update pricing including the new taxes
SaleLine_TreeIter = self.SaleEntryGrid_ListStore.get_iter_first()
self.SaleTotal = 0
self.TaxTotal =0
while SaleLine_TreeIter:
StockID = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['SKU'])
TaxCatID = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['TaxCatID'])
Quantity = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['Quantity'])
Price = self.GetPrice(StockID, TaxCatID, Quantity)
self.SaleEntryGrid_ListStore.set_value(SaleLine_TreeIter,self.Col['SellPrice'],Price)
LineTotal = Price * Quantity
self.SaleEntryGrid_ListStore.set_value(SaleLine_TreeIter,self.Col['LineTotal'],LineTotal)
self.SaleTotal += LineTotal
print "StockID = " + StockID + " new price = " + str(Price)
try:
LineTaxRate = self.TaxRate[TaxCatID]
except:
LineTaxRate = 0
self.TaxTotal += (LineTotal*LineTaxRate/(1+LineTaxRate))
SaleLine_TreeIter = self.SaleEntryGrid_ListStore.iter_next(SaleLine_TreeIter)
# end loop through all items in the SalesEntryGrid_ListStore
self.SaleTotal_Value.set_label('<b>' + "{0: .2f}".format(self.SaleTotal) + '</b>')
self.SaleTax_Value.set_label("{0: .2f}".format(self.TaxTotal))
#Set the label in the main window to show the customer
self.CustomerName_Label.set_label('<b>' + _('Customer') + ': ' + self.CustomerDetails['name']+ '</b>')
if self.CustomerDetails['debtorno']!=self.Config['DebtorNo']:
self.CustomerName_Label.show()
else:
self.CustomerName_Label.hide()
self.CustomerSearch_Dialog.destroy()
def OpenCustomerSearchDialog (self, widget, data=None):
self.CustomerSearch_Dialog = gtk.Dialog(_('Customer Search'),self.MainWindow,gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK,gtk.RESPONSE_ACCEPT))
RowHBox = gtk.HBox(homogeneous=False, spacing=5)
#Pack the RowHBox into the VerticalBox below the menu
self.CustomerSearch_Dialog.vbox.pack_start(RowHBox, False, False, 2)
RowHBox.show()
Search_Label = gtk.Label(_('Enter Search:'))
Search_Label.show()
RowHBox.pack_start(Search_Label,False,False, 2)
self.SearchCustomerField = 'Customer Code' #set as default to search by Item Code
self.SearchCustomer_Entry = gtk.Entry()
self.SearchCustomer_Entry.set_width_chars(20)
self.SearchCustomer_Entry.set_editable(True)
self.SearchCustomer_Entry.connect('changed', self.SearchCustomers)
self.SearchCustomer_Entry.show()
RowHBox.pack_start(self.SearchCustomer_Entry,False,False, 2)
RadioBox = gtk.HBox(False, 10)
RadioBox.set_border_width(10)
RowHBox.pack_start(RadioBox, True, True, 0)
RadioBox.show()
Search_Radio = gtk.RadioButton(None, _('Search Customer _Code'))
Search_Radio.connect('toggled', self.CustomerRadioButtonClicked, 'Customer Code')
RadioBox.pack_start(Search_Radio, True, True, 0)
Search_Radio.set_active(True)
Search_Radio.show()
Search_Radio = gtk.RadioButton(Search_Radio, _('Search Customer _Name'))
Search_Radio.connect('toggled', self.CustomerRadioButtonClicked, 'Customer Name')
RadioBox.pack_start(Search_Radio, True, True, 0)
Search_Radio.show()
separator = gtk.HSeparator()
RowHBox.pack_start(separator, False, True, 0)
separator.show()
self.CustomerSearch = dict()
self.CustomerSearch['DebtorNo'] = 0
self.CustomerSearch['Name'] = 1
self.CustomerSearch['BranchCode'] = 2
self.CustomerSearch['BranchName'] = 3
#Define a list store to hold the CustomerSearch
self.CustomerSearch_ListStore = gtk.ListStore(str,str, str, str)
#Define a Tree View to display them
CustomerSearch_TreeView = gtk.TreeView(self.CustomerSearch_ListStore)
CustomerSearch_TreeView.connect('row_activated',self.SelectedCustomer)
#Define the columns to hold the data
DebtorNo_col = gtk.TreeViewColumn(_('Customer Code'))
Name_col = gtk.TreeViewColumn(_('Customer Name'))
BranchCode_col = gtk.TreeViewColumn(_('Branch Code'))
BranchName_col = gtk.TreeViewColumn(_('Branch Name'))
#Add the colums to the TreeView
CustomerSearch_TreeView.append_column(DebtorNo_col)
CustomerSearch_TreeView.append_column(Name_col)
CustomerSearch_TreeView.append_column(BranchCode_col)
CustomerSearch_TreeView.append_column(BranchName_col)
#Define the cells to hold the data
DebtorNo_cell = gtk.CellRendererText()
DebtorNo_cell.set_property('width',100)
DebtorNo_col.pack_start(DebtorNo_cell,True)
DebtorNo_col.set_attributes(DebtorNo_cell, text=self.CustomerSearch['DebtorNo'])
Name_cell = gtk.CellRendererText()
Name_cell.set_property('width',250)
Name_col.pack_start(Name_cell,True)
Name_col.set_attributes(Name_cell, text=self.CustomerSearch['Name'])
BranchCode_cell = gtk.CellRendererText()
BranchCode_cell.set_property('width',100)
BranchCode_col.pack_start(BranchCode_cell,True)
BranchCode_col.set_attributes(BranchCode_cell, text=self.CustomerSearch['BranchCode'])
BranchName_cell = gtk.CellRendererText()
BranchName_cell.set_property('width',250)
BranchName_col.pack_start(BranchName_cell,True)
BranchName_col.set_attributes(BranchName_cell, text=self.CustomerSearch['BranchName'])
CustomerSearch_TreeView.show()
CustomerSearch_ScrolledWindow = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
CustomerSearch_ScrolledWindow.set_border_width(10)
CustomerSearch_ScrolledWindow.set_policy (gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
CustomerSearch_ScrolledWindow.set_size_request(700,400)
CustomerSearch_ScrolledWindow.add (CustomerSearch_TreeView)
CustomerSearch_ScrolledWindow.show()
self.CustomerSearch_Dialog.vbox.pack_start(CustomerSearch_ScrolledWindow, True)
Response = self.CustomerSearch_Dialog.run()
if Response == gtk.RESPONSE_ACCEPT:
CurrentSelection = CustomerSearch_TreeView.get_selection()
(model, CustomerIter) = CurrentSelection.get_selected()
if CustomerIter != None:
self.CustomerDetails = self.GetCustomerDetails(self.CustomerSearch_ListStore.get_value(CustomerIter, self.CustomerSearch['DebtorNo']),self.CustomerSearch_ListStore.get_value(CustomerIter, self.CustomerSearch['BranchCode']))
self.BranchCode = self.CustomerSearch_ListStore.get_value(CustomerIter, self.CustomerSearch['BranchCode'])
if self.CustomerDetails['debtorno']!=self.Config['DebtorNo']:
self.CustomerName_Label.show()
else:
self.CustomerName_Label.hide()
self.CustomerSearch_Dialog.destroy()
def OpenLocationStockDialog (self, widget, data=None):
CurrentSelection = self.SaleEntryGrid_TreeView.get_selection()
(model, SaleLineIter) = CurrentSelection.get_selected()
if SaleLineIter == None:
MessageBox = gtk.MessageDialog(self.MainWindow, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('There is no item selected in the main POS window. First bring up the item on the sale, select it, then click the inventory location inquiry'))
MessageBox.run()
MessageBox.destroy()
print _('No item selected to inquire on')
else:
LocationStock_Dialog = gtk.Dialog(_('Location Inventory Inquiry'),self.MainWindow,gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR,(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
LocationStock = dict()
LocationStock['LocationName'] = 0
LocationStock['Quantity'] = 1
#Define a list store to hold the LocationStock
LocationStock_ListStore = gtk.ListStore(str,float)
#Get the data using XML-RPC back to the database
Transport = TimeoutTransport()
x_server = xmlrpclib.Server(self.Config['webERPXmlRpcServer'],transport=Transport)
#Do the weberp.xmlrpc_GetStockBalance on the webERP installation
XMLRPC_Result = x_server.weberp.xmlrpc_GetStockBalance(self.SaleEntryGrid_ListStore.get_value(SaleLineIter,self.Col['SKU']),self.Config['webERPuser'],self.Config['webERPpwd'])
if XMLRPC_Result[0] != 0:
MessageBox = gtk.MessageDialog(self.MainWindow, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('The XML-RPC call to retrieve the inventory location inquiry details from webERP was unsucessful. It could be that internet connectivity to the webERP server is down'))
MessageBox.run()
MessageBox.destroy()
else:
# Populate the ListStore with the data returned from the XML-RPC call
result = self.db.cursor()
for InventoryQuantity in XMLRPC_Result[1]:
result.execute("SELECT locationname FROM locations WHERE loccode=?",(InventoryQuantity['loccode'],))
for Row in result:
LocationStock_ListStore.append((Row['locationname'],float(InventoryQuantity['quantity'])))
#Define a Tree View to display them
LocationStock_TreeView = gtk.TreeView(LocationStock_ListStore)
#Define the columns to hold the data
LocationName_col = gtk.TreeViewColumn(_('Location'))
Quantity_col = gtk.TreeViewColumn(_('Quantity'))
#Add the colums to the TreeView
LocationStock_TreeView.append_column(LocationName_col)
LocationStock_TreeView.append_column(Quantity_col)
#Define the cells to hold the data
LocationName_cell = gtk.CellRendererText()
LocationName_cell.set_property('width',120)
LocationName_cell.set_property('mode',gtk.CELL_RENDERER_MODE_INERT)
LocationName_col.pack_start(LocationName_cell,True)
LocationName_col.set_attributes(LocationName_cell, text=LocationStock['LocationName'])
Quantity_cell = gtk.CellRendererText()
Quantity_cell.set_property('width',130)
Quantity_cell.set_property('mode',gtk.CELL_RENDERER_MODE_INERT)
Quantity_col.pack_start(Quantity_cell,True)
Quantity_col.set_cell_data_func(Quantity_cell, self.FormatDecimalPlaces, LocationStock['Quantity'])
LocationStock_TreeView.show()
LocationStock_ScrolledWindow = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
LocationStock_ScrolledWindow.set_border_width(10)
LocationStock_ScrolledWindow.set_policy (gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
LocationStock_ScrolledWindow.set_size_request(320,200)
LocationStock_ScrolledWindow.add (LocationStock_TreeView)
LocationStock_ScrolledWindow.show()
LocationStock_Dialog.vbox.pack_start(LocationStock_ScrolledWindow, True)
LocationStock_Dialog.run()
LocationStock_Dialog.destroy()
# End of Inventory Location Inquiry Dialog Box
def PaymentEntered(self, widget, PaymentMethod):
try:
Amount = float(self.Payment_Entry.get_text())
except:
MessageBox = gtk.MessageDialog(self.EnterPayment_Dialog, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('Only positive numeric values can be entered'))
MessageBox.run()
MessageBox.destroy()
self.Payment_Entry.set_text('0.00')
print _('Only positive amounts to be entered for payments')
return 0
if Amount <0:
MessageBox = gtk.MessageDialog(self.EnterPayment_Dialog, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('Only positive amounts can be entered for payments'))
MessageBox.run()
MessageBox.destroy()
self.Payment_Entry.set_text("0.00")
print _('Only positive amounts to be entered for payments')
return 0
Payment_TreeIter = self.Payment_ListStore.get_iter_first()
AddedPayment = False
self.TotalPayments = 0
while Payment_TreeIter:
ThisLinePaymentMethod = self.Payment_ListStore.get_value(Payment_TreeIter, self.PaymentMethods['ID'])
if ThisLinePaymentMethod == 9999:
if (self.SaleTotal - self.TotalPayments - Amount < 0):
MessageBox = gtk.MessageDialog(self.EnterPayment_Dialog, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _("Cannot charge an account more than is required. If part of the sale is settled by another payment method then only the balance can be charged to the customer\'s account."))
MessageBox.run()
MessageBox.destroy()
self.Payment_Entry.set_text("{0: .2f}".format(self.SaleTotal - self.TotalPayments))
print _('Cannot charge a customer account more than is required. The sum of other payment methods together with the account charge is greater than the total sale')
return 0
print PaymentMethod, ThisLinePaymentMethod
ThisLinePaymentAmount = float(self.Payment_ListStore.get_value(Payment_TreeIter, self.PaymentMethods['Amount']))
if int(ThisLinePaymentMethod) == int(PaymentMethod):
self.Payment_ListStore.set_value(Payment_TreeIter,self.PaymentMethods['Amount'],Amount)
AddedPayment = True
self.TotalPayments += Amount
else:
self.TotalPayments += ThisLinePaymentAmount
Payment_TreeIter = self.Payment_ListStore.iter_next(Payment_TreeIter)
# end loop through all items in the Payment_ListStore
if AddedPayment==False:
if PaymentMethod==9999:
PaymentName = _('Charge Account')
if (self.SaleTotal - self.TotalPayments - Amount < 0):
MessageBox = gtk.MessageDialog(self.EnterPayment_Dialog, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _("Cannot charge an account more than is required. If part of the sale is settled by another payment method then only the balance can be charged to the customer\'s account. The amount charged has been changed to") + ' ' + "{0: .2f}".format(self.SaleTotal - self.TotalPayments))
MessageBox.run()
MessageBox.destroy()
self.Payment_Entry.set_text("{0: .2f}".format(self.SaleTotal - self.TotalPayments))
Amount = (self.SaleTotal - self.TotalPayments)
print _('Cannot charge a customer account more than is required. The sum of other payment methods together with the account charge is greater than the total sale')
else:
result = self.db.cursor()
result.execute("SELECT paymentname FROM paymentmethods WHERE paymentid=?", (PaymentMethod,))
Row=result.fetchone()
PaymentName = Row['paymentname']
self.Payment_ListStore.append((PaymentMethod, PaymentName, Amount))
self.TotalPayments += Amount
self.PaymentTotal_Value.set_label('<b>' + "{0: .2f}".format(self.TotalPayments) + '</b>')
LeftToPay = self.SaleTotal - self.TotalPayments
if LeftToPay < 0:
LeftToPay = 0
self.LeftToPay_Value.set_label('<b>' + "{0: .2f}".format(LeftToPay) + '</b>')
self.EnterPayment_Dialog.destroy()
def EnterPaymentAmount(self, widget, PaymentMethod=None):
#user clicked a payment method button in the Payment Dialog...
if PaymentMethod=='Charge_Account':
PaymentName = _('Account Charge')
PaymentMethod=9999
else:
result = self.db.cursor()
result.execute("SELECT paymentname FROM paymentmethods WHERE paymentid=?", (PaymentMethod,))
Row=result.fetchone()
PaymentName = Row['paymentname']
self.EnterPayment_Dialog = gtk.Dialog(_('Enter') + ' ' + PaymentName + ' ' + _('Amount'), self.Payment_Dialog,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT| gtk.DIALOG_NO_SEPARATOR, None)
Payment_Label = gtk.Label(_('Enter') + ' ' + PaymentName + ' ' + _('Amount'))
Payment_Label.show()
self.EnterPayment_Dialog.vbox.pack_start(Payment_Label,False)
self.Payment_Entry = gtk.Entry(max=15)
self.Payment_Entry.editable = True
self.Payment_Entry.xalign = 1
self.Payment_Entry.grab_focus()
#Find out if this payment method is already added to the liststore
ExistingPaymentMethod = False
Payment_TreeIter = self.Payment_ListStore.get_iter_first()
if (int(self.Config['CashPaymentMethodID'])==PaymentMethod):
#if it is cash then round to the nearest smallest coin
LeftToPay = self.RoundToSmallestCoin(self.SaleTotal - self.TotalPayments)
else:
LeftToPay = self.SaleTotal - self.TotalPayments
while Payment_TreeIter:
ThisLinePaymentMethod = self.Payment_ListStore.get_value(Payment_TreeIter, self.PaymentMethods['ID'])
ThisLinePaymentAmount = self.Payment_ListStore.get_value(Payment_TreeIter, self.PaymentMethods['Amount'])
if int(ThisLinePaymentMethod) == int(PaymentMethod):
#set the entry to the existing amount previously entered
if float(ThisLinePaymentAmount)==0:
self.Payment_Entry.set_text("{0: .2f}".format(LeftToPay))
else:
self.Payment_Entry.set_text("{0: .2f}".format(ThisLinePaymentAmount))
ExistingPaymentMethod = True
break
Payment_TreeIter = self.Payment_ListStore.iter_next(Payment_TreeIter)
# end loop through all items in the Payment_ListStore
if ExistingPaymentMethod == False:
#Then set the amount to the remaining balance to be paid
self.Payment_Entry.set_text("{0: .2f}".format(LeftToPay))
self.Payment_Entry.connect('activate', self.PaymentEntered, PaymentMethod)
self.Payment_Entry.show()
self.EnterPayment_Dialog.vbox.pack_start(self.Payment_Entry,False)
self.EnterPayment_Dialog.run()
self.EnterPayment_Dialog.destroy()
def RoundToSmallestCoin (self, Amount):
NumberofSmallestCoins = Amount / float(self.Config['SmallestCoin'])
DecimalPart = NumberofSmallestCoins - int(NumberofSmallestCoins)
if DecimalPart==0:
return Amount
elif DecimalPart > 0.51: #rounding up
return round((Amount+float(self.Config['SmallestCoin'])/2)/float(self.Config['SmallestCoin']))*float(self.Config['SmallestCoin'])
else:#rounding down
return round((Amount-float(self.Config['SmallestCoin'])/2)/float(self.Config['SmallestCoin']))*float(self.Config['SmallestCoin'])
def PaymentComplete(self,widget,data=None):
OpenCashDrawer = False
print "Rounded sale total = " + str(self.RoundToSmallestCoin(self.SaleTotal))
print "Total Payments = " + str(self.TotalPayments)
if (self.RoundToSmallestCoin(self.SaleTotal) - self.TotalPayments) > 0.009:
MessageBox = gtk.MessageDialog(self.Payment_Dialog, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, _('The sale cannot be accepted until sufficient payments have been tendered and entered.'))
MessageBox.run()
MessageBox.destroy()
print _('Insufficient payment entered')
return
else:
#Now process the sale into the database
#Get the POS transaction number
result = self.db.cursor()
result.execute("INSERT INTO transcounter VALUES (NULL)")
self.LastTransNo = result.lastrowid
InvoiceParameters = (self.LastTransNo, self.CustomerDetails['debtorno'], self.CustomerDetails['branchcode'], datetime.datetime.now(), self.CustomerDetails['salestype'], self.SaleTotal - self.TaxTotal, self.TaxTotal)
result.execute("INSERT INTO debtortrans (id, transno, type, debtorno, branchcode, trandate, tpe, ovamount, ovgst) VALUES (NULL,?,10,?,?,?,?,?,?)", InvoiceParameters)
DebtorTransID = result.lastrowid
#Now need to work out the amount for each tax authority - have to run through the lines on the order - or store by tax authority at the time of calculation would be neater.
#Now to add the stockmoves have to go through the self.SaleGrid_ListStore.iter
SaleLine_TreeIter = self.SaleEntryGrid_ListStore.get_iter_first()
while SaleLine_TreeIter:
StockID = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['SKU'])
#The Gross Price (inclusive of taxes)
Price = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['SellPrice'])
Quantity = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['Quantity'])
TaxCatID = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['TaxCatID'])
Remarks = self.SaleEntryGrid_ListStore.get_value(SaleLine_TreeIter, self.Col['Remarks'])
#We actually want to store the tax exclusive value - we have the total gross from debtortrans ovamount+ ovgst
#the net price must be sent back to webERP for creating the invoice in webERP
#also the tax exclusive numbers are more useful for sales analysis
try:
LineTaxRate = self.TaxRate[TaxCatID]
except:
LineTaxRate =0
Price /= (1+LineTaxRate)
StockMovesParameters = (StockID,self.LastTransNo, Price, Quantity, Remarks)
result.execute("INSERT INTO stockmoves (stkmoveno, stockid, type, transno, price, qty, reference) VALUES (NULL,?,10,?,?,?,?)", StockMovesParameters)
#And while we are here let's add the stockmovestaxes too ... a bit more tricky
StockMoveNo = result.lastrowid
TaxOrder = 0
AccumTax = 0
for TaxAuthority, Tax in self.Taxes[TaxCatID].items():
print 'TaxCatID = ', TaxCatID , ' TaxAuthority = ', TaxAuthority
if Tax['TaxOnTax']==1:
self.Taxes[TaxCatID][TaxAuthority]['Amount'] += Tax['Rate']*(Price*Quantity+AccumTax)
else:
self.Taxes[TaxCatID][TaxAuthority]['Amount'] += Tax['Rate']*Price*Quantity
AccumTax += self.Taxes[TaxCatID][TaxAuthority]['Amount']
StkMoveTaxesParameters = (StockMoveNo,TaxAuthority,Tax['Rate'],Tax['TaxOnTax'],TaxOrder)
result.execute("INSERT INTO stockmovestaxes (stkmoveno,taxauthid,taxrate,taxontax,taxcalculationorder) VALUES (?,?,?,?,?)",StkMoveTaxesParameters)
TaxOrder +=1
SaleLine_TreeIter = self.SaleEntryGrid_ListStore.iter_next(SaleLine_TreeIter)
# end loop through all items in the SalesEntryGrid_ListStore
for TaxAuthority, Tax in self.Taxes[TaxCatID].items():
InvoiceTaxParameters = (DebtorTransID, TaxAuthority, Tax['Amount'])
result.execute("INSERT INTO debtortranstaxes( debtortransid, taxauthid, taxamount) VALUES (?,?,?)",InvoiceTaxParameters)
#Now add the debtortrans for the payments made
#Need to work out if there was any rounding due to coins
Change = self.RoundToSmallestCoin(self.TotalPayments - self.SaleTotal)
if Change > 0 :
ChangeEntered = False
else:
ChangeEntered = True
#PaymentTotal = self.TotalPayments - self.RoundToSmallestCoin(self.TotalPayments - self.SaleTotal)
Rounding = self.SaleTotal - self.TotalPayments + Change
if Rounding !=0:
RoundingEntered = False
else:
RoundingEntered = True
Payment_TreeIter = self.Payment_ListStore.get_iter_first()
while Payment_TreeIter:
PaymentMethod = int(self.Payment_ListStore.get_value(Payment_TreeIter, self.PaymentMethods['ID']))
PaymentAmount = float(self.Payment_ListStore.get_value(Payment_TreeIter, self.PaymentMethods['Amount']))
if RoundingEntered == False:
RoundingAmount = Rounding
RoundingEntered = True
else:
RoundingAmount =0
if (int(self.Config['CashPaymentMethodID'])==PaymentMethod):
#Need to take off any change given from the payments made
PaymentAmount -= Change
ChangeEntered = True
PaymentParameters = (self.LastTransNo, self.CustomerDetails['debtorno'], datetime.datetime.now(), PaymentAmount, RoundingAmount, PaymentMethod)
OpenCashDrawer = True
else:
PaymentParameters = (self.LastTransNo, self.CustomerDetails['debtorno'], datetime.datetime.now(), PaymentAmount, RoundingAmount, PaymentMethod)
NeedCashDrawerParameters = (PaymentMethod,)
result.execute("SELECT opencashdrawer FROM paymentmethods WHERE paymentid=?",NeedCashDrawerParameters)
CashDrawerRow = result.fetchone()
if CashDrawerRow != None:
if CashDrawerRow['opencashdrawer']==1:
OpenCashDrawer = True
# end if its a cash payment method or not
result.execute("INSERT INTO debtortrans (id, transno, type, debtorno, trandate, ovamount, ovdiscount, paymentmethod) VALUES (NULL,?,12,?,?,?,?,?)", PaymentParameters)
Payment_TreeIter = self.Payment_ListStore.iter_next(Payment_TreeIter)
# end loop through all items in the Payment_ListStore
if ChangeEntered==False:
PaymentParameters = (self.LastTransNo, self.CustomerDetails['debtorno'], datetime.datetime.now(), -Change, 0, int(self.Config['CashPaymentMethodID']))
OpenCashDrawer = True
ChangeEntered = True
result.execute("INSERT INTO debtortrans (id, transno, type, debtorno, trandate, ovamount, ovdiscount, paymentmethod) VALUES (NULL,?,12,?,?,?,?,?)", PaymentParameters)
self.db.commit()
if OpenCashDrawer==True:
if self.ReceiptPrinter is None:
MessageBox = gtk.MessageDialog(self.MainWindow, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,_('Cannot connect to a receipt printer. The cash drawer cannot be opened without one being connected to the receipt printer!'))
MessageBox.run()
MessageBox.destroy()
else:
try:
self.ReceiptPrinter.cashdraw(2)
except:
print _('Could not open cashdrawer')
if (self.Config['AutoPrintReceipt']=='1' or self.Config['AutoPrintReceipt'].upper()=='YES'):
self.PrintReceipt(self.LastTransNo)
#if the Payments are greater than the sale by more than the smallest currency denomination
if Change > float(self.Config['SmallestCoin']):
#if the SaleTotal< TotalPayments the show the amount of change in a dialog box
MessageBox = gtk.MessageDialog(self.Payment_Dialog, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, None )
MessageBox.set_markup('<b>' + _('Change') + ': ' + "{0: .2f}".format(Change) + '</b>')
OpenCashDrawer = True
MessageBox.run()
MessageBox.destroy()
#clear the SaleListStore