/
account_move.py
1798 lines (1621 loc) · 99.1 KB
/
account_move.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
# -*- coding: utf-8 -*-
import time
from datetime import date
from collections import OrderedDict
from odoo import api, fields, models, _
from odoo.osv import expression
from odoo.exceptions import RedirectWarning, UserError, ValidationError
from odoo.tools.misc import formatLang, format_date
from odoo.tools import float_is_zero, float_compare
from odoo.tools.safe_eval import safe_eval
from odoo.addons import decimal_precision as dp
from lxml import etree
#----------------------------------------------------------
# Entries
#----------------------------------------------------------
class AccountMove(models.Model):
_name = "account.move"
_description = "Journal Entries"
_order = 'date desc, id desc'
_inherit = ['mail.thread', 'mail.activity.mixin']
@api.model
def default_get(self, fields):
rec = super(AccountMove, self).default_get(fields)
if not rec.get('journal_id'):
rec.update({'journal_id': self.env['account.journal'].search([('type', '=', 'general'), ('company_id', '=', self.env.user.company_id.id)], limit=1).id})
return rec
@api.multi
@api.depends('name', 'state')
def name_get(self):
result = []
for move in self:
if move.state == 'draft':
name = '* ' + str(move.id)
else:
name = move.name
result.append((move.id, name))
return result
@api.multi
@api.depends('line_ids.debit', 'line_ids.credit')
def _amount_compute(self):
for move in self:
total = 0.0
for line in move.line_ids:
total += line.debit
move.amount = total
@api.depends('line_ids.debit', 'line_ids.credit', 'line_ids.matched_debit_ids.amount', 'line_ids.matched_credit_ids.amount', 'line_ids.account_id.user_type_id.type')
def _compute_matched_percentage(self):
"""Compute the percentage to apply for cash basis method. This value is relevant only for moves that
involve journal items on receivable or payable accounts.
"""
for move in self:
total_amount = 0.0
total_reconciled = 0.0
for line in move.line_ids:
if line.account_id.user_type_id.type in ('receivable', 'payable'):
amount = abs(line.debit - line.credit)
total_amount += amount
for partial_line in (line.matched_debit_ids + line.matched_credit_ids):
total_reconciled += partial_line.amount
precision_currency = move.currency_id or move.company_id.currency_id
if float_is_zero(total_amount, precision_rounding=precision_currency.rounding):
move.matched_percentage = 1.0
else:
move.matched_percentage = total_reconciled / total_amount
@api.multi
@api.depends('line_ids.reconcile_model_id')
def _compute_reconcile_model(self):
for move in self:
move.reconcile_model_id = move.line_ids.mapped('reconcile_model_id')
@api.model
@api.depends('reconcile_model_id')
def _search_reconcile_model(self, operator, operand):
if operand:
rmi = self.search([('line_ids.reconcile_model_id', operator, operand)])
else:
rmi = self.search([('line_ids', operator, operand)])
if rmi:
return [('id', 'in', rmi.ids)]
return [('id', '=', False)]
@api.one
@api.depends('company_id')
def _compute_currency(self):
self.currency_id = self.company_id.currency_id or self.env.user.company_id.currency_id
@api.multi
def _get_default_journal(self):
if self.env.context.get('default_journal_type'):
return self.env['account.journal'].search([('company_id', '=', self.env.user.company_id.id), ('type', '=', self.env.context['default_journal_type'])], limit=1).id
@api.multi
@api.depends('line_ids.partner_id')
def _compute_partner_id(self):
for move in self:
partner = move.line_ids.mapped('partner_id')
move.partner_id = partner.id if len(partner) == 1 else False
@api.onchange('date')
def _onchange_date(self):
'''On the form view, a change on the date will trigger onchange() on account.move
but not on account.move.line even the date field is related to account.move.
Then, trigger the _onchange_amount_currency manually.
'''
self.line_ids._onchange_amount_currency()
name = fields.Char(string='Number', required=True, copy=False, default='/')
ref = fields.Char(string='Reference', copy=False)
date = fields.Date(required=True, states={'posted': [('readonly', True)]}, index=True, default=fields.Date.context_today)
journal_id = fields.Many2one('account.journal', string='Journal', required=True, states={'posted': [('readonly', True)]}, default=_get_default_journal)
currency_id = fields.Many2one('res.currency', compute='_compute_currency', store=True, string="Currency")
state = fields.Selection([('draft', 'Unposted'), ('posted', 'Posted')], string='Status',
required=True, readonly=True, copy=False, default='draft',
help='All manually created new journal entries are usually in the status \'Unposted\', '
'but you can set the option to skip that status on the related journal. '
'In that case, they will behave as journal entries automatically created by the '
'system on document validation (invoices, bank statements...) and will be created '
'in \'Posted\' status.')
line_ids = fields.One2many('account.move.line', 'move_id', string='Journal Items',
states={'posted': [('readonly', True)]}, copy=True)
partner_id = fields.Many2one('res.partner', compute='_compute_partner_id', string="Partner", store=True, readonly=True)
amount = fields.Monetary(compute='_amount_compute', store=True)
narration = fields.Text(string='Internal Note')
company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', store=True, readonly=True)
matched_percentage = fields.Float('Percentage Matched', compute='_compute_matched_percentage', digits=0, store=True, readonly=True, help="Technical field used in cash basis method")
reconcile_model_id = fields.Many2many('account.reconcile.model', compute='_compute_reconcile_model', search='_search_reconcile_model', string="Reconciliation Model", readonly=True)
# Dummy Account field to search on account.move by account_id
dummy_account_id = fields.Many2one('account.account', related='line_ids.account_id', string='Account', store=False, readonly=True)
tax_cash_basis_rec_id = fields.Many2one(
'account.partial.reconcile',
string='Tax Cash Basis Entry of',
help="Technical field used to keep track of the tax cash basis reconciliation. "
"This is needed when cancelling the source: it will post the inverse journal entry to cancel that part too.")
auto_reverse = fields.Boolean(string='Reverse Automatically', default=False, help='If this checkbox is ticked, this entry will be automatically reversed at the reversal date you defined.')
reverse_date = fields.Date(string='Reversal Date', help='Date of the reverse accounting entry.')
reverse_entry_id = fields.Many2one('account.move', String="Reverse entry", store=True, readonly=True)
to_check = fields.Boolean(string='To Check', default=False, help='If this checkbox is ticked, it means that the user was not sure of all the related informations at the time of the creation of the move and that the move needs to be checked again.')
tax_type_domain = fields.Char(store=False, help='Technical field used to have a dynamic taxes domain on the form view.')
@api.constrains('line_ids', 'journal_id', 'auto_reverse', 'reverse_date')
def _validate_move_modification(self):
if 'posted' in self.mapped('line_ids.payment_id.state'):
raise ValidationError(_("You cannot modify a journal entry linked to a posted payment."))
@api.onchange('journal_id')
def _onchange_journal_id(self):
self.tax_type_domain = self.journal_id.type if self.journal_id.type in ('sale', 'purchase') else None
@api.onchange('line_ids')
def _onchange_line_ids(self):
'''Compute additional lines corresponding to the taxes set on the line_ids.
For example, add a line with 1000 debit and 15% tax, this onchange will add a new
line with 150 debit.
'''
def _str_to_list(string):
#remove heading and trailing brackets and return a list of int. This avoid calling safe_eval on untrusted field content
string = string[1:-1]
if string:
return [int(x) for x in string.split(',')]
return []
def _build_grouping_key(line):
#build a string containing all values used to create the tax line
return str(line.tax_ids.ids) + '-' + str(line.analytic_tag_ids.ids) + '-' + (line.analytic_account_id and str(line.analytic_account_id.id) or '')
def _parse_grouping_key(line):
# Retrieve values computed the last time this method has been run.
if not line.tax_line_grouping_key:
return {'tax_ids': [], 'tag_ids': [], 'analytic_account_id': False}
tax_str, tags_str, analytic_account_str = line.tax_line_grouping_key.split('-')
return {
'tax_ids': _str_to_list(tax_str),
'tag_ids': _str_to_list(tags_str),
'analytic_account_id': analytic_account_str and int(analytic_account_str) or False,
}
def _find_existing_tax_line(line_ids, tax, tag_ids, analytic_account_id):
if tax.analytic:
return line_ids.filtered(lambda x: x.tax_line_id == tax and x.analytic_tag_ids.ids == tag_ids and x.analytic_account_id.id == analytic_account_id)
return line_ids.filtered(lambda x: x.tax_line_id == tax)
def _get_lines_to_sum(line_ids, tax, tag_ids, analytic_account_id):
if tax.analytic:
return line_ids.filtered(lambda x: tax in x.tax_ids and x.analytic_tag_ids.ids == tag_ids and x.analytic_account_id.id == analytic_account_id)
return line_ids.filtered(lambda x: tax in x.tax_ids)
def _get_tax_account(tax, amount):
if tax.tax_exigibility == 'on_payment' and tax.cash_basis_account_id:
return tax.cash_basis_account_id
if tax.type_tax_use == 'purchase':
return tax.refund_account_id if amount < 0 else tax.account_id
return tax.refund_account_id if amount >= 0 else tax.account_id
# Cache the already computed tax to avoid useless recalculation.
processed_taxes = self.env['account.tax']
self.ensure_one()
for line in self.line_ids.filtered(lambda x: x.recompute_tax_line):
# Retrieve old field values.
parsed_key = _parse_grouping_key(line)
# Unmark the line.
line.recompute_tax_line = False
# Manage group of taxes.
group_taxes = line.tax_ids.filtered(lambda t: t.amount_type == 'group')
children_taxes = group_taxes.mapped('children_tax_ids')
if children_taxes:
line.tax_ids += children_taxes - line.tax_ids
# Because the taxes on the line changed, we need to recompute them.
processed_taxes -= children_taxes
# Get the taxes to process.
taxes = self.env['account.tax'].browse(parsed_key['tax_ids'])
taxes += line.tax_ids.filtered(lambda t: t not in taxes)
taxes += children_taxes.filtered(lambda t: t not in taxes)
to_process_taxes = (taxes - processed_taxes).filtered(lambda t: t.amount_type != 'group')
processed_taxes += to_process_taxes
# Process taxes.
for tax in to_process_taxes:
tax_line = _find_existing_tax_line(self.line_ids, tax, parsed_key['tag_ids'], parsed_key['analytic_account_id'])
lines_to_sum = _get_lines_to_sum(self.line_ids, tax, parsed_key['tag_ids'], parsed_key['analytic_account_id'])
if not lines_to_sum:
# Drop tax line because the originator tax is no longer used.
self.line_ids -= tax_line
continue
balance = sum([l.balance for l in lines_to_sum])
# Compute the tax amount one by one.
quantity = len(lines_to_sum) if tax.amount_type == 'fixed' else 1
taxes_vals = tax.compute_all(balance,
quantity=quantity, currency=line.currency_id, product=line.product_id, partner=line.partner_id)
if tax_line:
# Update the existing tax_line.
if balance:
# Update the debit/credit amount according to the new balance.
if taxes_vals.get('taxes'):
amount = taxes_vals['taxes'][0]['amount']
account = _get_tax_account(tax, amount) or line.account_id
tax_line.debit = amount > 0 and amount or 0.0
tax_line.credit = amount < 0 and -amount or 0.0
tax_line.account_id = account
else:
# Reset debit/credit in case of the originator line is temporary set to 0 in both debit/credit.
tax_line.debit = tax_line.credit = 0.0
elif taxes_vals.get('taxes'):
# Create a new tax_line.
amount = taxes_vals['taxes'][0]['amount']
account = _get_tax_account(tax, amount) or line.account_id
tax_vals = taxes_vals['taxes'][0]
name = tax_vals['name']
line_vals = {
'account_id': account.id,
'name': name,
'tax_line_id': tax_vals['id'],
'partner_id': line.partner_id.id,
'debit': amount > 0 and amount or 0.0,
'credit': amount < 0 and -amount or 0.0,
'analytic_account_id': line.analytic_account_id.id if tax.analytic else False,
'analytic_tag_ids': line.analytic_tag_ids.ids if tax.analytic else False,
'move_id': self.id,
'tax_exigible': tax.tax_exigibility == 'on_invoice',
'company_id': self.company_id.id,
'company_currency_id': self.company_id.currency_id.id,
}
# N.B. currency_id/amount_currency are not set because if we have two lines with the same tax
# and different currencies, we have no idea which currency set on this line.
self.env['account.move.line'].new(line_vals)
# Keep record of the values used as taxes the last time this method has been run.
line.tax_line_grouping_key = _build_grouping_key(line)
@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(AccountMove, self).fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
if self._context.get('vat_domain'):
res['fields']['line_ids']['views']['tree']['fields']['tax_line_id']['domain'] = [('tag_ids', 'in', [self.env.ref(self._context.get('vat_domain')).id])]
return res
@api.model
def create(self, vals):
move = super(AccountMove, self.with_context(mail_create_nolog=True, check_move_validity=False, partner_id=vals.get('partner_id'))).create(vals)
move.assert_balanced()
return move
@api.multi
def write(self, vals):
if 'line_ids' in vals:
res = super(AccountMove, self.with_context(check_move_validity=False)).write(vals)
self.assert_balanced()
else:
res = super(AccountMove, self).write(vals)
return res
@api.multi
def post(self):
self._post_validate()
# Create the analytic lines in batch is faster as it leads to less cache invalidation.
self.mapped('line_ids').create_analytic_lines()
for move in self:
if move.name == '/':
new_name = False
journal = move.journal_id
if journal.sequence_id:
sequence = journal.sequence_id
new_name = sequence.with_context(ir_sequence_date=move.date).next_by_id()
else:
raise UserError(_('Please define a sequence on the journal.'))
if new_name:
move.name = new_name
if move == move.company_id.account_opening_move_id and not move.company_id.account_bank_reconciliation_start:
# For opening moves, we set the reconciliation date threshold
# to the move's date if it wasn't already set (we don't want
# to have to reconcile all the older payments -made before
# installing Accounting- with bank statements)
move.company_id.account_bank_reconciliation_start = move.date
return self.write({'state': 'posted'})
@api.multi
def action_post(self):
if self.mapped('line_ids.payment_id'):
if any(self.mapped('journal_id.post_at_bank_rec')):
raise UserError(_("A payment journal entry generated in a journal configured to post entries only when payments are reconciled with a bank statement cannot be manually posted. Those will be posted automatically after performing the bank reconciliation."))
return self.post()
@api.multi
def button_cancel(self):
AccountMoveLine = self.env['account.move.line']
excluded_move_ids = []
if self._context.get('edition_mode'):
excluded_move_ids = AccountMoveLine.search(AccountMoveLine._get_domain_for_edition_mode() + [('move_id', 'in', self.ids)]).mapped('move_id').ids
for move in self:
if not move.journal_id.update_posted and move.id not in excluded_move_ids:
raise UserError(_('You cannot modify a posted entry of this journal.\nFirst you should set the journal to allow cancelling entries.'))
# We remove all the analytics entries for this journal
move.mapped('line_ids.analytic_line_ids').unlink()
if self.ids:
self.check_access_rights('write')
self.check_access_rule('write')
self._check_lock_date()
self._cr.execute('UPDATE account_move '\
'SET state=%s '\
'WHERE id IN %s', ('draft', tuple(self.ids),))
self.invalidate_cache()
self._check_lock_date()
return True
@api.multi
def unlink(self):
for move in self:
#check the lock date + check if some entries are reconciled
move.line_ids._update_check()
move.line_ids.unlink()
return super(AccountMove, self).unlink()
@api.multi
def _post_validate(self):
for move in self:
if move.line_ids:
if not all([x.company_id.id == move.company_id.id for x in move.line_ids]):
raise UserError(_("Cannot create moves for different companies."))
self.assert_balanced()
return self._check_lock_date()
@api.multi
def _check_lock_date(self):
for move in self:
lock_date = max(move.company_id.period_lock_date or date.min, move.company_id.fiscalyear_lock_date or date.min)
if self.user_has_groups('account.group_account_manager'):
lock_date = move.company_id.fiscalyear_lock_date
if move.date <= (lock_date or date.min):
if self.user_has_groups('account.group_account_manager'):
message = _("You cannot add/modify entries prior to and inclusive of the lock date %s") % (lock_date)
else:
message = _("You cannot add/modify entries prior to and inclusive of the lock date %s. Check the company settings or ask someone with the 'Adviser' role") % (lock_date)
raise UserError(message)
return True
@api.multi
def assert_balanced(self):
if not self.ids:
return True
prec = self.env.user.company_id.currency_id.decimal_places
self._cr.execute("""\
SELECT move_id
FROM account_move_line
WHERE move_id in %s
GROUP BY move_id
HAVING abs(sum(debit) - sum(credit)) > %s
""", (tuple(self.ids), 10 ** (-max(5, prec))))
if len(self._cr.fetchall()) != 0:
raise UserError(_("Cannot create unbalanced journal entry."))
return True
@api.multi
def _reverse_move(self, date=None, journal_id=None, auto=False):
self.ensure_one()
with self.env.norecompute():
reversed_move = self.copy(default={
'date': date,
'journal_id': journal_id.id if journal_id else self.journal_id.id,
'ref': (_('Automatic reversal of: %s') if auto else _('Reversal of: %s')) % (self.name),
'auto_reverse': False})
for acm_line in reversed_move.line_ids.with_context(check_move_validity=False):
acm_line.write({
'debit': acm_line.credit,
'credit': acm_line.debit,
'amount_currency': -acm_line.amount_currency
})
self.reverse_entry_id = reversed_move
self.recompute()
return reversed_move
@api.multi
def reverse_moves(self, date=None, journal_id=None, auto=False):
date = date or fields.Date.today()
reversed_moves = self.env['account.move']
for ac_move in self:
#unreconcile all lines reversed
aml = ac_move.line_ids.filtered(lambda x: x.account_id.reconcile or x.account_id.internal_type == 'liquidity')
aml.remove_move_reconcile()
reversed_move = ac_move._reverse_move(date=date,
journal_id=journal_id,
auto=auto)
reversed_moves |= reversed_move
#reconcile together the reconcilable (or the liquidity aml) and their newly created counterpart
for account in set([x.account_id for x in aml]):
to_rec = aml.filtered(lambda y: y.account_id == account)
to_rec |= reversed_move.line_ids.filtered(lambda y: y.account_id == account)
#reconciliation will be full, so speed up the computation by using skip_full_reconcile_check in the context
to_rec.reconcile()
if reversed_moves:
reversed_moves._post_validate()
reversed_moves.post()
return [x.id for x in reversed_moves]
return []
@api.multi
def open_reconcile_view(self):
return self.line_ids.open_reconcile_view()
# FIXME: Clarify me and change me in master
@api.multi
def action_duplicate(self):
self.ensure_one()
action = self.env.ref('account.action_move_journal_line').read()[0]
action['target'] = 'inline'
action['context'] = dict(self.env.context)
action['context']['view_no_maturity'] = False
action['views'] = [(self.env.ref('account.view_move_form').id, 'form')]
action['res_id'] = self.copy().id
return action
@api.model
def _run_reverses_entries(self):
''' This method is called from a cron job. '''
records = self.search([
('state', '=', 'posted'),
('auto_reverse', '=', True),
('reverse_date', '<=', fields.Date.today()),
('reverse_entry_id', '=', False)])
for move in records:
date = None
if move.reverse_date and (not self.env.user.company_id.period_lock_date or move.reverse_date > self.env.user.company_id.period_lock_date):
date = move.reverse_date
move.reverse_moves(date=date, auto=True)
@api.multi
def action_view_reverse_entry(self):
action = self.env.ref('account.action_move_journal_line').read()[0]
action['views'] = [(self.env.ref('account.view_move_form').id, 'form')]
action['res_id'] = self.reverse_entry_id.id
return action
class AccountMoveLine(models.Model):
_name = "account.move.line"
_description = "Journal Item"
_order = "date desc, id desc"
@api.onchange('debit', 'credit', 'tax_ids', 'analytic_account_id', 'analytic_tag_ids')
def onchange_tax_ids_create_aml(self):
for line in self:
line.recompute_tax_line = True
@api.onchange('debit')
def _onchange_debit(self):
self.ensure_one()
if self.debit != 0:
self.credit = 0
@api.onchange('credit')
def _onchange_credit(self):
self.ensure_one()
if self.credit != 0:
self.debit = 0
@api.model_cr
def init(self):
""" change index on partner_id to a multi-column index on (partner_id, ref), the new index will behave in the
same way when we search on partner_id, with the addition of being optimal when having a query that will
search on partner_id and ref at the same time (which is the case when we open the bank reconciliation widget)
"""
cr = self._cr
cr.execute('DROP INDEX IF EXISTS account_move_line_partner_id_index')
cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('account_move_line_partner_id_ref_idx',))
if not cr.fetchone():
cr.execute('CREATE INDEX account_move_line_partner_id_ref_idx ON account_move_line (partner_id, ref)')
@api.depends('debit', 'credit', 'amount_currency', 'currency_id', 'matched_debit_ids', 'matched_credit_ids', 'matched_debit_ids.amount', 'matched_credit_ids.amount', 'move_id.state')
def _amount_residual(self):
""" Computes the residual amount of a move line from a reconcilable account in the company currency and the line's currency.
This amount will be 0 for fully reconciled lines or lines from a non-reconcilable account, the original line amount
for unreconciled lines, and something in-between for partially reconciled lines.
"""
for line in self:
if not line.account_id.reconcile and line.account_id.internal_type != 'liquidity':
line.reconciled = False
line.amount_residual = 0
line.amount_residual_currency = 0
continue
#amounts in the partial reconcile table aren't signed, so we need to use abs()
amount = abs(line.debit - line.credit)
amount_residual_currency = abs(line.amount_currency) or 0.0
sign = 1 if (line.debit - line.credit) > 0 else -1
if not line.debit and not line.credit and line.amount_currency and line.currency_id:
#residual for exchange rate entries
sign = 1 if float_compare(line.amount_currency, 0, precision_rounding=line.currency_id.rounding) == 1 else -1
for partial_line in (line.matched_debit_ids + line.matched_credit_ids):
# If line is a credit (sign = -1) we:
# - subtract matched_debit_ids (partial_line.credit_move_id == line)
# - add matched_credit_ids (partial_line.credit_move_id != line)
# If line is a debit (sign = 1), do the opposite.
sign_partial_line = sign if partial_line.credit_move_id == line else (-1 * sign)
amount += sign_partial_line * partial_line.amount
#getting the date of the matched item to compute the amount_residual in currency
if line.currency_id and line.amount_currency:
if partial_line.currency_id and partial_line.currency_id == line.currency_id:
amount_residual_currency += sign_partial_line * partial_line.amount_currency
else:
if line.balance and line.amount_currency:
rate = line.amount_currency / line.balance
else:
date = partial_line.credit_move_id.date if partial_line.debit_move_id == line else partial_line.debit_move_id.date
rate = line.currency_id.with_context(date=date).rate
amount_residual_currency += sign_partial_line * line.currency_id.round(partial_line.amount * rate)
#computing the `reconciled` field.
reconciled = False
digits_rounding_precision = line.company_id.currency_id.rounding
if (line.matched_debit_ids or line.matched_credit_ids) and float_is_zero(amount, precision_rounding=digits_rounding_precision):
if line.currency_id and line.amount_currency:
if float_is_zero(amount_residual_currency, precision_rounding=line.currency_id.rounding):
reconciled = True
else:
reconciled = True
line.reconciled = reconciled
line.amount_residual = line.company_id.currency_id.round(amount * sign)
line.amount_residual_currency = line.currency_id and line.currency_id.round(amount_residual_currency * sign) or 0.0
@api.depends('debit', 'credit')
def _store_balance(self):
for line in self:
line.balance = line.debit - line.credit
@api.model
def _get_currency(self):
currency = False
context = self._context or {}
if context.get('default_journal_id', False):
currency = self.env['account.journal'].browse(context['default_journal_id']).currency_id
return currency
@api.depends('debit', 'credit', 'move_id.matched_percentage', 'move_id.journal_id')
def _compute_cash_basis(self):
for move_line in self:
if move_line.journal_id.type in ('sale', 'purchase'):
move_line.debit_cash_basis = move_line.debit * move_line.move_id.matched_percentage
move_line.credit_cash_basis = move_line.credit * move_line.move_id.matched_percentage
else:
move_line.debit_cash_basis = move_line.debit
move_line.credit_cash_basis = move_line.credit
move_line.balance_cash_basis = move_line.debit_cash_basis - move_line.credit_cash_basis
@api.depends('move_id.line_ids', 'move_id.line_ids.tax_line_id', 'move_id.line_ids.debit', 'move_id.line_ids.credit')
def _compute_tax_base_amount(self):
for move_line in self:
if move_line.tax_line_id:
base_lines = move_line.move_id.line_ids.filtered(lambda line: move_line.tax_line_id in line.tax_ids)
move_line.tax_base_amount = abs(sum(base_lines.mapped('balance')))
else:
move_line.tax_base_amount = 0
@api.depends('move_id')
def _compute_parent_state(self):
for record in self.filtered('move_id'):
record.parent_state = record.move_id.state
name = fields.Char(string="Label")
quantity = fields.Float(digits=dp.get_precision('Product Unit of Measure'),
help="The optional quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very useful for some reports.")
product_uom_id = fields.Many2one('uom.uom', string='Unit of Measure')
product_id = fields.Many2one('product.product', string='Product')
debit = fields.Monetary(default=0.0, currency_field='company_currency_id')
credit = fields.Monetary(default=0.0, currency_field='company_currency_id')
balance = fields.Monetary(compute='_store_balance', store=True, currency_field='company_currency_id',
help="Technical field holding the debit - credit in order to open meaningful graph views from reports")
debit_cash_basis = fields.Monetary(currency_field='company_currency_id', compute='_compute_cash_basis', store=True)
credit_cash_basis = fields.Monetary(currency_field='company_currency_id', compute='_compute_cash_basis', store=True)
balance_cash_basis = fields.Monetary(compute='_compute_cash_basis', store=True, currency_field='company_currency_id',
help="Technical field holding the debit_cash_basis - credit_cash_basis in order to open meaningful graph views from reports")
amount_currency = fields.Monetary(default=0.0, help="The amount expressed in an optional other currency if it is a multi-currency entry.")
company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string="Company Currency", readonly=True,
help='Utility field to express amount currency', store=True)
currency_id = fields.Many2one('res.currency', string='Currency', default=_get_currency,
help="The optional other currency if it is a multi-currency entry.")
amount_residual = fields.Monetary(compute='_amount_residual', string='Residual Amount', store=True, currency_field='company_currency_id',
help="The residual amount on a journal item expressed in the company currency.")
amount_residual_currency = fields.Monetary(compute='_amount_residual', string='Residual Amount in Currency', store=True,
help="The residual amount on a journal item expressed in its currency (possibly not the company currency).")
tax_base_amount = fields.Monetary(string="Base Amount", compute='_compute_tax_base_amount', currency_field='company_currency_id', store=True)
account_id = fields.Many2one('account.account', string='Account', required=True, index=True,
ondelete="cascade", domain=[('deprecated', '=', False)], default=lambda self: self._context.get('account_id', False))
move_id = fields.Many2one('account.move', string='Journal Entry', ondelete="cascade",
help="The move of this entry line.", index=True, required=True, auto_join=True)
narration = fields.Text(related='move_id.narration', string='Narration', readonly=False)
ref = fields.Char(related='move_id.ref', string='Reference', store=True, copy=False, index=True, readonly=False)
payment_id = fields.Many2one('account.payment', string="Originator Payment", help="Payment that created this entry", copy=False)
statement_line_id = fields.Many2one('account.bank.statement.line', index=True, string='Bank statement line reconciled with this entry', copy=False, readonly=True)
statement_id = fields.Many2one('account.bank.statement', related='statement_line_id.statement_id', string='Statement', store=True,
help="The bank statement used for bank reconciliation", index=True, copy=False)
reconciled = fields.Boolean(compute='_amount_residual', store=True)
reconcile_model_id = fields.Many2one('account.reconcile.model', string="Reconciliation Model", copy=False)
full_reconcile_id = fields.Many2one('account.full.reconcile', string="Matching Number", copy=False, index=True)
matched_debit_ids = fields.One2many('account.partial.reconcile', 'credit_move_id', String='Matched Debits',
help='Debit journal items that are matched with this journal item.')
matched_credit_ids = fields.One2many('account.partial.reconcile', 'debit_move_id', String='Matched Credits',
help='Credit journal items that are matched with this journal item.')
journal_id = fields.Many2one('account.journal', related='move_id.journal_id', string='Journal', readonly=False,
index=True, store=True, copy=False) # related is required
blocked = fields.Boolean(string='No Follow-up', default=False,
help="You can check this box to mark this journal item as a litigation with the associated partner")
date_maturity = fields.Date(string='Due date', index=True, required=True, copy=False,
help="This field is used for payable and receivable journal entries. You can put the limit date for the payment of this line.")
date = fields.Date(related='move_id.date', string='Date', index=True, store=True, copy=False, readonly=False) # related is required
analytic_line_ids = fields.One2many('account.analytic.line', 'move_id', string='Analytic lines', oldname="analytic_lines")
tax_ids = fields.Many2many('account.tax', string='Taxes', domain=['|', ('active', '=', False), ('active', '=', True)])
tax_line_id = fields.Many2one('account.tax', string='Originator tax', ondelete='restrict')
analytic_account_id = fields.Many2one('account.analytic.account', string='Analytic Account', index=True)
analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags')
company_id = fields.Many2one('res.company', related='account_id.company_id', string='Company', store=True, readonly=True)
# TODO: put the invoice link and partner_id on the account_move
invoice_id = fields.Many2one('account.invoice', oldname="invoice")
partner_id = fields.Many2one('res.partner', string='Partner', ondelete='restrict')
tax_exigible = fields.Boolean(string='Appears in VAT report', default=True,
help="Technical field used to mark a tax line as exigible in the vat report or not (only exigible journal items are displayed). By default all new journal items are directly exigible, but with the feature cash_basis on taxes, some will become exigible only when the payment is recorded.")
parent_state = fields.Char(compute="_compute_parent_state", help="State of the parent account.move")
recompute_tax_line = fields.Boolean(store=False, help="Technical field used to know if the tax_ids field has been modified in the UI.")
tax_line_grouping_key = fields.Char(store=False, string='Old Taxes', help="Technical field used to store the old values of fields used to compute tax lines (in account.move form view) between the moment the user changed it and the moment the ORM reflects that change in its one2many")
_sql_constraints = [
('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in accounting entry !'),
('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in accounting entry !'),
]
@api.model
def default_get(self, fields):
rec = super(AccountMoveLine, self).default_get(fields)
if 'line_ids' not in self._context:
return rec
#compute the default credit/debit of the next line in case of a manual entry
balance = 0
for line in self.move_id.resolve_2many_commands(
'line_ids', self._context['line_ids'], fields=['credit', 'debit']):
balance += line.get('debit', 0) - line.get('credit', 0)
if len(self._context['line_ids']) > 1:
lines = self.move_id.resolve_2many_commands('line_ids', self._context['line_ids'][-2:], fields=['partner_id', 'account_id'])
if lines[0].get('partner_id', False) == lines[1].get('partner_id', False):
rec.update({'partner_id': lines[0].get('partner_id', False)})
if lines[0].get('account_id', False) == lines[1].get('account_id', False):
rec.update({'account_id': lines[0].get('account_id', False)})
if balance < 0:
rec.update({'debit': -balance})
if balance > 0:
rec.update({'credit': balance})
return rec
@api.multi
@api.constrains('tax_ids', 'tax_line_id')
def _check_tax_lock_date1(self):
for line in self:
if line.date <= (line.company_id.tax_lock_date or date.min):
raise ValidationError(_("The operation is refused as it would impact an already issued tax statement. " +
"Please change the journal entry date or the tax lock date set in the settings ({}) to proceed").format(line.company_id.tax_lock_date or date.min))
@api.multi
@api.constrains('credit', 'debit', 'date')
def _check_tax_lock_date2(self):
for line in self:
if (line.tax_ids or line.tax_line_id) and line.date <= (line.company_id.tax_lock_date or date.min):
raise ValidationError(_("The operation is refused as it would impact an already issued tax statement. " +
"Please change the journal entry date or the tax lock date set in the settings ({}) to proceed").format(line.company_id.tax_lock_date or date.min))
@api.multi
@api.constrains('currency_id', 'account_id')
def _check_currency(self):
for line in self:
account_currency = line.account_id.currency_id
if account_currency and account_currency != line.company_id.currency_id:
if not line.currency_id or line.currency_id != account_currency:
raise ValidationError(_('The selected account of your Journal Entry forces to provide a secondary currency. You should remove the secondary currency on the account.'))
@api.multi
@api.constrains('currency_id', 'amount_currency')
def _check_currency_and_amount(self):
for line in self:
if (line.amount_currency and not line.currency_id):
raise ValidationError(_("You cannot create journal items with a secondary currency without filling both 'currency' and 'amount currency' fields."))
@api.multi
@api.constrains('amount_currency', 'debit', 'credit')
def _check_currency_amount(self):
for line in self:
if line.amount_currency:
if (line.amount_currency > 0.0 and line.credit > 0.0) or (line.amount_currency < 0.0 and line.debit > 0.0):
raise ValidationError(_('The amount expressed in the secondary currency must be positive when account is debited and negative when account is credited.'))
@api.depends('account_id.user_type_id')
def _compute_is_unaffected_earnings_line(self):
for record in self:
unaffected_earnings_type = self.env.ref("account.data_unaffected_earnings")
record.is_unaffected_earnings_line = unaffected_earnings_type == record.account_id.user_type_id
@api.onchange('amount_currency', 'currency_id', 'account_id')
def _onchange_amount_currency(self):
'''Recompute the debit/credit based on amount_currency/currency_id and date.
However, date is a related field on account.move. Then, this onchange will not be triggered
by the form view by changing the date on the account.move.
To fix this problem, see _onchange_date method on account.move.
'''
for line in self:
company_currency_id = line.account_id.company_id.currency_id
amount = line.amount_currency
if line.currency_id and company_currency_id and line.currency_id != company_currency_id:
amount = line.currency_id._convert(amount, company_currency_id, line.company_id, line.date or fields.Date.today())
line.debit = amount > 0 and amount or 0.0
line.credit = amount < 0 and -amount or 0.0
####################################################
# Reconciliation methods
####################################################
@api.multi
def check_full_reconcile(self):
"""
This method check if a move is totally reconciled and if we need to create exchange rate entries for the move.
In case exchange rate entries needs to be created, one will be created per currency present.
In case of full reconciliation, all moves belonging to the reconciliation will belong to the same account_full_reconcile object.
"""
# Get first all aml involved
part_recs = self.env['account.partial.reconcile'].search(['|', ('debit_move_id', 'in', self.ids), ('credit_move_id', 'in', self.ids)])
amls = self
todo = set(part_recs)
seen = set()
while todo:
partial_rec = todo.pop()
seen.add(partial_rec)
for aml in [partial_rec.debit_move_id, partial_rec.credit_move_id]:
if aml not in amls:
amls += aml
for x in aml.matched_debit_ids | aml.matched_credit_ids:
if x not in seen:
todo.add(x)
partial_rec_ids = [x.id for x in seen]
if not amls:
return
# If we have multiple currency, we can only base ourselve on debit-credit to see if it is fully reconciled
currency = set([a.currency_id for a in amls if a.currency_id.id != False])
multiple_currency = False
if len(currency) != 1:
currency = False
multiple_currency = True
else:
currency = list(currency)[0]
# Get the sum(debit, credit, amount_currency) of all amls involved
total_debit = 0
total_credit = 0
total_amount_currency = 0
maxdate = date.min
to_balance = {}
cash_basis_partial = self.env['account.partial.reconcile']
for aml in amls:
cash_basis_partial |= aml.move_id.tax_cash_basis_rec_id
total_debit += aml.debit
total_credit += aml.credit
maxdate = max(aml.date, maxdate)
total_amount_currency += aml.amount_currency
# Convert in currency if we only have one currency and no amount_currency
if not aml.amount_currency and currency:
multiple_currency = True
total_amount_currency += aml.company_id.currency_id._convert(aml.balance, currency, aml.company_id, aml.date)
# If we still have residual value, it means that this move might need to be balanced using an exchange rate entry
if aml.amount_residual != 0 or aml.amount_residual_currency != 0:
if not to_balance.get(aml.currency_id):
to_balance[aml.currency_id] = [self.env['account.move.line'], 0]
to_balance[aml.currency_id][0] += aml
to_balance[aml.currency_id][1] += aml.amount_residual != 0 and aml.amount_residual or aml.amount_residual_currency
# Check if reconciliation is total
# To check if reconciliation is total we have 3 differents use case:
# 1) There are multiple currency different than company currency, in that case we check using debit-credit
# 2) We only have one currency which is different than company currency, in that case we check using amount_currency
# 3) We have only one currency and some entries that don't have a secundary currency, in that case we check debit-credit
# or amount_currency.
# 4) Cash basis full reconciliation
# - either none of the moves are cash basis reconciled, and we proceed
# - or some moves are cash basis reconciled and we make sure they are all fully reconciled
digits_rounding_precision = amls[0].company_id.currency_id.rounding
if (
(
not cash_basis_partial or (cash_basis_partial and all([p >= 1.0 for p in amls._get_matched_percentage().values()]))
) and
(
currency and float_is_zero(total_amount_currency, precision_rounding=currency.rounding) or
multiple_currency and float_compare(total_debit, total_credit, precision_rounding=digits_rounding_precision) == 0
)
):
exchange_move_id = False
# Eventually create a journal entry to book the difference due to foreign currency's exchange rate that fluctuates
if to_balance and any([not float_is_zero(residual, precision_rounding=digits_rounding_precision) for aml, residual in to_balance.values()]):
exchange_move = self.env['account.move'].create(
self.env['account.full.reconcile']._prepare_exchange_diff_move(move_date=maxdate, company=amls[0].company_id))
part_reconcile = self.env['account.partial.reconcile']
for aml_to_balance, total in to_balance.values():
if total:
rate_diff_amls, rate_diff_partial_rec = part_reconcile.create_exchange_rate_entry(aml_to_balance, exchange_move)
amls += rate_diff_amls
partial_rec_ids += rate_diff_partial_rec.ids
else:
aml_to_balance.reconcile()
exchange_move.post()
exchange_move_id = exchange_move.id
#mark the reference of the full reconciliation on the exchange rate entries and on the entries
self.env['account.full.reconcile'].create({
'partial_reconcile_ids': [(6, 0, partial_rec_ids)],
'reconciled_line_ids': [(6, 0, amls.ids)],
'exchange_move_id': exchange_move_id,
})
@api.multi
def _reconcile_lines(self, debit_moves, credit_moves, field):
""" This function loops on the 2 recordsets given as parameter as long as it
can find a debit and a credit to reconcile together. It returns the recordset of the
account move lines that were not reconciled during the process.
"""
(debit_moves + credit_moves).read([field])
to_create = []
cash_basis = debit_moves and debit_moves[0].account_id.internal_type in ('receivable', 'payable') or False
cash_basis_percentage_before_rec = {}
dc_vals ={}
while (debit_moves and credit_moves):
debit_move = debit_moves[0]
credit_move = credit_moves[0]
company_currency = debit_move.company_id.currency_id
# We need those temporary value otherwise the computation might be wrong below
temp_amount_residual = min(debit_move.amount_residual, -credit_move.amount_residual)
temp_amount_residual_currency = min(debit_move.amount_residual_currency, -credit_move.amount_residual_currency)
dc_vals[(debit_move.id, credit_move.id)] = (debit_move, credit_move, temp_amount_residual_currency)
amount_reconcile = min(debit_move[field], -credit_move[field])
#Remove from recordset the one(s) that will be totally reconciled
# For optimization purpose, the creation of the partial_reconcile are done at the end,
# therefore during the process of reconciling several move lines, there are actually no recompute performed by the orm
# and thus the amount_residual are not recomputed, hence we have to do it manually.
if amount_reconcile == debit_move[field]:
debit_moves -= debit_move
else:
debit_moves[0].amount_residual -= temp_amount_residual
debit_moves[0].amount_residual_currency -= temp_amount_residual_currency
if amount_reconcile == -credit_move[field]:
credit_moves -= credit_move
else:
credit_moves[0].amount_residual += temp_amount_residual
credit_moves[0].amount_residual_currency += temp_amount_residual_currency
#Check for the currency and amount_currency we can set
currency = False
amount_reconcile_currency = 0
if field == 'amount_residual_currency':
currency = credit_move.currency_id.id
amount_reconcile_currency = temp_amount_residual_currency
amount_reconcile = temp_amount_residual
if cash_basis:
tmp_set = debit_move | credit_move
cash_basis_percentage_before_rec.update(tmp_set._get_matched_percentage())
to_create.append({
'debit_move_id': debit_move.id,
'credit_move_id': credit_move.id,
'amount': amount_reconcile,
'amount_currency': amount_reconcile_currency,
'currency_id': currency,
})
cash_basis_subjected = []
part_rec = self.env['account.partial.reconcile']
with self.env.norecompute():
for partial_rec_dict in to_create:
debit_move, credit_move, amount_residual_currency = dc_vals[partial_rec_dict['debit_move_id'], partial_rec_dict['credit_move_id']]
# /!\ NOTE: Exchange rate differences shouldn't create cash basis entries
# i. e: we don't really receive/give money in a customer/provider fashion
# Since those are not subjected to cash basis computation we process them first
if not amount_residual_currency and debit_move.currency_id and credit_move.currency_id:
part_rec.create(partial_rec_dict)
else:
cash_basis_subjected.append(partial_rec_dict)
for after_rec_dict in cash_basis_subjected:
new_rec = part_rec.create(after_rec_dict)
# if the pair belongs to move being reverted, do not create CABA entry
if cash_basis and not (new_rec.debit_move_id + new_rec.credit_move_id).mapped('move_id').mapped('reverse_entry_id'):
new_rec.create_tax_cash_basis_entry(cash_basis_percentage_before_rec)
self.recompute()
return debit_moves+credit_moves
@api.multi
def auto_reconcile_lines(self):
# Create list of debit and list of credit move ordered by date-currency
debit_moves = self.filtered(lambda r: r.debit != 0 or r.amount_currency > 0)
credit_moves = self.filtered(lambda r: r.credit != 0 or r.amount_currency < 0)
debit_moves = debit_moves.sorted(key=lambda a: (a.date_maturity or a.date, a.currency_id))
credit_moves = credit_moves.sorted(key=lambda a: (a.date_maturity or a.date, a.currency_id))
# Compute on which field reconciliation should be based upon:
field = self[0].account_id.currency_id and 'amount_residual_currency' or 'amount_residual'
#if all lines share the same currency, use amount_residual_currency to avoid currency rounding error
if self[0].currency_id and all([x.amount_currency and x.currency_id == self[0].currency_id for x in self]):
field = 'amount_residual_currency'
# Reconcile lines
ret = self._reconcile_lines(debit_moves, credit_moves, field)
return ret
def _check_reconcile_validity(self):
#Perform all checks on lines
company_ids = set()
all_accounts = []
for line in self:
company_ids.add(line.company_id.id)
all_accounts.append(line.account_id)
if (line.matched_debit_ids or line.matched_credit_ids) and line.reconciled:
raise UserError(_('You are trying to reconcile some entries that are already reconciled.'))
if len(company_ids) > 1:
raise UserError(_('To reconcile the entries company should be the same for all entries.'))
if len(set(all_accounts)) > 1:
raise UserError(_('Entries are not from the same account.'))
if not (all_accounts[0].reconcile or all_accounts[0].internal_type == 'liquidity'):
raise UserError(_('Account %s (%s) does not allow reconciliation. First change the configuration of this account to allow it.') % (all_accounts[0].name, all_accounts[0].code))
@api.multi
def reconcile(self, writeoff_acc_id=False, writeoff_journal_id=False):
# Empty self can happen if the user tries to reconcile entries which are already reconciled.
# The calling method might have filtered out reconciled lines.
if not self:
return True
self._check_reconcile_validity()
#reconcile everything that can be
remaining_moves = self.auto_reconcile_lines()