Skip to content

Commit

Permalink
[FIX] account_payment_term_surcharge: change cron
Browse files Browse the repository at this point in the history
Se cambia la logica de la generacion de notas de debito para que
el cron pueda correr por partes

closes #418

X-original-commit: bf9ce01
Signed-off-by: Katherine Zaoral <[email protected]>
Signed-off-by: Ignacio Cainelli <[email protected]>
  • Loading branch information
ica-adhoc committed Jul 28, 2023
1 parent 1947123 commit b46226b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 29 deletions.
2 changes: 1 addition & 1 deletion account_payment_term_surcharge/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
##############################################################################
{
'name': 'Surcharges on payment terms',
'version': "15.0.1.0.0",
'version': "15.0.1.1.0",
'category': 'Accounting',
'sequence': 14,
'summary': 'Allow to add surcharges for invoices on payment terms',
Expand Down
67 changes: 40 additions & 27 deletions account_payment_term_surcharge/models/account_move.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from odoo import fields, models, _
from odoo import fields, models, _, api
from odoo.exceptions import UserError

import logging
Expand All @@ -8,51 +8,42 @@
class AccountMove(models.Model):
_inherit = 'account.move'

def _get_payment_term_surcharges(self):
result = []
for surcharge in self.invoice_payment_term_id.surcharge_ids:
result.append({'date': surcharge._calculate_date(self.invoice_date), 'surcharge': surcharge.surcharge})
result.sort(key=lambda x: x['date'])
return result
next_surcharge_date = fields.Date(compute='_compute_next_surcharge', store=True)
next_surcharge_percent = fields.Float(compute='_compute_next_surcharge', store=True)

def _cron_recurring_surcharges_invoices(self):
_logger.info('Running Surcharges Invoices Cron Job')
self.search([
('invoice_payment_term_id.surcharge_ids', '!=', False),
def _cron_recurring_surcharges_invoices(self, batch_size=60):
current_date = fields.Date.context_today(self)
domain = [
('next_surcharge_date', '<=', current_date),
('state', '=', 'posted'),
('payment_state', '=', 'not_paid')],
# buscamos facturas que tengan surcharges, esten posteadas y aun no pagadas
).create_surcharges_invoices()
('payment_state', '=', 'not_paid')]
_logger.info('Running Surcharges Invoices Cron Job, pendientes por procesar %s facturas' % self.search_count(domain))
to_create = self.search(domain)
to_create[:batch_size].create_surcharges_invoices()
if len(to_create) > batch_size:
self.env.ref('account_payment_term_surcharge.cron_recurring_surcharges_invoices')._trigger()

def create_surcharges_invoices(self):
for rec in self:
_logger.info(
'Creating Surcharges Invoices (id: %s, company: %s)', rec.id,
rec.company_id.name)
current_date = fields.Date.context_today(self)
surcharges = rec._get_payment_term_surcharges()
for surcharge in surcharges:
if surcharge.get('date') <= current_date and surcharge.get('date') not in rec.debit_note_ids.mapped('invoice_date'):
# si tiene un surcharge el dia de hoy, se evalua que no tenga notas de debito
# con fecha de hoy, en caso de que tenga, se corre el create_invoice
rec.create_surcharge_invoice(surcharge)
rec.create_surcharge_invoice(rec.next_surcharge_date, rec.next_surcharge_percent)

def create_surcharge_invoice(self, surcharge):
def create_surcharge_invoice(self, surcharge_date, surcharge_percent):
self.ensure_one()
product = self.company_id.payment_term_surcharge_product_id
if not product:
raise UserError('Atención, debes configurar un producto por defecto para que aplique a la hora de crear las facturas de recargo')
debt = self.amount_residual
surcharge_percent = surcharge.get('surcharge')
to_date = surcharge.get('date')
move_debit_note_wiz = self.env['account.debit.note'].with_context(active_model="account.move",
active_ids=self.ids).create({
'date': to_date,
'date': surcharge_date,
'reason': 'Surcharge Invoice',
})
debit_note = self.env['account.move'].browse(move_debit_note_wiz.create_debit().get('res_id'))
debit_note.narration = product.name + '.\n' + self.prepare_info(to_date, debt, surcharge.get('surcharge'))
self._add_surcharge_line(debit_note, product, debt, to_date, surcharge_percent)
debit_note.narration = product.name + '.\n' + self.prepare_info(surcharge_date, debt, surcharge_percent)
self._add_surcharge_line(debit_note, product, debt, surcharge_date, surcharge_percent)
if self.company_id.payment_term_surcharge_invoice_auto_post:
try:
debit_note.action_post()
Expand All @@ -61,6 +52,7 @@ def create_surcharge_invoice(self, surcharge):
"Something went wrong validating "
"surcharge invoice: {}".format(exp))
raise exp
self._compute_next_surcharge()

def prepare_info(self, to_date, debt, surcharge):
self.ensure_one()
Expand All @@ -87,3 +79,24 @@ def _add_surcharge_line(self, debit_note, product, debt, to_date, surcharge):
debit_note.invoice_line_ids[0].price_unit = (surcharge / 100) * debt
debit_note.invoice_line_ids[0].name = product.name + '.\n' + comment
debit_note._recompute_dynamic_lines()

@api.depends('invoice_payment_term_id', 'invoice_date')
def _compute_next_surcharge(self):
for rec in self:
if rec.invoice_payment_term_id.surcharge_ids != False:
surcharges = []
debit_note_dates = rec.debit_note_ids.mapped('invoice_date')
for surcharge in rec.invoice_payment_term_id.surcharge_ids:
tentative_date = surcharge._calculate_date(rec.invoice_date)
if tentative_date not in debit_note_dates:
surcharges.append({'date': tentative_date, 'surcharge': surcharge.surcharge})
surcharges.sort(key=lambda x: x['date'])
if len(surcharges) > 0:
rec.next_surcharge_date = surcharges[0].get('date')
rec.next_surcharge_percent = surcharges[0].get('surcharge')
else:
rec.next_surcharge_date = False
rec.next_surcharge_percent = False
else:
rec.next_surcharge_date = False
rec.next_surcharge_percent = False
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def _onchange_option(self):
def _calculate_date(self, date_ref=None):
''' Se retorna la fecha de un recargo segun una fecha dada, esto se hace
teniendo en cuenta la configuracion propia del recargo. '''
date_ref = date_ref or fields.Date.today()
date_ref = date_ref or fields.Date.context_today(self)
next_date = fields.Date.from_string(date_ref)
if self.option == 'day_after_invoice_date':
next_date += relativedelta(days=self.days)
Expand Down

0 comments on commit b46226b

Please sign in to comment.