-
Notifications
You must be signed in to change notification settings - Fork 1
/
gncli.py
executable file
·1955 lines (1476 loc) · 64.7 KB
/
gncli.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/python3
'''
gncli.py -- A command line interface for GnuCash
Copyright (C) 2019 Tom Lofts <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, contact:
Free Software Foundation Voice: +1-617-542-5942
51 Franklin Street, Fifth Floor Fax: +1-617-542-2652
Boston, MA 02110-1301, USA [email protected]
@author Tom Lofts <[email protected]>
'''
import gnucash
import gnucash_simple
import json
import atexit
from functools import wraps
import re
import sys
# to resolve bug in http://stackoverflow.com/questions/2427240/thread-safe-equivalent-to-pythons-time-strptime
import _strptime
import datetime
from decimal import Decimal
from gnucash.gnucash_business import Vendor, Bill, Entry, GncNumeric, \
Customer, Invoice, Split, Account, Transaction
from gnucash.gnucash_business import \
GNC_AMT_TYPE_VALUE, \
GNC_AMT_TYPE_PERCENT
from gnucash import \
QOF_QUERY_AND, \
QOF_QUERY_OR, \
QOF_QUERY_NAND, \
QOF_QUERY_NOR, \
QOF_QUERY_XOR
from gnucash import \
QOF_STRING_MATCH_NORMAL, \
QOF_STRING_MATCH_CASEINSENSITIVE
from gnucash import \
QOF_COMPARE_LT, \
QOF_COMPARE_LTE, \
QOF_COMPARE_EQUAL, \
QOF_COMPARE_GT, \
QOF_COMPARE_GTE, \
QOF_COMPARE_NEQ
from gnucash import \
INVOICE_TYPE
from gnucash import \
INVOICE_IS_PAID
from gnucash.gnucash_core_c import \
GNC_INVOICE_CUST_INVOICE, \
GNC_INVOICE_VEND_INVOICE, \
INVOICE_IS_POSTED
# define globals for compatiblity with Gnucash rest
session = None
def get_customers(book):
query = gnucash.Query()
query.search_for('gncCustomer')
query.set_book(book)
customers = []
for result in query.run():
customers.append(gnucash_simple.customerToDict(
gnucash.gnucash_business.Customer(instance=result)))
query.destroy()
return customers
def get_customer(book, id):
customer = book.CustomerLookupByID(id)
if customer is None:
return None
else:
return gnucash_simple.customerToDict(customer)
def get_vendors(book):
query = gnucash.Query()
query.search_for('gncVendor')
query.set_book(book)
vendors = []
for result in query.run():
vendors.append(gnucash_simple.vendorToDict(
gnucash.gnucash_business.Vendor(instance=result)))
query.destroy()
return vendors
def get_vendor(book, id):
vendor = book.VendorLookupByID(id)
if vendor is None:
return None
else:
return gnucash_simple.vendorToDict(vendor)
def get_accounts(book):
accounts = gnucash_simple.accountToDict(book.get_root_account())
return accounts
def get_account(book, guid):
account_guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(guid, account_guid)
account = account_guid.AccountLookup(book)
if account is None:
return None
account = gnucash_simple.accountToDict(account)
if account is None:
return None
else:
return account
def get_account_splits(book, guid, date_posted_from, date_posted_to):
account_guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(guid, account_guid)
query = gnucash.Query()
query.search_for('Split')
query.set_book(book)
SPLIT_TRANS= 'trans'
QOF_DATE_MATCH_NORMAL = 1
TRANS_DATE_POSTED = 'date-posted'
if date_posted_from is not None:
try:
date_posted_from = datetime.datetime.strptime(date_posted_from, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDatePostedFrom',
'The date posted from must be provided in the form YYYY-MM-DD',
{'field': 'date_posted_from'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_GTE, QOF_DATE_MATCH_NORMAL, date_posted_from.date())
param_list = [SPLIT_TRANS, TRANS_DATE_POSTED]
query.add_term(param_list, pred_data, QOF_QUERY_AND)
if date_posted_to is not None:
try:
date_posted_to = datetime.datetime.strptime(date_posted_to, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDatePostedTo',
'The date posted to must be provided in the form YYYY-MM-DD',
{'field': 'date_posted_from'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_LTE, QOF_DATE_MATCH_NORMAL, date_posted_to.date())
param_list = [SPLIT_TRANS, TRANS_DATE_POSTED]
query.add_term(param_list, pred_data, QOF_QUERY_AND)
SPLIT_ACCOUNT = 'account'
QOF_PARAM_GUID = 'guid'
if guid is not None:
gnucash.gnucash_core.GUIDString(guid, account_guid)
query.add_guid_match(
[SPLIT_ACCOUNT, QOF_PARAM_GUID], account_guid, QOF_QUERY_AND)
splits = []
for split in query.run():
splits.append(gnucash_simple.splitToDict(
gnucash.gnucash_business.Split(instance=split),
['account', 'transaction', 'other_split']))
query.destroy()
return splits
# Might be a good idea to pass though these options as properties instead
def get_invoices(book, properties):
defaults = [
'customer',
'is_posted',
'is_paid',
'is_active',
'date_opened_from',
'date_opened_to',
'date_due_to',
'date_due_from',
'date_posted_to',
'date_posted_from'
]
for default in defaults:
if default not in properties.keys():
properties[default] = None
query = gnucash.Query()
query.search_for('gncInvoice')
query.set_book(book)
if properties['is_posted'] == 0:
query.add_boolean_match([INVOICE_IS_POSTED], False, QOF_QUERY_AND)
elif properties['is_posted'] == 1:
query.add_boolean_match([INVOICE_IS_POSTED], True, QOF_QUERY_AND)
if properties['is_paid'] == 0:
query.add_boolean_match([INVOICE_IS_PAID], False, QOF_QUERY_AND)
elif properties['is_paid'] == 1:
query.add_boolean_match([INVOICE_IS_PAID], True, QOF_QUERY_AND)
# active = JOB_IS_ACTIVE
if properties['is_active'] == 0:
query.add_boolean_match(['active'], False, QOF_QUERY_AND)
elif properties['is_active'] == 1:
query.add_boolean_match(['active'], True, QOF_QUERY_AND)
QOF_PARAM_GUID = 'guid'
INVOICE_OWNER = 'owner'
if properties['customer'] is not None:
customer_guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(properties['customer'], customer_guid)
query.add_guid_match(
[INVOICE_OWNER, QOF_PARAM_GUID], customer_guid, QOF_QUERY_AND)
if properties['date_due_from'] is not None:
try:
properties['date_due_from'] = datetime.datetime.strptime(properties['date_due_from'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateDueFrom',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_due_from'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_GTE, 2, properties['date_due_from'].date())
query.add_term(['date_due'], pred_data, QOF_QUERY_AND)
if properties['date_due_to'] is not None:
try:
properties['date_due_to'] = datetime.datetime.strptime(properties['date_due_to'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateDueTo',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_due_to'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_LTE, 2, properties['date_due_to'].date())
query.add_term(['date_due'], pred_data, QOF_QUERY_AND)
if properties['date_opened_from'] is not None:
try:
properties['date_opened_from'] = datetime.datetime.strptime(properties['date_opened_from'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateOpenedFrom',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_opened_from'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_GTE, 2, properties['date_opened_from'].date())
query.add_term(['date_opened'], pred_data, QOF_QUERY_AND)
if properties['date_opened_to'] is not None:
try:
properties['date_opened_to'] = datetime.datetime.strptime(properties['date_opened_to'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateOpenedTo',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_opened_to'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_LTE, 2, properties['date_opened_to'].date())
query.add_term(['date_opened'], pred_data, QOF_QUERY_AND)
if properties['date_posted_from'] is not None:
try:
properties['date_posted_from'] = datetime.datetime.strptime(properties['date_posted_from'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDatePostedFrom',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_posted_from'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_GTE, 2, properties['date_posted_from'].date())
query.add_term(['date_posted'], pred_data, QOF_QUERY_AND)
if properties['date_posted_to'] is not None:
try:
properties['date_posted_to'] = datetime.datetime.strptime(properties['date_posted_to'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDatePostedTo',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_posted_to'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_LTE, 2, properties['date_posted_to'].date())
query.add_term(['date_posted'], pred_data, QOF_QUERY_AND)
# return only invoices
pred_data = gnucash.gnucash_core.QueryInt32Predicate(QOF_COMPARE_EQUAL,
GNC_INVOICE_CUST_INVOICE)
query.add_term([INVOICE_TYPE], pred_data, QOF_QUERY_AND)
invoices = []
for result in query.run():
invoices.append(gnucash_simple.invoiceToDict(
gnucash.gnucash_business.Invoice(instance=result)))
query.destroy()
return invoices
def get_bills(book, properties):
# define defaults and set to None
defaults = [
'customer',
'is_paid',
'is_active',
'date_opened_from',
'date_opened_to',
'date_due_to',
'date_due_from',
'date_posted_to',
'date_posted_from'
]
for default in defaults:
if default not in properties.keys():
properties[default] = None
query = gnucash.Query()
query.search_for('gncInvoice')
query.set_book(book)
if properties['is_paid'] == 0:
query.add_boolean_match([INVOICE_IS_PAID], False, QOF_QUERY_AND)
elif properties['is_paid'] == 1:
query.add_boolean_match([INVOICE_IS_PAID], True, QOF_QUERY_AND)
# active = JOB_IS_ACTIVE
if properties['is_active'] == 0:
query.add_boolean_match(['active'], False, QOF_QUERY_AND)
elif properties['is_active'] == 1:
query.add_boolean_match(['active'], True, QOF_QUERY_AND)
QOF_PARAM_GUID = 'guid'
INVOICE_OWNER = 'owner'
if properties['customer'] is not None:
customer_guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(properties['customer'], customer_guid)
query.add_guid_match(
[INVOICE_OWNER, QOF_PARAM_GUID], customer_guid, QOF_QUERY_AND)
# These are identical to invoices...
if properties['date_due_from'] is not None:
try:
properties['date_due_from'] = datetime.datetime.strptime(properties['date_due_from'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateDueFrom',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_due_from'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_GTE, 2, properties['date_due_from'].date())
query.add_term(['date_due'], pred_data, QOF_QUERY_AND)
if properties['date_due_to'] is not None:
try:
properties['date_due_to'] = datetime.datetime.strptime(properties['date_due_to'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateDueTo',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_due_to'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_LTE, 2, properties['date_due_to'].date())
query.add_term(['date_due'], pred_data, QOF_QUERY_AND)
if properties['date_opened_from'] is not None:
try:
properties['date_opened_from'] = datetime.datetime.strptime(properties['date_opened_from'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateOpenedFrom',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_opened_from'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_GTE, 2, properties['date_opened_from'].date())
query.add_term(['date_opened'], pred_data, QOF_QUERY_AND)
if properties['date_opened_to'] is not None:
try:
properties['date_opened_to'] = datetime.datetime.strptime(properties['date_opened_to'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateOpenedTo',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_opened_to'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_LTE, 2, properties['date_opened_to'].date())
query.add_term(['date_opened'], pred_data, QOF_QUERY_AND)
if properties['date_posted_from'] is not None:
try:
properties['date_posted_from'] = datetime.datetime.strptime(properties['date_posted_from'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDatePostedFrom',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_posted_from'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_GTE, 2, properties['date_posted_from'].date())
query.add_term(['date_posted'], pred_data, QOF_QUERY_AND)
if properties['date_posted_to'] is not None:
try:
properties['date_posted_to'] = datetime.datetime.strptime(properties['date_posted_to'], "%Y-%m-%d")
except ValueError:
raise Error('InvalidDatePostedTo',
'The date due from to must be provided in the form YYYY-MM-DD',
{'field': 'date_posted_to'})
pred_data = gnucash.gnucash_core.QueryDatePredicate(
QOF_COMPARE_LTE, 2, properties['date_posted_to'].date())
query.add_term(['date_posted'], pred_data, QOF_QUERY_AND)
# return only bills (2 = bills)
pred_data = gnucash.gnucash_core.QueryInt32Predicate(QOF_COMPARE_EQUAL, 2)
query.add_term([INVOICE_TYPE], pred_data, QOF_QUERY_AND)
bills = []
for result in query.run():
bills.append(gnucash_simple.billToDict(
gnucash.gnucash_business.Bill(instance=result)))
query.destroy()
return bills
def get_gnucash_invoice(book, id):
# we don't use book.InvoicelLookupByID(id) as this is identical to
# book.BillLookupByID(id) so can return the same object if they share IDs
query = gnucash.Query()
query.search_for('gncInvoice')
query.set_book(book)
# return only invoices
pred_data = gnucash.gnucash_core.QueryInt32Predicate(QOF_COMPARE_EQUAL,
GNC_INVOICE_CUST_INVOICE)
query.add_term([INVOICE_TYPE], pred_data, QOF_QUERY_AND)
INVOICE_ID = 'id'
pred_data = gnucash.gnucash_core.QueryStringPredicate(
QOF_COMPARE_EQUAL, id, QOF_STRING_MATCH_NORMAL, False)
query.add_term([INVOICE_ID], pred_data, QOF_QUERY_AND)
invoice = None
for result in query.run():
invoice = gnucash.gnucash_business.Invoice(instance=result)
query.destroy()
return invoice
def get_gnucash_bill(book ,id):
# we don't use book.InvoicelLookupByID(id) as this is identical to
# book.BillLookupByID(id) so can return the same object if they share IDs
query = gnucash.Query()
query.search_for('gncInvoice')
query.set_book(book)
# return only bills (2 = bills)
pred_data = gnucash.gnucash_core.QueryInt32Predicate(QOF_COMPARE_EQUAL, 2)
query.add_term([INVOICE_TYPE], pred_data, QOF_QUERY_AND)
INVOICE_ID = 'id'
pred_data = gnucash.gnucash_core.QueryStringPredicate(
QOF_COMPARE_EQUAL, id, QOF_STRING_MATCH_NORMAL, False)
query.add_term([INVOICE_ID], pred_data, QOF_QUERY_AND)
bill = None
for result in query.run():
bill = gnucash.gnucash_business.Bill(instance=result)
query.destroy()
return bill
def get_invoice(book, id):
return gnucash_simple.invoiceToDict(get_gnucash_invoice(book, id))
def pay_invoice(book, id, transaction_guid, posted_account_guid, transfer_account_guid,
payment_date, memo, num, auto_pay):
# Where is posted_account_guid used - it's in the dialog, but we're not using it
invoice = get_gnucash_invoice(book, id)
if invoice is None:
raise Error('NoInvoice', 'An invoice with this ID does not exist',
{'field': 'id'})
if transaction_guid == '':
transaction = None
else:
guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(transaction_guid, guid)
transaction = guid.TransLookup(book)
if transaction is None:
raise Error('NoTransaction', 'No transaction exists with this GUID',
{'field': 'transaction_guid'})
try:
payment_date = datetime.datetime.strptime(payment_date, "%Y-%m-%d")
except ValueError:
raise Error('InvalidPaymentDate',
'The payment date must be provided in the form YYYY-MM-DD',
{'field': 'payment_date'})
account_guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(transfer_account_guid, account_guid)
transfer_account = account_guid.AccountLookup(book)
if transfer_account is None:
raise Error('NoTransferAccount', 'No account exists with this GUID',
{'field': 'transfer_account_guid'})
invoice.ApplyPayment(transaction, transfer_account, invoice.GetTotal(), GncNumeric(0),
payment_date, memo, num)
return gnucash_simple.invoiceToDict(invoice)
def pay_bill(book, id, posted_account_guid, transfer_account_guid, payment_date,
memo, num, auto_pay):
# The posted_account_guid is not actually used in bill.ApplyPayment - why is it on the payment screen?
bill = get_gnucash_bill(book, id)
if bill is None:
raise Error('NoBill', 'A bill with this ID does not exist',
{'field': 'id'})
try:
payment_date = datetime.datetime.strptime(payment_date, "%Y-%m-%d")
except ValueError:
raise Error('InvalidPaymentDate',
'The payment date must be provided in the form YYYY-MM-DD',
{'field': 'payment_date'})
account_guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(transfer_account_guid, account_guid)
transfer_account = account_guid.AccountLookup(book)
if transfer_account is None:
raise Error('NoTransferAccount', 'No account exists with this GUID',
{'field': 'transfer_account_guid'})
# We pay the negitive total as the bill as this seemed to cause issues
# with the split not being set correctly and not being marked as paid
bill.ApplyPayment(None, transfer_account, bill.GetTotal().neg(), GncNumeric(0),
payment_date, memo, num)
return gnucash_simple.billToDict(bill)
def get_bill(book, id):
return gnucash_simple.billToDict(get_gnucash_bill(book, id))
def add_vendor(book, id, currency_mnumonic, name, contact, address_line_1,
address_line_2, address_line_3, address_line_4, phone, fax, email):
if name == '':
raise Error('NoVendorName', 'A name must be entered for this company',
{'field': 'name'})
if (address_line_1 == ''
and address_line_2 == ''
and address_line_3 == ''
and address_line_4 == ''):
raise Error('NoVendorAddress',
'An address must be entered for this company',
{'field': 'address'})
commod_table = book.get_table()
currency = commod_table.lookup('CURRENCY', currency_mnumonic)
if currency is None:
raise Error('InvalidVendorCurrency',
'A valid currency must be supplied for this vendor',
{'field': 'currency'})
if id is None:
id = book.VendorNextID()
vendor = Vendor(book, id, currency, name)
address = vendor.GetAddr()
address.SetName(contact)
address.SetAddr1(address_line_1)
address.SetAddr2(address_line_2)
address.SetAddr3(address_line_3)
address.SetAddr4(address_line_4)
address.SetPhone(phone)
address.SetFax(fax)
address.SetEmail(email)
return gnucash_simple.vendorToDict(vendor)
def add_customer(book, id, currency_mnumonic, name, contact, address_line_1,
address_line_2, address_line_3, address_line_4, phone, fax, email):
if name == '':
raise Error('NoCustomerName',
'A name must be entered for this company', {'field': 'name'})
if (address_line_1 == ''
and address_line_2 == ''
and address_line_3 == ''
and address_line_4 == ''):
raise Error('NoCustomerAddress',
'An address must be entered for this company',
{'field': 'address'})
commod_table = book.get_table()
currency = commod_table.lookup('CURRENCY', currency_mnumonic)
if currency is None:
raise Error('InvalidCustomerCurrency',
'A valid currency must be supplied for this customer',
{'field': 'currency'})
if id is None:
id = book.CustomerNextID()
customer = Customer(book, id, currency, name)
address = customer.GetAddr()
address.SetName(contact)
address.SetAddr1(address_line_1)
address.SetAddr2(address_line_2)
address.SetAddr3(address_line_3)
address.SetAddr4(address_line_4)
address.SetPhone(phone)
address.SetFax(fax)
address.SetEmail(email)
return gnucash_simple.customerToDict(customer)
def update_customer(book, id, name, contact, address_line_1, address_line_2,
address_line_3, address_line_4, phone, fax, email):
customer = book.CustomerLookupByID(id)
if customer is None:
raise Error('NoCustomer', 'A customer with this ID does not exist',
{'field': 'id'})
if name == '':
raise Error('NoCustomerName',
'A name must be entered for this company', {'field': 'name'})
if (address_line_1 == ''
and address_line_2 == ''
and address_line_3 == ''
and address_line_4 == ''):
raise Error('NoCustomerAddress',
'An address must be entered for this company',
{'field': 'address'})
customer.SetName(name)
address = customer.GetAddr()
address.SetName(contact)
address.SetAddr1(address_line_1)
address.SetAddr2(address_line_2)
address.SetAddr3(address_line_3)
address.SetAddr4(address_line_4)
address.SetPhone(phone)
address.SetFax(fax)
address.SetEmail(email)
return gnucash_simple.customerToDict(customer)
def add_invoice(book, id, customer_id, currency_mnumonic, date_opened, notes):
# Check customer ID is provided to avoid "CRIT <qof> qof_query_string_predicate: assertion '*str != '\0'' failed" error
if customer_id == '':
raise Error('NoCustomer',
'A customer ID must be provided', {'field': 'id'})
customer = book.CustomerLookupByID(customer_id)
if customer is None:
raise Error('NoCustomer',
'A customer with this ID does not exist', {'field': 'id'})
if id is None:
id = book.InvoiceNextID(customer)
try:
date_opened = datetime.datetime.strptime(date_opened, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateOpened',
'The date opened must be provided in the form YYYY-MM-DD',
{'field': 'date_opened'})
if currency_mnumonic is None:
currency_mnumonic = customer.GetCurrency().get_mnemonic()
commod_table = book.get_table()
currency = commod_table.lookup('CURRENCY', currency_mnumonic)
if currency is None:
raise Error('InvalidInvoiceCurrency',
'A valid currency must be supplied for this invoice',
{'field': 'currency'})
elif currency.get_mnemonic() != customer.GetCurrency().get_mnemonic():
# Does Gnucash actually enforce this?
raise Error('MismatchedInvoiceCurrency',
'The currency of this invoice does not match the customer',
{'field': 'currency'})
invoice = Invoice(book, id, currency, customer, date_opened.date())
invoice.SetNotes(notes)
return gnucash_simple.invoiceToDict(invoice)
def update_invoice(book, id, customer_id, currency_mnumonic, date_opened,
notes, posted, posted_account_guid, posted_date, due_date, posted_memo,
posted_accumulatesplits, posted_autopay):
invoice = get_gnucash_invoice(book, id)
if invoice is None:
raise Error('NoInvoice',
'An invoice with this ID does not exist',
{'field': 'id'})
customer = book.CustomerLookupByID(customer_id)
if customer is None:
raise Error('NoCustomer', 'A customer with this ID does not exist',
{'field': 'customer_id'})
try:
date_opened = datetime.datetime.strptime(date_opened, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateOpened',
'The date opened must be provided in the form YYYY-MM-DD',
{'field': 'date_opened'})
if posted_date == '':
if posted == 1:
raise Error('NoDatePosted',
'The date posted must be supplied when posted=1',
{'field': 'date_posted'})
else:
try:
posted_date = datetime.datetime.strptime(posted_date, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDatePosted',
'The date posted must be provided in the form YYYY-MM-DD',
{'field': 'posted_date'})
if due_date == '':
if posted == 1:
raise Error('NoDateDue',
'The due date must be supplied when posted=1',
{'field': 'due_date'})
else:
try:
due_date = datetime.datetime.strptime(due_date, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateDue',
'The due date must be provided in the form YYYY-MM-DD',
{'field': 'due_date'})
if posted_account_guid == '':
if posted == 1:
raise Error('NoPostedAccountGuid',
'The posted account GUID must be supplied when posted=1',
{'field': 'posted_account_guid'})
else:
guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(posted_account_guid, guid)
posted_account = guid.AccountLookup(book)
if posted_account is None:
raise Error('NoAccount',
'No account exists with the posted account GUID',
{'field': 'posted_account_guid'})
invoice.SetOwner(customer)
invoice.SetDateOpened(date_opened)
invoice.SetNotes(notes)
# post if currently unposted and posted=1
if ((invoice.GetDatePosted() is None or invoice.GetDatePosted().strftime("%Y-%m-%d") == '1970-01-01') and posted == 1):
invoice.PostToAccount(posted_account, posted_date, due_date,
posted_memo, posted_accumulatesplits, posted_autopay)
return gnucash_simple.invoiceToDict(invoice)
def update_bill(book, id, vendor_id, currency_mnumonic, date_opened, notes,
posted, posted_account_guid, posted_date, due_date, posted_memo,
posted_accumulatesplits, posted_autopay):
bill = get_gnucash_bill(book, id)
if bill is None:
raise Error('NoBill', 'A bill with this ID does not exist',
{'field': 'id'})
vendor = book.VendorLookupByID(vendor_id)
if vendor is None:
raise Error('NoVendor',
'A vendor with this ID does not exist',
{'field': 'vendor_id'})
try:
date_opened = datetime.datetime.strptime(date_opened, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateOpened',
'The date opened must be provided in the form YYYY-MM-DD',
{'field': 'date_opened'})
if posted_date == '':
if posted == 1:
raise Error('NoDatePosted',
'The date posted must be supplied when posted=1',
{'field': 'date_posted'})
else:
try:
posted_date = datetime.datetime.strptime(posted_date, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDatePosted',
'The date posted must be provided in the form YYYY-MM-DD',
{'field': 'posted_date'})
if due_date == '':
if posted == 1:
raise Error('NoDateDue',
'The due date must be supplied when posted=1',
{'field': 'date_sue'})
else:
try:
due_date = datetime.datetime.strptime(due_date, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateDue',
'The due date must be provided in the form YYYY-MM-DD',
{'field': 'due_date'})
if posted_account_guid == '':
if posted == 1:
raise Error('NoPostedAccountGuid',
'The posted account GUID must be supplied when posted=1',
{'field': 'posted_account_guid'})
else:
guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(posted_account_guid, guid)
posted_account = guid.AccountLookup(book)
if posted_account is None:
raise Error('NoAccount',
'No account exists with the posted account GUID',
{'field': 'posted_account_guid'})
bill.SetOwner(vendor)
bill.SetDateOpened(date_opened)
bill.SetNotes(notes)
# post if currently unposted and posted=1
if bill.GetDatePosted() is None and posted == 1:
bill.PostToAccount(posted_account, posted_date, due_date, posted_memo,
posted_accumulatesplits, posted_autopay)
return gnucash_simple.billToDict(bill)
def add_entry(book, invoice_id, date, description, account_guid, quantity,
price, discount_type, discount):
invoice = get_gnucash_invoice(book, invoice_id)
if invoice is None:
raise Error('NoInvoice',
'No invoice exists with this ID', {'field': 'invoice_id'})
try:
date = datetime.datetime.strptime(date, "%Y-%m-%d")
except ValueError:
raise Error('InvalidDateOpened',
'The date opened must be provided in the form YYYY-MM-DD',
{'field': 'date'})
# Only value based discounts are supported
if discount_type != GNC_AMT_TYPE_VALUE:
raise Error('UnsupportedDiscountType', 'Only value based discounts are currently supported',
{'field': 'discount_type'})
guid = gnucash.gnucash_core.GUID()
gnucash.gnucash_core.GUIDString(account_guid, guid)
account = guid.AccountLookup(book)
if account is None:
raise Error('NoAccount', 'No account exists with this GUID',
{'field': 'account_guid'})
try:
quantity = Decimal(quantity).quantize(Decimal('.01'))
except ArithmeticError:
raise Error('InvalidQuantity', 'This quantity is not valid',
{'field': 'quantity'})
try:
price = Decimal(price).quantize(Decimal('.01'))
except ArithmeticError:
raise Error('InvalidPrice', 'This price is not valid',
{'field': 'price'})
# Currently only value based discounts are supported
try:
discount = Decimal(discount).quantize(Decimal('.01'))
except ArithmeticError:
raise Error('InvalidDiscount', 'This discount is not valid',
{'field': 'discount'})
entry = Entry(book, invoice, date.date())
entry.SetDateEntered(datetime.datetime.now())
entry.SetDescription(description)
entry.SetInvAccount(account)
entry.SetQuantity(gnc_numeric_from_decimal(quantity))
entry.SetInvPrice(gnc_numeric_from_decimal(price))
# Do we need to set this?
# entry.SetInvDiscountHow()
entry.SetInvDiscountType(discount_type)
# Currently only value based discounts are supported
entry.SetInvDiscount(gnc_numeric_from_decimal(discount))