Skip to content

Commit

Permalink
[MIG] account_payment_term_surcharge: Migration to 16.0
Browse files Browse the repository at this point in the history
closes #440

Signed-off-by: Filoquin adhoc <maq@adhoc.com.ar>
  • Loading branch information
ica-adhoc committed Nov 6, 2023
1 parent 3ce7f8a commit e51061a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 47 deletions.
4 changes: 2 additions & 2 deletions account_payment_term_surcharge/__manifest__.py
Expand Up @@ -19,7 +19,7 @@
##############################################################################
{
'name': 'Surcharges on payment terms',
'version': "15.0.1.0.0",
'version': "16.0.1.0.0",
'category': 'Accounting',
'sequence': 14,
'summary': 'Allow to add surcharges for invoices on payment terms',
Expand All @@ -37,6 +37,6 @@
'security/ir.model.access.csv',
'data/ir_cron_data.xml'
],
'installable': False,
'installable': True,
'application': False,
}
88 changes: 43 additions & 45 deletions account_payment_term_surcharge/models/account_move.py
@@ -1,4 +1,4 @@
from odoo import fields, models, _
from odoo import fields, models, _, api, Command
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'))
debit_note.write({'invoice_line_ids': self._prepare_surcharge_line(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,10 +52,10 @@ 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()
# Format date to customer language
lang_code = self.env.context.get('lang', self.env.user.lang)
lang = self.env['res.lang']._lang_get(lang_code)
date_format = lang.date_format
Expand All @@ -75,23 +66,30 @@ def prepare_info(self, to_date, debt, surcharge):
to_date_format, debt, surcharge)
return res

def _prepare_surcharge_line(self, product, debt, to_date, surcharge):
def _add_surcharge_line(self, debit_note, product, debt, to_date, surcharge):
self.ensure_one()
partner = self.partner_id
comment = self.prepare_info(to_date, debt, surcharge)
# fpos = partner.property_account_position_id
# taxes = product.taxes_id.filtered(
# lambda r: r.company_id == self.company_id)
# tax_id = fpos.map_tax(taxes, product)
#TODO ver si se agrega el tax manualmente o no
invoice_line_vals = [(0, 0, {
"product_id": product.id,
"quantity": 1.0,
"price_unit": (surcharge / 100) * debt,
"partner_id": partner.id,
"name": product.name + '.\n' + comment,
# "analytic_account_id": self.env.context.get('analytic_id', False),
# "tax_ids": [(6, 0, tax_id.ids)]
})]
debit_note = debit_note.with_context(check_move_validity=False)
line_vals = [Command.create({"product_id": product.id, "price_unit": (surcharge / 100) * debt, "name": product.name + '.\n' + comment})]
debit_note.write({'invoice_line_ids': line_vals})

return invoice_line_vals
@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

0 comments on commit e51061a

Please sign in to comment.