Skip to content

Commit

Permalink
Fixed customs errors
Browse files Browse the repository at this point in the history
  • Loading branch information
rosenvladimirov committed May 6, 2024
1 parent 57f6108 commit 951c9d0
Show file tree
Hide file tree
Showing 8 changed files with 149 additions and 84 deletions.
107 changes: 104 additions & 3 deletions l10n_bg_tax_admin/models/account_move.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ class AccountMove(models.Model):
)
l10n_bg_customs_date_custom_id = fields.Date("Customs date", related='l10n_bg_customs_invoice_id.l10n_bg_customs_date')
l10n_bg_name_custom_id = fields.Char("Customs number", related='l10n_bg_customs_invoice_id.l10n_bg_name')
l10n_bg_customs_invoice_ids = fields.Many2many('account.move',
'customs_invoices_rel',
'invoice_id',
'customs_id',
string='Used invoices in customs',
check_company=True,
copy=False,
readonly=True,
states={'draft': [('readonly', False)]},
)

# === Partner fields === #
l10n_bg_customs_partner_id = fields.Many2one('res.partner',
Expand All @@ -73,6 +83,11 @@ class AccountMove(models.Model):
default=lambda self: self._default_l10n_bg_currency_rate(),
help="Statistics currency rate for customs in Bulgaria.",
)
tax_totals_signed = fields.Binary(
string="Invoice Totals in Currency",
compute='_compute_tax_totals_signed',
exportable=False,
)

@api.depends('currency_id', 'company_id', 'date')
def _default_l10n_bg_currency_rate(self):
Expand Down Expand Up @@ -136,13 +151,88 @@ def _get_move_display_name(self, show_ref=False):
name += self.l10n_bg_name and "(%s)" % self.l10n_bg_name or ""
return name

@api.depends_context('lang')
@api.depends(
'invoice_line_ids.currency_rate',
'invoice_line_ids.tax_base_amount',
'invoice_line_ids.tax_line_id',
'invoice_line_ids.price_total',
'invoice_line_ids.price_subtotal',
'invoice_payment_term_id',
'partner_id',
'currency_id',
)
def _compute_tax_totals_signed(self):
for move in self:
if move.is_invoice(include_receipts=True):
base_lines = move.invoice_line_ids.filtered(lambda line: line.display_type == 'product')
base_line_values_list = [line._convert_to_tax_base_line_dict() for line in base_lines]
sign = move.direction_sign
if move.id:
# The invoice is stored so we can add the early payment discount lines directly to reduce the
# tax amount without touching the untaxed amount.
base_line_values_list += [
{
**line._convert_to_tax_base_line_dict(),
'handle_price_include': False,
'quantity': 1.0,
'price_unit': sign * line.amount_currency,
}
for line in move.line_ids.filtered(lambda line: line.display_type == 'epd')
]

kwargs = {
'base_lines': base_line_values_list,
'currency': move.currency_id or move.journal_id.currency_id or move.company_id.currency_id,
}

if move.id:
kwargs['tax_lines'] = [
line._convert_to_tax_line_dict()
for line in move.line_ids.filtered(lambda line: line.display_type == 'tax')
]
else:
# In case the invoice isn't yet stored, the early payment discount lines are not there. Then,
# we need to simulate them.
epd_aggregated_values = {}
for base_line in base_lines:
if not base_line.epd_needed:
continue
for grouping_dict, values in base_line.epd_needed.items():
epd_values = epd_aggregated_values.setdefault(grouping_dict, {'price_subtotal': 0.0})
epd_values['price_subtotal'] += values['price_subtotal']

for grouping_dict, values in epd_aggregated_values.items():
taxes = None
if grouping_dict.get('tax_ids'):
taxes = self.env['account.tax'].browse(grouping_dict['tax_ids'][0][2])

kwargs['base_lines'].append(self.env['account.tax']._convert_to_tax_base_line_dict(
None,
partner=move.partner_id,
currency=move.currency_id,
taxes=taxes,
price_unit=values['price_subtotal'],
quantity=1.0,
account=self.env['account.account'].browse(grouping_dict['account_id']),
analytic_distribution=values.get('analytic_distribution'),
price_subtotal=values['price_subtotal'],
is_refund=move.move_type in ('out_refund', 'in_refund'),
handle_price_include=False,
extra_context={'_extra_grouping_key_': 'epd'},
))
move.tax_totals_signed = self.env['account.tax']._prepare_tax_totals_signed(**kwargs)
else:
move.tax_totals_signed = None

def _new_entry_vals(self, fiscal_position_id):
return {
'move_type': 'entry',
'date': self.date,
'fiscal_position_id': fiscal_position_id.id,
'line_ids': [Command.clear()],
'invoice_line_ids': [Command.clear()],
'l10n_bg_customs_invoice_ids': [Command.set(self.ids)]
}

def _post(self, soft=True):
Expand Down Expand Up @@ -186,7 +276,7 @@ def _post(self, soft=True):
'l10n_bg_customs_date': move.invoice_date,
'l10n_bg_customs_commercial_partner_id': move.commercial_partner_id.id,
'l10n_bg_customs_partner_shipping_id': move.partner_shipping_id.id,
'invoice_line_ids': customs_id._customs_aml(move, new_entry_id, map_id, nra_id),
'invoice_line_ids': customs_id._customs_aml(move, new_entry_id, map_id),
})
new_entry_id._default_l10n_bg_currency_rate()

Expand All @@ -212,10 +302,13 @@ def button_draft(self):
self.env['account.move.bg.customs'].search([
('move_id', '=', line.l10n_bg_customs_id.id),
]).unlink()
self.env['account.move'].search([
customs_move_id = self.env['account.move'].search([
('id', '=', line.l10n_bg_customs_invoice_id.id),
('move_type', '=', 'entry')
]).unlink()
])
if customs_move_id.state == 'posted':
customs_move_id.button_draft()
customs_move_id.unlink()

if line.l10n_bg_protocol_invoice_id:
self.env['account.move.bg.protocol'].search([
Expand Down Expand Up @@ -259,6 +352,14 @@ def _onchange_l10n_bg_currency_rate(self):
self.line_ids._compute_currency_rate()
self.line_ids._inverse_amount_currency()

@api.onchange('l10n_bg_customs_invoice_ids')
def _onchange_l10n_bg_customs_invoice_ids(self):
for invoice_id in (self.l10n_bg_customs_invoice_ids - self.l10n_bg_customs_invoice_id):
if self.invoice_line_ids.filtered(lambda r: r.l10n_bg_customs_invoice_id == invoice_id):
continue
map_id = invoice_id.fiscal_position_id.map_type(invoice_id)
self.invoice_line_ids = self.l10n_bg_customs_id._customs_aml(invoice_id, self, map_id)

# -------------------------------------------------------------------------
# HELPER METHODS
# -------------------------------------------------------------------------
Expand Down
25 changes: 18 additions & 7 deletions l10n_bg_tax_admin/models/account_move_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,44 +7,55 @@
class AccountMoveLine(models.Model):
_inherit = "account.move.line"

# --------------
# CUSTOMS FIELDS
# --------------

l10n_bg_customs_invoice_id = fields.Many2one('account.move',
string='Base invoice in line',
check_company=True,
copy=False,
states={'draft': [('readonly', True)]},
)

# === Price fields company currency === #
price_unit_signed = fields.Float(
string='Unit Price in company currency',
compute="_compute_price_unit_signed", store=True, readonly=False, precompute=True,
compute="_compute_price_unit_signed",
digits='Product Price',
)
price_subtotal_signed = fields.Monetary(
string='Subtotal in company currency',
compute='_compute_totals_signed', store=True,
compute='_compute_totals_signed',
currency_field='company_currency_id',
)
price_total_signed = fields.Monetary(
string='Total in company currency',
compute='_compute_totals_signed', store=True,
compute='_compute_totals_signed',
currency_field='company_currency_id',
)

@api.depends('price_unit', 'move_id.l10n_bg_protocol_invoice_id')
def _compute_price_unit_signed(self):
for line in self:
if line.currency_id == line.company_id.currency_id:
if line.move_id.currency_id == line.move_id.company_id.currency_id:
line.price_unit_signed = line.price_unit
else:
line.price_unit_signed = line.company_id.currency_id.round(line.price_unit / line.currency_rate)
line.price_unit_signed = line.move_id.company_id.currency_id.round(line.price_unit / line.currency_rate)

@api.depends('quantity', 'discount', 'price_unit', 'tax_ids', 'currency_id', 'move_id.l10n_bg_protocol_invoice_id')
def _compute_totals_signed(self):
for line in self:
if line.display_type != 'product':
line.price_total_signed = line.price_subtotal_signed = False
else:
subtotal = line.company_id.currency_id.round(line.amount_currency / line.currency_rate)
subtotal = line.move_id.company_id.currency_id.round(line.amount_currency / line.currency_rate)
# Compute 'price_total_signed'.
if line.tax_ids:
taxes_res = line.tax_ids.compute_all(
subtotal,
quantity=1.0,
currency=line.currency_id,
currency=line.move_id.company_id.currency_id,
product=line.product_id,
partner=line.partner_id,
is_refund=line.is_refund,
Expand Down
25 changes: 13 additions & 12 deletions l10n_bg_tax_admin/models/account_tax.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def _prepare_tax_totals_signed(self, base_lines, currency, tax_lines=None):
"""

# ==== Compute the taxes ====

company_currency = self.env.company.currency_id
to_process = []
for base_line in base_lines:
to_update_vals, tax_values_list = self._compute_taxes_for_single_line(base_line)
Expand All @@ -73,7 +73,8 @@ def grouping_key_generator(base_line, tax_values):
'base_amount': tax_detail['base_amount'],
'tax_amount': tax_detail['tax_amount'],
}
rate = tax_detail['tax_amount'] / tax_detail['tax_amount_currency']
tax_amount_currency = tax_detail['tax_amount_currency'] != 0.0 and tax_detail['tax_amount_currency'] or 1.0
rate = tax_detail['tax_amount'] / tax_amount_currency

# Handle a manual edition of tax lines.
if tax_lines is not None:
Expand All @@ -86,7 +87,7 @@ def grouping_key_generator(base_line, tax_values):
tax_amount = tax_amount_signed = 0.0
for matched_tax_line in matched_tax_lines:
tax_amount += matched_tax_line['tax_amount']
if currency != self.company_id.currency_id:
if currency != company_currency:
tax_amount_signed += matched_tax_line['tax_amount'] * rate
else:
tax_amount_signed += matched_tax_line['tax_amount']
Expand Down Expand Up @@ -121,9 +122,9 @@ def grouping_key_generator(base_line, tax_values):
'tax_group_amount': tax_group_vals['tax_amount'],
'tax_group_base_amount': tax_group_vals['base_amount'],
'formatted_tax_group_amount': formatLang(self.env, tax_group_vals['tax_amount'],
currency_obj=self.company_id.currency_id),
currency_obj=company_currency),
'formatted_tax_group_base_amount': formatLang(self.env, tax_group_vals['base_amount'],
currency_obj=self.company_id.currency_id),
currency_obj=company_currency),
})

# ==== Build the final result ====
Expand All @@ -135,22 +136,22 @@ def grouping_key_generator(base_line, tax_values):
'name': subtotal_title,
'amount': amount_total,
'formatted_amount': formatLang(self.env, amount_total,
currency_obj=self.company_id.currency_id),
currency_obj=company_currency),
})
for groups_by_subtotal_line in groups_by_subtotal[subtotal_title]:
amount_tax += groups_by_subtotal_line['tax_group_amount']

amount_total = amount_untaxed + amount_tax

display_tax_base = (len(global_tax_details['tax_details']) == 1 and self.company_id.currency_id.compare_amounts(tax_group_vals_list[0]['base_amount'], amount_untaxed) != 0)\
display_tax_base = (len(global_tax_details['tax_details']) == 1 and company_currency.compare_amounts(tax_group_vals_list[0]['base_amount'], amount_untaxed) != 0)\
or len(global_tax_details['tax_details']) > 1
display_tax_base_signed = currency != self.company_id.currency_id
display_tax_base_signed = currency != company_currency

return {
'amount_untaxed': self.company_id.currency_id.round(amount_untaxed),
'amount_total': self.company_id.currency_id.round(amount_total),
'formatted_amount_total': formatLang(self.env, amount_total, currency_obj=self.company_id.currency_id),
'formatted_amount_untaxed': formatLang(self.env, amount_untaxed, currency_obj=self.company_id.currency_id),
'amount_untaxed': company_currency.round(amount_untaxed),
'amount_total': company_currency.round(amount_total),
'formatted_amount_total': formatLang(self.env, amount_total, currency_obj=company_currency),
'formatted_amount_untaxed': formatLang(self.env, amount_untaxed, currency_obj=company_currency),
'groups_by_subtotal': groups_by_subtotal,
'subtotals': subtotals,
'subtotals_order': sorted(subtotal_order.keys(), key=lambda k: subtotal_order[k]),
Expand Down
32 changes: 10 additions & 22 deletions l10n_bg_tax_admin/models/l10n_bg_customs_account_move.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,33 +28,21 @@ class AccountMoveBgCustoms(models.Model):
tracking=True,
index='trigram',
)
l10n_bg_customs_invoice_ids = fields.Many2many('account.move',
'customs_invoices_rel',
'invoice_id',
'customs_id',
string='Used invoices in customs',
check_company=True,
copy=False,
readonly=True,
states={'draft': [('readonly', False)]},
)

def _customs_aml(self, invoice_id, new_entry_id, map_id, partner_id):
@api.onchange('customs_name')
def _onchange_customs_name(self):
if self.customs_name:
self.move_id.l10n_bg_name = self.customs_name

def _customs_aml(self, invoice_id, new_entry_id, map_id):
# Create new account moves
partner_id = partner_id or self.partner_id
partner_account_id = self.env['account.account']._get_most_frequent_account_for_partner(
company_id=self.company_id.id,
partner_id=partner_id.id,
move_type=invoice_id.move_type,
)
partner_account_id = self.env['account.account'].browse(partner_account_id)
base_lines = invoice_id.invoice_line_ids.filtered(lambda r: r.display_type == 'product')
amount_currency_total = 0.0
factor_percent = map_id.factor_percent == 0.0 and 100.0 or map_id.factor_percent
for line in base_lines:
amount_currency_total += line.amount_currency
amount_currency_total *= factor_percent / 100
account_id = map_id.account_id and map_id.account_id or partner_account_id
account_id = map_id.account_id and map_id.account_id or invoice_id.company_id.account_journal_suspense_account_id
tax_ids = account_id.tax_ids.filtered(lambda tax: tax.type_tax_use == 'purchase')
if not tax_ids:
tax_ids = invoice_id.company_id.account_purchase_tax_id
Expand All @@ -63,18 +51,18 @@ def _customs_aml(self, invoice_id, new_entry_id, map_id, partner_id):
aml_vals_list = [Command.create({
'display_type': 'product',
'account_id': account_id.id,
'partner_id': partner_id.id,
'partner_id': new_entry_id.partner_id.id,
'currency_id': invoice_id.currency_id.id,
'amount_currency': amount_currency_total,
'balance': amount_currency_total * invoice_id.l10n_bg_currency_rate,
'l10n_bg_customs_invoice_id': invoice_id.id,
'tax_ids': [Command.set(tax_ids.ids)],
})]
return aml_vals_list

def _customs_vals(self, move_id):
return {
'move_id': move_id.id,
'customs_name': 'BG',
'customs_name': move_id.l10n_bg_name,
'customs_date': move_id.invoice_date,
'l10n_bg_customs_invoice_ids': [Command.set(move_id.ids)]
}
Loading

0 comments on commit 951c9d0

Please sign in to comment.