-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathaccount.py
3228 lines (2859 loc) · 117 KB
/
account.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
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import datetime
import operator
from collections import defaultdict
from decimal import Decimal
from functools import wraps
from itertools import zip_longest
from dateutil.relativedelta import relativedelta
from sql import Column, Literal, Null, Window
from sql.aggregate import Count, Max, Min, Sum
from sql.conditionals import Case, Coalesce
from trytond import backend
from trytond.i18n import gettext
from trytond.model import (
Check, ModelSQL, ModelView, Unique, fields, sequence_ordered, tree)
from trytond.model.exceptions import AccessError
from trytond.modules.currency.fields import Monetary
from trytond.pool import Pool
from trytond.pyson import Bool, Eval, If, PYSONEncoder
from trytond.report import Report
from trytond.tools import grouped_slice, lstrip_wildcard, reduce_ids
from trytond.transaction import Transaction
from trytond.wizard import (
Button, StateAction, StateTransition, StateView, Wizard)
from .common import ActivePeriodMixin, PeriodMixin
from .exceptions import (
AccountValidationError, ChartWarning, SecondCurrencyError)
def inactive_records(func):
@wraps(func)
def wrapper(*args, **kwargs):
with Transaction().set_context(active_test=False):
return func(*args, **kwargs)
return wrapper
def TypeMixin(template=False):
class Mixin:
__slots__ = ()
name = fields.Char('Name', required=True)
statement = fields.Selection([
(None, ""),
('balance', "Balance"),
('income', "Income"),
('off-balance', "Off-Balance"),
], "Statement",
states={
'required': Bool(Eval('parent')),
})
assets = fields.Boolean(
"Assets",
states={
'invisible': Eval('statement') != 'balance',
})
receivable = fields.Boolean(
"Receivable",
domain=[
If((Eval('statement') != 'balance')
| ~Eval('assets', True),
('receivable', '=', False), ()),
],
states={
'invisible': ((Eval('statement') != 'balance')
| ~Eval('assets', True)),
})
stock = fields.Boolean(
"Stock",
domain=[
If(Eval('statement') == 'off-balance',
('stock', '=', False), ()),
],
states={
'invisible': Eval('statement') == 'off-balance',
})
payable = fields.Boolean(
"Payable",
domain=[
If((Eval('statement') != 'balance')
| Eval('assets', False),
('payable', '=', False), ()),
],
states={
'invisible': ((Eval('statement') != 'balance')
| Eval('assets', False)),
})
debt = fields.Boolean(
"Debt",
domain=[
If((Eval('statement') != 'balance')
| Eval('assets', False),
('debt', '=', False), ()),
],
states={
'invisible': ((Eval('statement') != 'balance')
| Eval('assets', False)),
},
help="Check to allow booking debt via supplier invoice.")
revenue = fields.Boolean(
"Revenue",
domain=[
If(Eval('statement') != 'income',
('revenue', '=', False), ()),
],
states={
'invisible': Eval('statement') != 'income',
})
expense = fields.Boolean(
"Expense",
domain=[
If(Eval('statement') != 'income',
('expense', '=', False), ()),
],
states={
'invisible': Eval('statement') != 'income',
})
if not template:
for fname in dir(Mixin):
field = getattr(Mixin, fname)
if not isinstance(field, fields.Field):
continue
field.states['readonly'] = (
Bool(Eval('template', -1)) & ~Eval('template_override', False))
return Mixin
class TypeTemplate(
TypeMixin(template=True), sequence_ordered(), tree(separator='\\'),
ModelSQL, ModelView):
'Account Type Template'
__name__ = 'account.account.type.template'
parent = fields.Many2One(
'account.account.type.template', "Parent", ondelete='RESTRICT',
domain=['OR',
If(Eval('statement') == 'off-balance',
('statement', '=', 'off-balance'),
If(Eval('statement') == 'balance',
('statement', '=', 'balance'),
('statement', '!=', 'off-balance')),
),
('statement', '=', None),
])
childs = fields.One2Many(
'account.account.type.template', 'parent', "Children")
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
table_h = cls.__table_handler__(module_name)
# Migration from 5.0: remove display_balance
table_h.drop_column('display_balance')
def _get_type_value(self, type=None):
'''
Set the values for account creation.
'''
res = {}
if not type or type.name != self.name:
res['name'] = self.name
if not type or type.sequence != self.sequence:
res['sequence'] = self.sequence
if not type or type.statement != self.statement:
res['statement'] = self.statement
if not type or type.assets != self.assets:
res['assets'] = self.assets
for boolean in [
'receivable', 'stock', 'payable', 'revenue', 'expense',
'debt']:
if not type or getattr(type, boolean) != getattr(self, boolean):
res[boolean] = getattr(self, boolean)
if not type or type.template != self:
res['template'] = self.id
return res
def create_type(self, company_id, template2type=None):
'''
Create recursively types based on template.
template2type is a dictionary with template id as key and type id as
value, used to convert template id into type. The dictionary is filled
with new types.
'''
pool = Pool()
Type = pool.get('account.account.type')
assert self.parent is None
if template2type is None:
template2type = {}
def create(templates):
values = []
created = []
for template in templates:
if template.id not in template2type:
vals = template._get_type_value()
vals['company'] = company_id
if template.parent:
vals['parent'] = template2type[template.parent.id]
else:
vals['parent'] = None
values.append(vals)
created.append(template)
types = Type.create(values)
for template, type_ in zip(created, types):
template2type[template.id] = type_.id
childs = [self]
while childs:
create(childs)
childs = sum((c.childs for c in childs), ())
class Type(
TypeMixin(), sequence_ordered(), tree(separator='\\'),
ModelSQL, ModelView):
'Account Type'
__name__ = 'account.account.type'
parent = fields.Many2One('account.account.type', 'Parent',
ondelete="RESTRICT",
states={
'readonly': (Bool(Eval('template', -1))
& ~Eval('template_override', False)),
},
domain=[
('company', '=', Eval('company', -1)),
])
childs = fields.One2Many('account.account.type', 'parent', 'Children',
domain=[
('company', '=', Eval('company', -1)),
])
currency = fields.Function(fields.Many2One(
'currency.currency', 'Currency'), 'get_currency')
amount = fields.Function(Monetary(
"Amount", currency='currency', digits='currency'),
'get_amount')
amount_cmp = fields.Function(Monetary(
"Amount", currency='currency', digits='currency'),
'get_amount_cmp')
company = fields.Many2One('company.company', 'Company', required=True,
ondelete="RESTRICT")
template = fields.Many2One('account.account.type.template', 'Template')
template_override = fields.Boolean('Override Template',
help="Check to override template definition",
states={
'invisible': ~Bool(Eval('template', -1)),
})
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
table_h = cls.__table_handler__(module_name)
# Migration from 5.0: remove display_balance
table_h.drop_column('display_balance')
@classmethod
def default_template_override(cls):
return False
@classmethod
def default_company(cls):
return Transaction().context.get('company')
def get_currency(self, name):
return self.company.currency.id
@classmethod
def get_amount(cls, types, name):
pool = Pool()
Account = pool.get('account.account')
GeneralLedger = pool.get('account.general_ledger.account')
context = Transaction().context
res = {}
for type_ in types:
res[type_.id] = Decimal('0.0')
childs = cls.search([
('parent', 'child_of', [t.id for t in types]),
])
type_sum = {}
for type_ in childs:
type_sum[type_.id] = Decimal('0.0')
if context.get('start_period') or context.get('end_period'):
start_period_ids = GeneralLedger.get_period_ids('start_%s' % name)
end_period_ids = GeneralLedger.get_period_ids('end_%s' % name)
period_ids = list(
set(end_period_ids).difference(set(start_period_ids)))
else:
period_ids = None
with Transaction().set_context(periods=period_ids):
accounts = Account.search([
('type', 'in', [t.id for t in childs]),
])
debit_credit_accounts = Account.search([
('type', '!=', None),
['OR',
('debit_type', 'in', [t.id for t in childs]),
('credit_type', 'in', [t.id for t in childs]),
],
])
for account in accounts:
balance = account.credit - account.debit
if ((not account.debit_type or balance > 0)
and (not account.credit_type or balance < 0)):
type_sum[account.type.id] += balance
for account in debit_credit_accounts:
balance = account.credit - account.debit
if account.debit_type and balance < 0:
type_sum[account.debit_type.id] += balance
elif account.credit_type and balance > 0:
type_sum[account.credit_type.id] += balance
for type_ in types:
childs = cls.search([
('parent', 'child_of', [type_.id]),
])
for child in childs:
res[type_.id] += type_sum[child.id]
res[type_.id] = type_.currency.round(res[type_.id])
if type_.statement == 'balance' and type_.assets:
res[type_.id] = - res[type_.id]
return res
@classmethod
def get_amount_cmp(cls, types, name):
transaction = Transaction()
current = transaction.context
if not current.get('comparison'):
return dict.fromkeys([t.id for t in types], None)
new = {}
for key, value in current.items():
if key.endswith('_cmp'):
new[key[:-4]] = value
with transaction.set_context(new):
return cls.get_amount(types, name)
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('/tree/field[@name="amount_cmp"]', 'tree_invisible',
~Eval('comparison', False)),
]
@classmethod
def copy(cls, types, default=None):
if default is None:
default = {}
else:
default = default.copy()
default.setdefault('template', None)
return super().copy(types, default=default)
@classmethod
def delete(cls, types):
types = cls.search([
('parent', 'child_of', [t.id for t in types]),
])
super(Type, cls).delete(types)
def update_type(self, template2type=None):
'''
Update recursively types based on template.
template2type is a dictionary with template id as key and type id as
value, used to convert template id into type. The dictionary is filled
with new types
'''
if template2type is None:
template2type = {}
values = []
childs = [self]
while childs:
for child in childs:
if child.template:
if not child.template_override:
vals = child.template._get_type_value(type=child)
if vals:
values.append([child])
values.append(vals)
template2type[child.template.id] = child.id
childs = sum((c.childs for c in childs), ())
if values:
self.write(*values)
# Update parent
to_save = []
childs = [self]
while childs:
for child in childs:
if child.template:
if not child.template_override:
if child.template.parent:
parent = template2type[
child.template.parent.id]
else:
parent = None
old_parent = (
child.parent.id if child.parent else None)
if parent != old_parent:
child.parent = parent
to_save.append(child)
childs = sum((c.childs for c in childs), ())
self.__class__.save(to_save)
class OpenType(Wizard):
'Open Type'
__name__ = 'account.account.open_type'
start = StateTransition()
account = StateAction('account.act_account_balance_sheet')
ledger_account = StateAction('account.act_account_general_ledger')
def transition_start(self):
context_model = Transaction().context.get('context_model')
if context_model == 'account.balance_sheet.comparision.context':
return 'account'
elif context_model == 'account.income_statement.context':
return 'ledger_account'
return 'end'
def open_action(self, action):
pool = Pool()
action['name'] = '%s (%s)' % (action['name'], self.record.rec_name)
trans_context = Transaction().context
context = {
'active_id': trans_context.get('active_id'),
'active_ids': trans_context.get('active_ids', []),
'active_model': trans_context.get('active_model'),
}
context_model = trans_context.get('context_model')
if context_model:
Model = pool.get(context_model)
for fname in Model._fields.keys():
if fname == 'id':
continue
context[fname] = trans_context.get(fname)
action['pyson_context'] = PYSONEncoder().encode(context)
return action, {}
do_account = open_action
do_ledger_account = open_action
class AccountTypeStatement(Report):
__name__ = 'account.account.type.statement'
@classmethod
def get_context(cls, records, header, data):
pool = Pool()
Company = pool.get('company.company')
context = Transaction().context
report_context = super().get_context(records, header, data)
report_context['company'] = Company(context['company'])
if data.get('model_context') is not None:
Context = pool.get(data['model_context'])
values = {}
for field in Context._fields:
if field in context:
values[field] = context[field]
report_context['ctx'] = Context(**values)
report_context['types'] = zip_longest(
records, data.get('paths') or [], fillvalue=[])
return report_context
def AccountMixin(template=False):
class Mixin:
__slots__ = ()
_order_name = 'rec_name'
name = fields.Char('Name', required=True, select=True)
code = fields.Char('Code', select=True)
closed = fields.Boolean(
"Closed",
states={
'invisible': ~Eval('type'),
},
help="Check to prevent posting move on the account.")
reconcile = fields.Boolean(
"Reconcile",
states={
'invisible': ~Eval('type'),
},
help="Allow move lines of this account to be reconciled.")
party_required = fields.Boolean('Party Required',
domain=[
If(~Eval('type') | ~Eval('deferral', False),
('party_required', '=', False),
()),
],
states={
'invisible': ~Eval('type') | ~Eval('deferral', False),
})
general_ledger_balance = fields.Boolean('General Ledger Balance',
states={
'invisible': ~Eval('type'),
},
help="Display only the balance in the general ledger report.")
deferral = fields.Function(fields.Boolean(
"Deferral",
states={
'invisible': ~Eval('type'),
}),
'on_change_with_deferral', searcher='search_deferral')
@classmethod
def __setup__(cls):
super().__setup__()
if not cls.childs.domain:
cls.childs.domain = []
for type_ in ['type', 'debit_type']:
field = getattr(cls, type_)
field.domain = [
If(Eval('parent')
& Eval('_parent_parent.%s' % type_)
& Eval('_parent_parent.parent'),
('id', '=', Eval('_parent_parent.%s' % type_)),
()),
]
cls.childs.domain.append(
If(Eval(type_) & Eval('parent'),
(type_, '=', Eval(type_)),
()))
@classmethod
def default_closed(cls):
return False
@classmethod
def default_reconcile(cls):
return False
@classmethod
def default_party_required(cls):
return False
@classmethod
def default_general_ledger_balance(cls):
return False
@fields.depends('type')
def on_change_with_deferral(self, name=None):
return (self.type
and self.type.statement in {'balance', 'off-balance'})
@classmethod
def search_deferral(cls, name, clause):
_, operator, value = clause
if operator in {'in', 'not in'}:
if operator == 'in':
operator = '='
else:
operator = '!='
if True in value and False not in value:
value = '=', True
elif False in value and True not in value:
value = '=', False
else:
return [('id', operator, None)]
if ((operator == '=' and value)
or (operator == '!=' and not value)):
return [
('type.statement', 'in', ['balance', 'off-balance']),
]
else:
return ['OR',
('type', '=', None),
('type.statement', 'not in', ['balance', 'off-balance']),
]
def get_rec_name(self, name):
if self.code:
return self.code + ' - ' + self.name
else:
return self.name
@classmethod
def search_rec_name(cls, name, clause):
if clause[1].startswith('!') or clause[1].startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
code_value = clause[2]
if clause[1].endswith('like'):
code_value = lstrip_wildcard(clause[2])
return [bool_op,
('code', clause[1], code_value) + tuple(clause[3:]),
(cls._rec_name,) + tuple(clause[1:]),
]
@staticmethod
def order_rec_name(tables):
table, _ = tables[None]
return [table.code, table.name]
if not template:
for fname in dir(Mixin):
field = getattr(Mixin, fname)
if (not isinstance(field, fields.Field)
or isinstance(field, fields.Function)):
continue
field.states['readonly'] = (
Bool(Eval('template', -1)) & ~Eval('template_override', False))
return Mixin
class AccountTemplate(
AccountMixin(template=True), PeriodMixin, tree(), ModelSQL, ModelView):
'Account Template'
__name__ = 'account.account.template'
type = fields.Many2One(
'account.account.type.template', "Type", ondelete="RESTRICT")
debit_type = fields.Many2One(
'account.account.type.template', "Debit Type", ondelete="RESTRICT")
credit_type = fields.Many2One(
'account.account.type.template', "Credit Type", ondelete="RESTRICT")
parent = fields.Many2One('account.account.template', 'Parent', select=True,
ondelete="RESTRICT")
childs = fields.One2Many('account.account.template', 'parent', 'Children')
taxes = fields.Many2Many('account.account.template-account.tax.template',
'account', 'tax', 'Default Taxes',
domain=[('parent', '=', None)])
replaced_by = fields.Many2One(
'account.account.template', "Replaced By",
states={
'invisible': ~Eval('end_date'),
})
@classmethod
def __setup__(cls):
super(AccountTemplate, cls).__setup__()
cls._order.insert(0, ('code', 'ASC'))
cls._order.insert(1, ('name', 'ASC'))
table = cls.__table__()
cls._sql_constraints.append(
('only_one_debit_credit_types', Check(
table, (table.debit_type + table.credit_type) == Null),
'account.msg_only_one_debit_credit_types'))
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
# Drop the required constraint on 'kind'
table_h = cls.__table_handler__(module_name)
if table_h.column_exist('kind'):
table_h.not_null_action('kind', 'remove')
def _get_account_value(self, account=None):
'''
Set the values for account creation.
'''
res = {}
if not account or account.name != self.name:
res['name'] = self.name
if not account or account.code != self.code:
res['code'] = self.code
if not account or account.start_date != self.start_date:
res['start_date'] = self.start_date
if not account or account.end_date != self.end_date:
res['end_date'] = self.end_date
if not account or account.closed != self.closed:
res['closed'] = self.closed
if not account or account.reconcile != self.reconcile:
res['reconcile'] = self.reconcile
if not account or account.party_required != self.party_required:
res['party_required'] = self.party_required
if (not account
or account.general_ledger_balance
!= self.general_ledger_balance):
res['general_ledger_balance'] = self.general_ledger_balance
if not account or account.template != self:
res['template'] = self.id
return res
def create_account(self, company_id, template2account=None,
template2type=None):
'''
Create recursively accounts based on template.
template2account is a dictionary with template id as key and account id
as value, used to convert template id into account. The dictionary is
filled with new accounts
template2type is a dictionary with type template id as key and type id
as value, used to convert type template id into type.
'''
pool = Pool()
Account = pool.get('account.account')
assert self.parent is None
if template2account is None:
template2account = {}
if template2type is None:
template2type = {}
def create(templates):
values = []
created = []
for template in templates:
if template.id not in template2account:
vals = template._get_account_value()
vals['company'] = company_id
if template.parent:
vals['parent'] = template2account[template.parent.id]
else:
vals['parent'] = None
if template.type:
vals['type'] = template2type.get(template.type.id)
else:
vals['type'] = None
if template.debit_type:
vals['debit_type'] = template2type.get(
template.debit_type.id)
else:
vals['debit_type'] = None
if template.credit_type:
vals['credit_type'] = template2type.get(
template.credit_type.id)
else:
vals['credit_type'] = None
values.append(vals)
created.append(template)
accounts = Account.create(values)
for template, account in zip(created, accounts):
template2account[template.id] = account.id
childs = [self]
while childs:
create(childs)
childs = sum((c.childs for c in childs), ())
def update_account2(self, template2account, template2tax,
template_done=None):
'''
Update recursively account taxes and replaced_by based on template.
template2account is a dictionary with template id as key and account id
as value, used to convert template id into account.
template2tax is a dictionary with tax template id as key and tax id as
value, used to convert tax template id into tax.
template_done is a list of template id already updated. The list is
filled.
'''
Account = Pool().get('account.account')
if template2account is None:
template2account = {}
if template2tax is None:
template2tax = {}
if template_done is None:
template_done = []
def update(templates):
to_write = []
for template in templates:
if template.id not in template_done:
template_done.append(template.id)
account = Account(template2account[template.id])
if account.template_override:
continue
values = {}
if template.taxes:
tax_ids = [template2tax[x.id] for x in template.taxes]
values['taxes'] = [('add', tax_ids)]
if template.replaced_by:
values['replaced_by'] = template2account[
template.replaced_by.id]
if values:
to_write.append([account])
to_write.append(values)
if to_write:
Account.write(*to_write)
childs = [self]
while childs:
update(childs)
childs = sum((c.childs for c in childs), ())
class AccountTemplateTaxTemplate(ModelSQL):
'Account Template - Tax Template'
__name__ = 'account.account.template-account.tax.template'
_table = 'account_account_template_tax_rel'
account = fields.Many2One('account.account.template', 'Account Template',
ondelete='CASCADE', select=True, required=True)
tax = fields.Many2One('account.tax.template', 'Tax Template',
ondelete='RESTRICT', select=True, required=True)
class Account(AccountMixin(), ActivePeriodMixin, tree(), ModelSQL, ModelView):
'Account'
__name__ = 'account.account'
_states = {
'readonly': (Bool(Eval('template', -1))
& ~Eval('template_override', False)),
}
company = fields.Many2One('company.company', 'Company', required=True,
ondelete="RESTRICT")
currency = fields.Function(fields.Many2One('currency.currency',
'Currency'), 'get_currency')
second_currency = fields.Many2One('currency.currency',
'Secondary Currency', help='Force all moves for this account \n'
'to have this secondary currency.', ondelete="RESTRICT",
domain=[
('id', '!=', Eval('currency', -1)),
],
states={
'readonly': _states['readonly'],
'invisible': ~Eval('deferral', False),
})
type = fields.Many2One(
'account.account.type', "Type", ondelete='RESTRICT',
states={
'readonly': _states['readonly'],
},
domain=[
('company', '=', Eval('company')),
])
debit_type = fields.Many2One(
'account.account.type', "Debit Type", ondelete='RESTRICT',
states={
'readonly': _states['readonly'],
'invisible': (
~Eval('type') | Eval('credit_type')
| (_states['readonly']) & ~Eval('debit_type')),
},
domain=[
('company', '=', Eval('company')),
],
help="The type used if not empty and debit > credit.")
credit_type = fields.Many2One(
'account.account.type', "Credit Type", ondelete='RESTRICT',
states={
'readonly': _states['readonly'],
'invisible': (
~Eval('type') | Eval('debit_type')
| (_states['readonly']) & ~Eval('credit_type')),
},
domain=[
('company', '=', Eval('company')),
],
help="The type used if not empty and debit < credit.")
parent = fields.Many2One(
'account.account', 'Parent', select=True,
left="left", right="right", ondelete="RESTRICT", states=_states)
left = fields.Integer('Left', required=True, select=True)
right = fields.Integer('Right', required=True, select=True)
childs = fields.One2Many(
'account.account', 'parent', 'Children')
balance = fields.Function(Monetary(
"Balance", currency='currency', digits='currency'),
'get_balance')
credit = fields.Function(Monetary(
"Credit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_credit_debit')
debit = fields.Function(Monetary(
"Debit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_credit_debit')
amount_second_currency = fields.Function(Monetary(
"Amount Second Currency",
currency='second_currency', digits='second_currency',
states={
'invisible': ~Eval('second_currency'),
}),
'get_credit_debit')
line_count = fields.Function(
fields.Integer("Line Count"), 'get_credit_debit')
note = fields.Text('Note')
deferrals = fields.One2Many(
'account.account.deferral', 'account', "Deferrals", readonly=True,
states={
'invisible': ~Eval('type'),
})
taxes = fields.Many2Many('account.account-account.tax',
'account', 'tax', 'Default Taxes',
domain=[
('company', '=', Eval('company')),
('parent', '=', None),
],
help="Default tax for manual encoding of move lines\n"
'for journal types: "expense" and "revenue".')
replaced_by = fields.Many2One(
'account.account', "Replaced By",
domain=[('company', '=', Eval('company', -1))],
states={
'readonly': _states['readonly'],
'invisible': ~Eval('end_date'),
})
template = fields.Many2One('account.account.template', 'Template')
template_override = fields.Boolean('Override Template',
help="Check to override template definition",
states={
'invisible': ~Bool(Eval('template', -1)),
})
del _states
@classmethod
def __setup__(cls):
super(Account, cls).__setup__()
for date in [cls.start_date, cls.end_date]:
date.states = {
'readonly': (Bool(Eval('template', -1))
& ~Eval('template_override', False)),
}
cls._order.insert(0, ('code', 'ASC'))
cls._order.insert(1, ('name', 'ASC'))
table = cls.__table__()
cls._sql_constraints.append(
('only_one_debit_credit_types', Check(
table, (table.debit_type + table.credit_type) == Null),
'account.msg_only_one_debit_credit_types'))
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
# Drop the required constraint on 'kind'
table_h = cls.__table_handler__(module_name)
if table_h.column_exist('kind'):
table_h.not_null_action('kind', 'remove')
@classmethod
def validate_fields(cls, accounts, field_names):
super().validate_fields(accounts, field_names)
cls.check_second_currency(accounts, field_names)
cls.check_move_domain(accounts, field_names)
@staticmethod
def default_left():
return 0
@staticmethod
def default_right():
return 0
@staticmethod
def default_company():
return Transaction().context.get('company') or None
@classmethod
def default_template_override(cls):
return False
def get_currency(self, name):
return self.company.currency.id
@classmethod
def get_balance(cls, accounts, name):
pool = Pool()
MoveLine = pool.get('account.move.line')
FiscalYear = pool.get('account.fiscalyear')
cursor = Transaction().connection.cursor()
table_a = cls.__table__()
table_c = cls.__table__()
line = MoveLine.__table__()
ids = [a.id for a in accounts]
balances = dict((i, Decimal(0)) for i in ids)
line_query, fiscalyear_ids = MoveLine.query_get(line)
for sub_ids in grouped_slice(ids):
red_sql = reduce_ids(table_a.id, sub_ids)
cursor.execute(*table_a.join(table_c,
condition=(table_c.left >= table_a.left)
& (table_c.right <= table_a.right)
).join(line, condition=line.account == table_c.id
).select(
table_a.id,
Sum(Coalesce(line.debit, 0) - Coalesce(line.credit, 0)),