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
  • Loading branch information
ica-adhoc committed Jun 15, 2023
1 parent ebe0d77 commit a1efd0e
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 30 deletions.
4 changes: 2 additions & 2 deletions account_payment_term_surcharge/data/ir_cron_data.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
<record id="cron_recurring_surcharges_invoices" model="ir.cron">
<field name="name">Create Surcharges Invoices</field>
<field name="user_id" ref="base.user_root"/>
<field name="interval_number">1</field>
<field name="interval_type">days</field>
<field name="interval_number">15</field>
<field name="interval_type">minutes</field>
<field name="numbercall">-1</field>
<field name="model_id" ref="model_account_move"/>
<field name="code">model._cron_recurring_surcharges_invoices()</field>
Expand Down
64 changes: 37 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,39 @@
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),
domain = [
('next_surcharge_date', '<=', current_date),
('state', '=', 'posted'),
('invoice_payment_state', '=', 'not_paid')],
# buscamos facturas que tengan surcharges, esten posteadas y aun no pagadas
).create_surcharges_invoices()
('invoice_payment_state', '=', 'not_paid')]
_logger.info('Running Surcharges Invoices Cron Job, pendientes por procesar %s facturas' % self.search_count(domain)
current_date = fields.Date.context_today(self)
self.search(domain, limit=600).create_surcharges_invoices()

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 +49,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 +76,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 a1efd0e

Please sign in to comment.