-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatement.py
2346 lines (2117 loc) · 94 KB
/
statement.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 requests
from datetime import datetime, UTC, timedelta
from decimal import Decimal
from secrets import token_hex
from itertools import groupby, chain
from sql.conditionals import Greatest
from sql.functions import Function
from trytond.model import Workflow, ModelView, ModelSQL, fields, tree
from trytond.pool import Pool, PoolMeta
from trytond.pyson import Eval, Bool, If, PYSON, PYSONEncoder
from trytond.rpc import RPC
from trytond.wizard import (
Button, StateAction, StateTransition, StateView, Wizard)
from trytond.transaction import Transaction
from trytond.config import config
from .common import get_base_header
from trytond.i18n import gettext
from trytond.model.exceptions import AccessError
from trytond.modules.account_statement.exceptions import (
StatementValidateError, StatementValidateWarning)
from trytond.modules.currency.fields import Monetary
from trytond.modules.account_statement.statement import Unequal
from trytond import backend
_ZERO = Decimal(0)
class Similarity(Function):
__slots__ = ()
_function = 'SIMILARITY'
class JsonbExtractPathText(Function):
__slots__ = ()
_function = 'JSONB_EXTRACT_PATH_TEXT'
class Statement(metaclass=PoolMeta):
__name__ = 'account.statement'
start_date = fields.DateTime("Start Date", readonly=True)
end_date = fields.DateTime("End Date", readonly=True)
@classmethod
def __setup__(cls):
super().__setup__()
if cls.date.states.get('invisible', None):
cls.date.states['invisible'] |= (Bool(Eval('start_date')))
else:
cls.date.states['invisible'] = Bool(Eval('start_date'))
# Add new state to the statement, to avoid some checks qhen the
# statement came from the Bank lines.
cls.state.selection.append(('registered', "Registered"))
cls._transitions |= set((
('draft', 'registered'),
('registered', 'draft'),
('registered', 'validated'),
('validated', 'registered'),
))
cls._buttons.update({
'register': {
'invisible': ~Eval('state').in_(['draft', 'validated']),
'depends': ['state'],
},
})
cls._buttons['draft']['invisible'] = ~Eval('state').in_(
['cancelled', 'registered'])
cls._buttons['validate_statement']['invisible'] = ~Eval('state').in_(
['draft', 'registered'])
def _group_key(self, line):
pool = Pool()
StatementOrigin = pool.get('account.statement.origin')
StatementLine = pool.get('account.statement.line')
one_move = (line.statement.journal.one_move_per_origin
if line.statement else None)
if one_move and isinstance(line, (StatementLine, StatementOrigin)):
if isinstance(line, StatementLine):
key = (
('number', line.origin and (
line.origin.number or line.origin.description)
or Unequal()),
('date', line.origin.date),
('origin', line.origin),
)
elif isinstance(line, StatementOrigin):
key = (
('number', (line.number or line.description) or Unequal()),
('date', line.date),
('origin', line),
)
else:
key = super()._group_key(line)
return key
@classmethod
def cancel(cls, statements):
pool = Pool()
Origin = pool.get('account.statement.origin')
origins = [o for s in statements for o in s.origins]
if origins:
Origin.cancel(origins)
super().cancel(statements)
@classmethod
@ModelView.button
@Workflow.transition('registered')
def register(cls, statements):
pass
_states = {
'readonly': ~Eval('statement_state', '').in_(['draft', 'registered'])
}
class Line(metaclass=PoolMeta):
__name__ = 'account.statement.line'
maturity_date = fields.Date("Maturity Date",
states={
'invisible': Bool(Eval('related_to')),
'readonly': Eval('origin_state') != 'registered',
},
depends=['related_to'],
help="Set a date to make the line payable or receivable.")
suggested_line = fields.Many2One('account.statement.origin.suggested.line',
'Suggested Lines',
states={
'readonly': Eval('origin_state') != 'registered',
})
origin_state = fields.Function(
fields.Selection('get_origin_states', "Origin State"),
'on_change_with_origin_state')
show_paid_invoices = fields.Boolean('Show Paid Invoices',
states={
'readonly': Eval('origin_state') != 'registered',
})
@classmethod
def __setup__(cls):
super().__setup__()
new_domain = []
for domain in cls.related_to.domain['account.invoice']:
if isinstance(domain, PYSON):
values = [x for x in domain.pyson().values()
if isinstance(x, tuple)]
if ('state', '=', 'posted') in values:
new_domain.append(
If(Bool(Eval('show_paid_invoices')),
('state', '=', 'paid'),
If(Eval('statement_state').in_(
['draft', 'registered']),
('state', '=', 'posted'),
('state', '!=', ''))))
continue
new_domain.append(domain)
cls.related_to.domain['account.invoice'] = new_domain
cls.related_to.domain['account.move.line'] = [
('company', '=', Eval('company', -1)),
If(Eval('second_currency'),
('second_currency', '=', Eval('second_currency', -1)),
If(Eval('company_currency') == Eval('currency'),
('currency', '=', Eval('currency', -1)),
('second_currency', '=', Eval('currency', -1))
)),
If(Bool(Eval('party')),
('party', '=', Eval('party')),
()),
If(Bool(Eval('account')),
('account', '=', Eval('account')),
()),
('move_state', '=', 'posted'),
('account.reconcile', '=', True),
('state', '=', 'valid'),
('reconciliation', '=', None),
('invoice_payment', '=', None),
]
cls.statement.states['readonly'] = _states['readonly']
cls.number.states['readonly'] = _states['readonly']
cls.date.states['readonly'] = (
_states['readonly'] | Bool(Eval('origin', 0))
)
cls.amount.states['readonly'] = _states['readonly']
cls.amount_second_currency.states['readonly'] = _states['readonly']
cls.second_currency.states['readonly'] = _states['readonly']
cls.party.states['readonly'] = _states['readonly']
cls.party.states['required'] = (Eval('party_required', False)
& (Eval('statement_state').in_(['draft', 'registered']))
)
cls.account.states['readonly'] = _states['readonly']
cls.description.states['readonly'] = _states['readonly']
cls.related_to.states['readonly'] = _states['readonly']
@classmethod
def _get_relations(cls):
return super()._get_relations() + ['account.move.line']
@classmethod
def get_origin_states(cls):
pool = Pool()
Origin = pool.get('account.statement.origin')
return Origin.fields_get(['state'])['state']['selection']
@fields.depends('origin', '_parent_origin.state')
def on_change_with_origin_state(self, name=None):
if self.origin:
return self.origin.state
@fields.depends('origin', 'related_to', '_parent_origin.second_currency')
def on_change_with_second_currency(self, name=None):
if not self.related_to:
return None
if self.origin and self.origin.second_currency:
return self.origin.second_currency
@fields.depends('origin', 'related_to',
'_parent_origin.amount_second_currency')
def on_change_with_amount_second_currency(self, name=None):
if not self.related_to:
return None
if self.origin and self.origin.amount_second_currency:
return self.origin.amount_second_currency
@property
@fields.depends('related_to')
def move_line(self):
pool = Pool()
MoveLine = pool.get('account.move.line')
related_to = getattr(self, 'related_to', None)
if isinstance(related_to, MoveLine) and related_to.id >= 0:
return related_to
@move_line.setter
def move_line(self, value):
self.related_to = value
@property
@fields.depends('related_to')
def move_line_invoice(self):
pool = Pool()
MoveLine = pool.get('account.move.line')
Invoice = pool.get('account.invoice')
related_to = getattr(self, 'related_to', None)
if (isinstance(related_to, MoveLine) and related_to.id >= 0
and related_to.move and related_to.move.origin
and isinstance(related_to.move.origin, Invoice)):
return related_to.move.origin
@property
@fields.depends('company', '_parent_company.currency',
'show_paid_invoices',
methods=['invoice', 'move_line_invoice'])
def invoice_amount_to_pay(self):
amount_to_pay = None
# control the possibilty to use the move from invoice
invoice = self.invoice or self.move_line_invoice or None
if invoice:
sign = -1 if invoice.type == 'in' else 1
if invoice.currency == self.currency:
# If we are in the case that need control a refund invoice,
# need to get the total amount of the invoice.
amount_to_pay = sign * (invoice.total_amount
if self.show_paid_invoices and invoice.state == 'paid'
else invoice.amount_to_pay)
else:
amount = _ZERO
if invoice.state == 'posted':
for line in (invoice.lines_to_pay
+ invoice.payment_lines):
if line.reconciliation:
continue
amount += line.debit - line.credit
else:
# If we are in the case that need control a refund invoice,
# need to get the total amount of the invoice.
amount = (sign * invoice.total_amount
if self.show_paid_invoices and invoice.state == 'paid'
else _ZERO)
amount_to_pay = amount
if self.show_paid_invoices and amount_to_pay:
amount_to_pay = -1 * amount_to_pay
return amount_to_pay
@fields.depends('show_paid_invoices')
def on_change_party(self):
if not self.show_paid_invoices:
super().on_change_party()
@fields.depends('amount', 'account', methods=['invoice', 'move_line',
'invoice_amount_to_pay'])
def on_change_amount(self):
if self.invoice:
if self.invoice.account != self.account:
self.account = self.invoice.account
if (self.amount is not None
and self.invoice_amount_to_pay is not None
and ((self.amount >= 0) != (
self.invoice_amount_to_pay >= 0)
or (self.amount >= 0
and self.amount > self.invoice_amount_to_pay)
or (self.amount < 0
and self.amount < self.invoice_amount_to_pay))):
self.amount = self.invoice_amount_to_pay
elif self.move_line:
if self.move_line.account != self.account:
self.account = self.move_line.account
if (self.amount is not None and self.move_line.amount is not None
and ((self.amount >= 0) != (
self.move_line.amount >= 0)
or (self.amount >= 0
and self.amount > self.move_line.amount)
or (self.amount < 0
and self.amount < self.move_line.amount))):
self.amount = self.move_line.amount
else:
super().on_change_amount()
@fields.depends('account', methods=['move_line'])
def on_change_account(self):
super().on_change_account()
if self.move_line:
if self.account:
if self.move_line.account != self.account:
self.move_line = None
else:
self.move_line = None
@fields.depends('related_to', 'party', 'description', 'show_paid_invoices',
'origin', '_parent_origin.information', 'company',
'_parent_origin.remittance_information', '_parent_company.currency',
methods=['move_line', 'payment', 'invoice_amount_to_pay'])
def on_change_related_to(self):
pool = Pool()
Invoice = pool.get('account.invoice')
super().on_change_related_to()
if self.move_line:
if not self.party:
self.party = self.move_line.party
if not self.description:
self.description = (self.move_line.description
or self.move_line.move_description_used)
self.account = self.move_line.account
related_to = getattr(self, 'related_to', None)
if self.show_paid_invoices and not isinstance(related_to, Invoice):
self.show_paid_invoices = False
if not self.description and self.origin and self.origin.information:
self.description = self.origin.remittance_information
# TODO: Control when the currency is different
payments = set()
move_lines = set()
move_lines_second_currency = set()
invoice_id2amount_to_pay = {}
if self.invoice and self.invoice.id not in invoice_id2amount_to_pay:
invoice_id2amount_to_pay[self.invoice.id] = (
self.invoice_amount_to_pay)
if self.payment and self.payment.currency == self.company.currency:
payments.add(self.payment)
if self.move_line and self.move_line.currency == self.company.currency:
if self.currency == self.move_line.currency:
move_lines.add(self.move_line)
else:
move_lines_second_currency.add(self.move_line)
payment_id2amount = (dict((x.id, x.amount) for x in payments)
if payments else {})
move_line_id2amount = (dict((x.id, x.debit-x.credit)
for x in move_lines) if move_lines else {})
move_line_id2amount.update(dict((x.id, x.amount)
for x in move_lines_second_currency)
if move_lines_second_currency else {})
# As a 'core' difference, the value of the line amount must be the
# amount of the movement, invoice or payment. Not the line amount
# pending. It could induce an incorrect concept nad misunderstunding.
amount = None
if self.invoice and self.invoice.id in invoice_id2amount_to_pay:
amount = invoice_id2amount_to_pay.get(
self.invoice.id, _ZERO)
if self.payment and self.payment.id in payment_id2amount:
amount = payment_id2amount[self.payment.id]
if self.move_line and self.move_line.id in move_line_id2amount:
amount = move_line_id2amount[self.move_line.id]
if amount is None and self.invoice:
self.invoice = None
if amount is None and self.payment:
self.payment = None
if amount is None and self.move_line:
self.move_line = None
self.amount = amount
@classmethod
def cancel_move(cls, moves):
pool = Pool()
Move = pool.get('account.move')
MoveLine = pool.get('account.move.line')
Reconciliation = pool.get('account.move.reconciliation')
Invoice = pool.get('account.invoice')
for move in moves:
to_unreconcile = [x.reconciliation for x in move.lines
if x.reconciliation]
if to_unreconcile:
to_unreconcile = Reconciliation.browse([
x.id for x in to_unreconcile])
Reconciliation.delete(to_unreconcile)
# On possible related invoices, need to unlink the payment
# lines
to_unpay = [x for x in move.lines if x.invoice_payment]
if to_unpay:
Invoice.remove_payment_lines(to_unpay)
cancel_move = move.cancel(reversal=True)
cancel_move.origin = move.origin
Move.post([cancel_move])
mlines = [l for m in [move, cancel_move]
for l in m.lines if l.account.reconcile]
mlines.sort(key=lambda x: (x.party, x.account))
mlines = [list(l) for _, l in groupby(mlines,
key=lambda x: (x.party, x.account))]
if mlines:
MoveLine.reconcile(*mlines)
@classmethod
def cancel_lines(cls, lines, origin=None):
'''As is needed save an history fo all movements, do not remove the
possible move related. Create the cancelation move and leave they
related to the statement and the origin, to have an hstory.
'''
pool = Pool()
MoveLine = pool.get('account.move.line')
SuggestedLine = pool.get('account.statement.origin.suggested.line')
Warning = pool.get('res.user.warning')
moves = set()
mlines = []
for line in lines:
if line.move:
warning_key = Warning.format(
'origin_line_with_move', [line.move.id])
if Warning.check(warning_key):
raise StatementValidateWarning(warning_key,
gettext('account_statement_enable_banking.'
'msg_origin_line_with_move',
move=line.move.rec_name))
for mline in line.move.lines:
if mline.origin == line:
mlines.extend(([mline], {'origin': line.origin}))
moves.add(line.move)
if mlines:
with Transaction().set_context(from_account_statement_origin=True):
MoveLine.write(*mlines)
cls.cancel_move(list(moves))
suggested_lines = [x.suggested_line for x in lines
if x.suggested_line]
suggested_lines.extend(list(set([x.parent
for x in suggested_lines if x.parent])))
cls.write(lines, {'suggested_line': None})
if suggested_lines and (origin is None or origin == 'delete_move'):
SuggestedLine.propose(suggested_lines)
elif suggested_lines:
SuggestedLine.delete(suggested_lines)
@classmethod
def reconcile(cls, move_lines):
pool = Pool()
MoveLine = pool.get('account.move.line')
Reconcile = pool.get('account.move.reconciliation')
Invoice = pool.get('account.invoice')
Payment = pool.get('account.payment')
to_reconcile = {}
invoice_to_save = []
move_to_reconcile = {}
statement_lines = []
for move_line, statement_line in move_lines:
if not statement_line:
continue
if (statement_line.invoice and statement_line.show_paid_invoices
and move_line.account == statement_line.invoice.account):
additional_moves = [move_line.move]
invoice = statement_line.invoice
reconcile = [move_line]
payment_lines = list(set(chain(
[x for x in invoice.payment_lines],
invoice.reconciliation_lines)))
payments = []
for line in payment_lines:
if line.reconciliation:
payments.extend([p for l in line.reconciliation.lines
for p in l.payments if l.id != line.id])
# Temporally, need to allow
# from_account_bank_statement_line, until all is move
# from the old bank_statement to the new statement.
with Transaction().set_context(_skip_warnings=True,
from_account_bank_statement_line=True):
Reconcile.delete([line.reconciliation])
if line.move not in invoice.additional_moves:
additional_moves.append(line.move)
reconcile.append(line)
if payments:
Payment.fail(payments)
if reconcile:
MoveLine.reconcile(reconcile)
if invoice.payment_lines:
invoice.payment_lines = None
invoice_to_save.append(invoice)
if additional_moves:
invoice.additional_moves += tuple(additional_moves)
invoice_to_save.append(invoice)
elif statement_line.invoice:
key = (statement_line.party, statement_line.invoice)
if key in to_reconcile:
to_reconcile[key].append((move_line, statement_line))
else:
to_reconcile[key] = [(move_line, statement_line)]
elif statement_line.move_line:
assert move_line.account == statement_line.move_line.account
key = statement_line.party
if key in move_to_reconcile:
move_to_reconcile[key].append(
(move_line, statement_line.move_line))
else:
move_to_reconcile[key] = [
(move_line, statement_line.move_line)]
statement_lines.append(statement_line.id)
if invoice_to_save:
Invoice.save(list(set(invoice_to_save)))
if to_reconcile:
for _, value in to_reconcile.items():
super().reconcile(value)
if move_to_reconcile:
with Transaction().set_context(
account_statement_lines=statement_lines):
for _, value in move_to_reconcile.items():
MoveLine.reconcile(*value)
@classmethod
def delete(cls, lines):
cls.cancel_lines(lines, origin='delete')
for line in lines:
if line.statement_state not in {
'cancelled', 'registered', 'draft'}:
raise AccessError(
gettext(
'account_statement.'
'msg_statement_line_delete_cancel_draft',
line=line.rec_name,
sale=line.statement.rec_name))
# Use __func__ to directly access ModelSQL's delete method and
# pass it the right class
ModelSQL.delete.__func__(cls, lines)
@classmethod
def delete_move(cls, lines):
cls.cancel_lines(lines, origin='delete_move')
super().delete_move(lines)
def get_move_line(self):
line = super().get_move_line()
if self.maturity_date:
line.maturity_date = self.maturity_date
return line
@classmethod
def copy(cls, lines, default=None):
default = default.copy() if default is not None else {}
default.setdefault('maturity_date', None)
default.setdefault('suggested_line', None)
default.setdefault('show_paid_invoices', None)
return super().copy(lines, default=default)
class Origin(Workflow, metaclass=PoolMeta):
__name__ = 'account.statement.origin'
entry_reference = fields.Char("Entry Reference", readonly=True)
suggested_lines = fields.One2Many(
'account.statement.origin.suggested.line', 'origin',
'Suggested Lines', states=_states)
suggested_lines_tree = fields.Function(
fields.Many2Many('account.statement.origin.suggested.line', None, None,
'Suggested Lines', states=_states), 'get_suggested_lines_tree')
balance = Monetary("Balance", currency='currency', digits='currency',
readonly=True)
state = fields.Selection([
('registered', "Registered"),
('cancelled', "Cancelled"),
('posted', "Posted"),
], "State", readonly=True, required=True, sort=False)
remittance_information = fields.Function(
fields.Char('Remittance Information'), 'get_remittance_information',
searcher='search_remittance_information')
@classmethod
def __setup__(cls):
super().__setup__()
cls.number.search_unaccented = False
cls._order.insert(0, ('date', 'ASC'))
cls._order.insert(1, ('number', 'ASC'))
cls.statement.states['readonly'] = _states['readonly']
cls.number.states['readonly'] = _states['readonly']
cls.date.states['readonly'] = _states['readonly']
cls.amount.states['readonly'] = _states['readonly']
cls.amount_second_currency.states['readonly'] = _states['readonly']
cls.second_currency.states['readonly'] = _states['readonly']
cls.party.states['readonly'] = _states['readonly']
cls.account.states['readonly'] = _states['readonly']
cls.description.states['readonly'] = _states['readonly']
cls.lines.states['readonly'] = (
(Eval('statement_id', -1) < 0)
| (~Eval('statement_state').in_(
['draft', 'registered', 'validated']))
)
cls._transitions |= set((
('registered', 'posted'),
('registered', 'cancelled'),
('cancelled', 'registered'),
('posted', 'cancelled'),
))
cls._buttons.update({
'multiple_invoices': {
'invisible': Eval('state') != 'registered',
'depends': ['state'],
},
'multiple_move_lines': {
'invisible': Eval('state') != 'registered',
'depends': ['state'],
},
'register': {
'invisible': Eval('state') != 'cancelled',
'depends': ['state'],
},
'post': {
'invisible': Eval('state') != 'registered',
'depends': ['state'],
},
'cancel': {
'invisible': Eval('state') == 'cancelled',
'depends': ['state'],
},
'search_suggestions': {
'invisible': Eval('state') != 'registered',
'depends': ['state'],
},
})
cls.__rpc__.update({
'post': RPC(
readonly=False, instantiate=0, fresh_session=True),
})
@staticmethod
def default_state():
return 'registered'
@fields.depends('state')
def on_change_with_statement_state(self, name=None):
try:
state = super().on_change_with_statement_state()
except AttributeError:
state = None
return self.state or state
@property
@fields.depends('statement', '_parent_statement.journal')
def similarity_threshold(self):
return (self.statement.journal.similarity_threshold
if self.statement and self.statement.journal else None)
@property
@fields.depends('statement', '_parent_statement.journal')
def acceptable_similarity(self):
return (self.statement.journal.acceptable_similarity
if self.statement and self.statement.journal else None)
def get_suggested_lines_tree(self, name):
# return only parent lines in origin suggested lines
# Not children.
suggested_lines = []
def _get_children(line):
if line.parent is None:
suggested_lines.append(line)
for line in self.suggested_lines:
_get_children(line)
return [x.id for x in suggested_lines if x.state == 'proposed']
def get_remittance_information(self, name):
return (self.information.get('remittance_information', '')
if self.information else '')
@classmethod
def search_remittance_information(cls, name, clause):
pool = Pool()
StatementOrigin = pool.get('account.statement.origin')
origin_table = StatementOrigin.__table__()
cursor = Transaction().connection.cursor()
_, operator, value = clause
operator = 'in' if value else 'not in'
if backend.name == 'postgresql':
remittance_information_column = JsonbExtractPathText(
origin_table.information, 'remittance_information')
else:
remittance_information_column = origin_table.information
query = origin_table.select(origin_table.id,
where=(remittance_information_column.ilike(value)))
cursor.execute(*query)
return [('id', operator, [x[0] for x in cursor.fetchall()])]
def validate_amount(self):
pool = Pool()
Lang = pool.get('ir.lang')
amount = sum(x.amount for x in self.lines)
if amount != self.amount:
lang = Lang.get()
total_amount = lang.currency(
self.amount, self.statement.journal.currency)
amount = lang.currency(amount, self.statement.journal.currency)
raise StatementValidateError(
gettext('account_statement_enable_banking.'
'msg_origin_pending_amount',
origin_amount=total_amount,
line_amount=amount))
@classmethod
def validate_origin(cls, origins):
'''Basically is a piece of copy & paste from account_statement
validate_statement(), but adapted to work at origin level
'''
pool = Pool()
StatementLine = pool.get('account.statement.line')
Invoice = pool.get('account.invoice')
InvoiceTax = pool.get('account.invoice.tax')
Warning = pool.get('res.user.warning')
paid_cancelled_invoice_lines = []
for origin in origins:
origin.validate_amount()
for line in origin.lines:
if line.related_to:
# Try to find if the related_to is used in another
# posted origin, may be from the account move or from the
# possible realted invoice. But with the tax exception.
repeated = StatementLine.search([
('related_to', '=', line.related_to),
('id', '!=', line.id),
('origin.state', '=', 'posted'),
('show_paid_invoices', '=', False),
])
if not repeated and line.invoice:
repeated = StatementLine.search([
('related_to', 'in',
line.invoice.lines_to_pay),
('origin.state', '=', 'posted'),
])
if (not repeated and line.move_line
and line.move_line.move_origin
and isinstance(
line.move_line.move_origin, Invoice)
and (not line.move_line.origin
or not isinstance(
line.move_line.origin, InvoiceTax))):
repeated = StatementLine.search([
('related_to', '=',
line.move_line.move_origin),
('origin.state', '=', 'posted'),
])
if repeated:
invoice_amount_to_pay = line.invoice_amount_to_pay
if line.invoice and line.show_paid_invoices:
# returned recipt
# Unlink the account move from the account statement line
# to allow correctly attach to another statement line.
StatementLine.write(repeated, {
'related_to': None,
})
continue
elif invoice_amount_to_pay is not None:
# partial payment
line_sign = 1 if line.amount >= 0 else 0
invoice_sign = (1
if invoice_amount_to_pay >= 0 else 0)
if (line_sign == invoice_sign
and abs(line.amount) <= abs(
invoice_amount_to_pay)):
continue
raise AccessError(
gettext('account_statement_enable_banking.'
'msg_repeated_related_to_used',
related_to=str(line.related_to),
origin=(repeated[0].origin.rec_name
if repeated[0].origin else '')))
paid_cancelled_invoice_lines.extend(x for x in origin.lines
if x.invoice and (x.invoice.state == 'cancelled'
or (x.invoice.state == 'paid'
and not x.show_paid_invoices)))
if paid_cancelled_invoice_lines:
warning_key = Warning.format(
'statement_paid_cancelled_invoice_lines',
paid_cancelled_invoice_lines)
if Warning.check(warning_key):
raise StatementValidateWarning(warning_key,
gettext('account_statement'
'.msg_statement_invoice_paid_cancelled'))
StatementLine.write(paid_cancelled_invoice_lines, {
'related_to': None,
})
@classmethod
def create_moves(cls, origins):
'''Basically is a copy & paste from account_statement create_move(),
but adapted to work at origin level
'''
pool = Pool()
StatementLine = pool.get('account.statement.line')
StatementSuggest = pool.get('account.statement.origin.suggested.line')
Move = pool.get('account.move')
MoveLine = pool.get('account.move.line')
moves = []
lines_to_check = []
for origin in origins:
for key, lines in groupby(
origin.lines, key=origin.statement._group_key):
lines = list(lines)
lines_to_check.extend(lines)
key = dict(key)
move = origin.statement._get_move(key)
move.origin = origin
moves.append((move, lines))
Move.save([m for m, _ in moves])
to_write = []
for move, lines in moves:
to_write.extend((lines, {'move': move.id}))
if to_write:
StatementLine.write(*to_write)
move_lines = []
for move, lines in moves:
amount = _ZERO
amount_second_currency = _ZERO
statement = lines[0].statement if lines else None
for line in lines:
move_line = line.get_move_line()
if not move_line:
continue
move_line.move = move
amount += move_line.debit - move_line.credit
if move_line.amount_second_currency:
amount_second_currency += move_line.amount_second_currency
move_lines.append((move_line, line))
if statement:
move_line = statement._get_move_line(
amount, amount_second_currency, lines)
move_line.move = move
move_lines.append((move_line, None))
if move_lines:
MoveLine.save([x for x, _ in move_lines])
# Ensure that any related_to posted lines are not in another registered
# origin or suggested. Except for the paid invoice process or the
# partial payment invoices.
if lines_to_check:
related_tos = []
line_ids = []
suggested_ids = []
for line in lines_to_check:
# returned recipt
if line.show_paid_invoices:
continue
# partial payment. In this point the invoice is payed or
# partial payed, so the invoice.amount_to_pay >= 0.
if line.invoice and line.invoice_amount_to_pay != 0:
continue
line_ids.append(line.id)
if line.related_to:
related_tos.append(line.related_to)
if line.suggested_line:
suggested_ids.append(line.suggested_line.id)
lines = StatementLine.search([
('related_to', 'in', related_tos),
('id', 'not in', line_ids),
('show_paid_invoices', '=', False),
('origin', '!=', None),
])
lines_not_allowed = [l for l in lines if l.origin.state == 'posted']
lines_to_remove = [l for l in lines if l.origin.state != 'posted']
if lines_not_allowed:
raise AccessError(
gettext('account_statement_enable_banking.'
'msg_repeated_related_to_used',
realted_to=str(lines_not_allowed[0].related_to),
origin=(lines_not_allowed[0].origin.rec_name
if lines_not_allowed[0].origin else '')))
if lines_to_remove:
StatementLine.delete(lines_to_remove)
suggest_to_remove = StatementSuggest.search([
('related_to', 'in', related_tos),
('id', 'not in', suggested_ids),
])
if suggest_to_remove:
StatementSuggest.delete(suggest_to_remove)
# Reconcile at the end to avoid problems with the related_to lines
if move_lines:
StatementLine.reconcile(move_lines)
return moves
def similarity_parties(self, compare, threshold=0.13):
"""
This function return a dictionary with the possible parties ID on
'key' and the similairty on 'value'.
It compare the 'compare' value with the parties name, based on the
similarities journal deffined values.
Set the similarity threshold to 0.13 as is the minimum value detecte
that return a correct match with multiple words in compare field.
"""
pool = Pool()
Party = pool.get('party.party')
party_table = Party.__table__()
cursor = Transaction().connection.cursor()
if not compare:
return
similarity = Similarity(party_table.name, compare)
if hasattr(Party, 'trade_name'):
similarity = Greatest(similarity, Similarity(party_table.trade_name,
compare))
query = party_table.select(party_table.id, similarity,
where=(similarity >= threshold))
cursor.execute(*query)
parties = {}
for party, similarity in cursor.fetchall():
parties[party] = round(similarity * 10)
return parties
def increase_similarity_by_interval_date(self, date, interval_date=None,
similarity=0):
"""
This funtion increase the similarity if the dates are equal or in the
interval.
"""
if date:
control_dates = [self.date]
if self.information and self.information.get('value_date'):
control_dates.append(datetime.strptime(
self.information['value_date'], '%Y-%m-%d').date())
if not interval_date:
interval_date = timedelta(days=3)
if date in control_dates:
similarity += 3
else:
for control_date in control_dates:
start_date = control_date - interval_date
end_date = control_date + interval_date
if start_date <= date <= end_date:
similarity += 2
break
return similarity
def increase_similarity_by_party(self, party, similarity_parties,
similarity=0):
"""
This funtion increase the similarity if the party are similar.
"""
if party:
party_id = party.id
if party_id in similarity_parties:
if similarity_parties[party_id] >= self.acceptable_similarity: