Fix some bugs and improve code reducing lines.

Task: #047268
This commit is contained in:
Bernat Brunet 2023-11-11 16:36:18 +01:00
parent 22238c393b
commit ee9799aca9
7 changed files with 83 additions and 126 deletions

View File

@ -8,22 +8,39 @@ from trytond.tools import grouped_slice
class Invoice(metaclass=PoolMeta):
__name__ = 'account.invoice'
def get_allow_draft(self, name):
pool = Pool()
Commission = pool.get('commission')
result = super().get_allow_draft(name)
invoiced = Commission.search([
('origin.invoice', '=', self.id, 'account.invoice.line'),
('invoice_line', '!=', None),
])
if invoiced:
result = False
return result
@classmethod
def draft(cls, invoices):
pool = Pool()
Commission = pool.get('commission')
to_delete = []
for sub_invoices in grouped_slice(invoices):
ids = [i.id for i in sub_invoices]
commissions = Commission.search([
to_delete = Commission.search([
('origin.invoice', 'in', ids, 'account.invoice.line'),
('invoice_line', '=', None),
])
if commissions:
commissions_origin = Commission.search([
('origin.id', 'in', [c.id for c in commissions], 'commission'),
if to_delete:
to_delete_origin = Commission.search([
('origin.id', 'in',
[x.id for x in to_delete], 'commission'),
('invoice_line', '=', None),
])
if commissions_origin:
commissions += commissions_origin
Commission.delete(commissions)
if to_delete_origin:
to_delete += to_delete_origin
Commission.delete(to_delete)
return super(Invoice, cls).draft(invoices)

View File

@ -24,7 +24,14 @@ class Invoice(metaclass=PoolMeta):
cls._buttons['draft']['depends'] += tuple(['allow_draft'])
def get_allow_draft(self, name):
if self.state not in {'posted', 'cancelled', 'validated'}:
# when IN invoice is validate from scratch, the move is in 'draft'
# state, so in this case could be draft in a "normal" way
if (self.state == 'validated' and self.move
and self.move.state != 'draft'):
return False
elif self.state == 'cancelled' and self.number is not None:
return False
elif self.state in {'paid', 'draft'}:
return False
elif self.state == 'posted':
lines_to_pay = [l for l in self.lines_to_pay
@ -49,38 +56,25 @@ class Invoice(metaclass=PoolMeta):
to_draft = []
to_save = []
for invoice in invoices:
if (not invoice.allow_draft
or (invoice.state in ('validated', 'cancelled')
and invoice.number is None)):
if not invoice.allow_draft:
continue
move = invoice.move
if move:
if move.state == 'draft':
to_draft.append(invoice)
else:
to_save.append(invoice)
cancel_move = move.cancel(reversal=True)
Move.post([cancel_move])
moves.extend((invoice.move, cancel_move))
invoice.move = None
else:
to_draft.append(invoice)
continue
if invoice.state == 'canceled':
invoice.additional_moves += tuple(
[invoice.move, invoice.cnacel_move])
to_save.append(invoice)
continue
if invoice.state == 'validated':
to_save.append(invoice)
continue
lines_to_pay = [l for l in invoice.lines_to_pay
if not l.reconciliation]
extra_lines = [l for l in invoice.move.lines
if not l.account.reconcile]
compensation_move = Move.create_compensation_move(
lines_to_pay + extra_lines, origin=invoice)
moves.append(compensation_move)
invoice.additional_moves += tuple(
[invoice.move, compensation_move])
invoice.move = None
to_save.append(invoice)
if moves:
Move.post(moves)
if invoice.cancel_move:
moves.append(invoice.cancel_move)
invoice.cancel_move = None
invoice.additional_moves += tuple(moves)
# Only make the special steps for the invoices that came from 'posted'
# state or 'validated', 'canceled' with number, so the invoice have one
@ -103,5 +97,6 @@ class Invoice(metaclass=PoolMeta):
if to_reconcile:
MoveLine.reconcile(to_reconcile)
# Remove links to lines which actually do not pay the invoice
if to_save:
cls._clean_payments(to_save)

View File

@ -16,12 +16,12 @@ msgstr ""
msgctxt "model:ir.message,text:msg_invoice_in_payment"
msgid ""
"The invoice %(invoice)s have one or more move lines in payments [IDs: "
"%(payments)s]. This means that is possible that this payment will be in a "
"payment group and this group upload on a Bank. Are you sure that you want to"
" draft the invoice?"
"The invoice %(invoice)s could not be possible to draft, becasue it have one "
"or more move lines in payments [IDs: %(payments)s]. This means that is "
"possible that this payment will be in a payment group and this group upload "
"on a Bank."
msgstr ""
"La factura %(invoice)s té un o més apunts relacioants a pagaments [ID: "
"%(payments)s]. Això vol dir que és possible que aquest pagament estigui en "
"una remesa bancària i aquesta estigui pujada ja al Banc. Esteu segur que "
"voleu passar a esborrany la factura?"
"La factura %(invoice)s no es pot passar a esborrany, perquè té un o més "
"apunts relacionats a pagaments [ID: %(payments)s]. Això vol dir que és "
"possible que aquest pagament estigui en una remesa bancària i aquesta estigui "
"pujada ja al Banc."

View File

@ -16,12 +16,12 @@ msgstr ""
msgctxt "model:ir.message,text:msg_invoice_in_payment"
msgid ""
"The invoice %(invoice)s have one or more move lines in payments [IDs: "
"%(payments)s]. This means that is possible that this payment will be in a "
"payment group and this group upload on a Bank. Are you sure that you want to"
" draft the invoice?"
"The invoice %(invoice)s could not be possible to draft, becasue it have one "
"or more move lines in payments [IDs: %(payments)s]. This means that is "
"possible that this payment will be in a payment group and this group upload "
"on a Bank."
msgstr ""
"La factura %(invoice)s tiene uno o más apuntes relacionados en pagos [ID: "
"%(paids)s]. Esto significa que es posible que este pago sea en una remesa "
"y esta sea ya subida al Banco. ¿Estás seguro de que quieres pasar a borrador "
"la factura?"
"La factura %(invoice)s no se puede pasar a borrador, porque tiene uno o más "
"apuntes relacionados a pagos [ID: %(payments)s]. Esto quiere decir que és "
"posible que estos pagos esten ya en una remesa bancárea y ésta esté subida "
"al Banco."

View File

@ -7,7 +7,7 @@ this repository contains the full copyright notices and license terms. -->
<field name="text">You cannot create an account compesantion move in the period %(period)s because is closed.</field>
</record>
<record model="ir.message" id="msg_invoice_in_payment">
<field name="text">The invoice %(invoice)s have one or more move lines in payments [IDs: %(payments)s]. This means that is possible that this payment will be in a payment group and this group upload on a Bank. Are you sure that you want to draft the invoice?</field>
<field name="text">The invoice %(invoice)s could not be possible to draft, becasue it have one or more move lines in payments [IDs: %(payments)s]. This means that is possible that this payment will be in a payment group and this group upload on a Bank.</field>
</record>
</data>
</tryton>

67
move.py
View File

@ -10,80 +10,31 @@ class Move(metaclass=PoolMeta):
@classmethod
def check_modify(cls, *args, **kwargs):
# As now the moves related to an invoice are not delete when 'darf'
# the invoice, is needed to modify some restricted fields when the
# move is in post state
if Transaction().context.get('invoice_posted2draft', False):
return
return super().check_modify(*args, **kwargs)
@classmethod
def delete(cls, moves):
# When invoice is set to 'draft', try to delete the move's assocaited
# in 'move' and 'additional_move' fields. If this moves are post
# need to be not delete and matain them as historize
if Transaction().context.get('invoice_posted2draft', False):
return
super().delete(moves)
@classmethod
def create_compensation_move(cls, lines, origin=None, journal=None):
"""
Create a compensation move from move lines.
And add the origin if is setted.
If origini is setted and it is an invoice, for example, the
journal is not needed becasue is taken the invoice.
"""
pool = Pool()
MoveLine = pool.get('account.move.line')
Period = pool.get('account.period')
Date = pool.get('ir.date')
if not lines:
return None
company_id = (origin.company.id if hasattr(origin, 'company')
else Transaction().context.get('company'))
with Transaction().set_context(company=company_id):
date = Date.today()
period_id = Period.find(company_id, date=date)
if not period_id:
raise UserError(gettext(
'account_invoice_posted2draft.msg_draft_closed_period',
period=Period(period_id).rec_name,
))
if not journal:
journal = origin.journal if hasattr(origin, 'journal') else None
move = cls()
move.journal = journal
move.period = period_id
move.date = date
move.origin = origin
move.company = company_id
move.save()
default = {
'move': move,
'debit': lambda data: data['credit'],
'credit': lambda data: data['debit'],
'amount_second_currency': (
lambda data: data['amount_second_currency'] * -1
if data['amount_second_currency']
else data['amount_second_currency']),
'tax_lines.amount': lambda data: data['amount'] * -1,
'origin': (
lambda data: 'account.move.line,%s' % data['id']),
'analytic_lines.debit': lambda data: data['credit'],
'analytic_lines.credit': lambda data: data['debit'],
'bank_account': None,
'payment_type': None,
}
move_lines = MoveLine.copy(lines, default=default)
return move
class Line(metaclass=PoolMeta):
__name__ = 'account.move.line'
@classmethod
def check_modify(cls, lines, modified_fields=None):
# As now the moves related to an invoice are not delete when 'darf'
# the invoice, is needed to modify some restricted fields when the
# move is in post state
if Transaction().context.get('invoice_posted2draft', False):
return
return super().check_modify(lines, modified_fields)

View File

@ -3,7 +3,7 @@
# the full copyright notices and license terms.
from trytond.pool import Pool, PoolMeta
from trytond.i18n import gettext
from trytond.exceptions import UserWarning
from trytond.exceptions import UserError
class Invoice(metaclass=PoolMeta):
@ -30,14 +30,8 @@ class Invoice(metaclass=PoolMeta):
('state', '!=', 'failed'),
])
if payments:
warning_key = Warning.format(
'invoice_in_payment', future_invoices)
if Warning.check(warning_key):
raise UserWarning(warning_key,
gettext('account_invoice_posted2draft'
'.msg_invoice_in_payment',
invoice=invoice.rec_name,
payments=", ".join(
[p.id for p in payments])))
raise UserError(gettext('account_invoice_posted2draft'
'.msg_invoice_in_payment',
invoice=invoice.rec_name,
payments=", ".join([p.id for p in payments])))
return super().draft(invoices)