Skip to content

Commit

Permalink
[REF+IMP] l10n_br_sale_stock: Using Common from l10n_br_stock_account…
Browse files Browse the repository at this point in the history
… to reduce and avoid duplicate code and included test for case without Fiscal Operation.
  • Loading branch information
mbcosta committed Jun 28, 2024
1 parent 056fdff commit a8b843d
Showing 1 changed file with 76 additions and 93 deletions.
169 changes: 76 additions & 93 deletions l10n_br_sale_stock/tests/test_sale_stock.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,118 +7,51 @@
# https://github.com/OCA/account-invoicing/blob/16.0/
# stock_picking_invoicing/tests/common.py
from odoo import exceptions
from odoo.tests import Form, SavepointCase, tagged
from odoo.tests import Form, tagged

from odoo.addons.l10n_br_stock_account.tests.common import TestBrPickingInvoicingCommon


@tagged("post_install", "-at_install")
class TestSaleStock(SavepointCase):
class TestSaleStock(TestBrPickingInvoicingCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.invoice_model = cls.env["account.move"]
cls.invoice_wizard = cls.env["stock.invoice.onshipping"]
cls.stock_return_picking = cls.env["stock.return.picking"]
cls.stock_picking = cls.env["stock.picking"]

# TODO: Em uma instalção direta do modulo
# $ odoo -d test -i l10n_br_sale_stock --stop-after-init
# e depois
# $ odoo -d test --update=l10n_br_sale_stock --test-enable
# o campo do Diário não está vindo preenchido a solução e forçar
# preenchimento para não ter erro nos testes porem no caso dos dados
# demo ao testar na tela vai continuar o problema, para evita-lo é
# preciso instalar o l10n_br_account antes ou preencher manualmente,
# porém isso é um problema já que a instalação direta do modulo deve
# funcionar sem isso.
# No modulo l10n_br_sale para resolver esse problema é feito isso
# https://github.com/OCA/l10n-brazil/blob/12.0/l10n_br_sale/
# hooks.py#L35 e https://github.com/OCA/l10n-brazil/blob/12.0/
# l10n_br_sale/demo/fiscal_operation_simple.xml#L10 mas por algum
# motivo não vem carregado aqui, mesmo tendo o l10n_br_sale como
# dependencia.
cls.fiscal_operation_venda = cls.env.ref("l10n_br_fiscal.fo_venda")
cls.fiscal_operation_dev_venda = cls.env.ref(
"l10n_br_fiscal.fo_devolucao_venda"
)

cls.company_lucro_presumido = cls.env.ref(
"l10n_br_base.empresa_lucro_presumido"
)

# Problem in sale_stock_picking_invoicing
# In order to avoid errors in the tests CI environment when the tests
# Create of Invoice by Sale Order using sale.advance.payment.inv object
# is necessary let default policy as sale_order, just affect demo data.
# TODO: Is there other form to avoid this problem?
cls.companies = cls.env["res.company"].search(
# cls.companies = cls.env["res.company"].search(
# [("sale_invoicing_policy", "=", "sale_order")]
# )
# for company in cls.companies:
# company.sale_invoicing_policy = "stock_picking"

def set_sale_invoicing_policy(self):
# Isso deveria estar sendo feito no setupUpClass mas retorna erro:
# l10n_br_sale_stock/tests/test_sale_stock.py", line 53, in setUpClass
# cls.companies = cls.env["res.company"].search(
# AttributeError: type object 'TestSaleStock' has no attribute 'env'
# TODO: Parece que faltou algo no l10n_br_stock_account/tests/common.py
# para que seja possível fazer alterações no setupUpClass sem ocorrer
# erro, o problema hoje estão sendo contornado por esse metodo que precisa
# ser chamado em cada um dos testes para evitar erro.
self.companies = self.env["res.company"].search(
[("sale_invoicing_policy", "=", "sale_order")]
)
for company in cls.companies:
for company in self.companies:
company.sale_invoicing_policy = "stock_picking"

def _run_picking_onchanges(self, record):
record.onchange_picking_type()
record.onchange_partner_id()

def _run_line_onchanges(self, record):
record.onchange_product()
record.onchange_product_uom()

def picking_move_state(self, picking):
self._run_picking_onchanges(picking)
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
self._run_line_onchanges(move)
move.quantity_done = move.product_uom_qty
picking.button_validate()

def create_invoice_wizard(self, pickings):
wizard_obj = self.env["stock.invoice.onshipping"].with_context(
active_ids=pickings.ids,
active_model=pickings._name,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
# One invoice per partner but group products
wizard_values.update({"group": "partner_product"})
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "in", pickings.ids)]
invoice = self.env["account.move"].search(domain)
return invoice

def return_picking_wizard(self, picking):
# Return Picking
return_wizard_form = Form(
self.env["stock.return.picking"].with_context(
**dict(active_id=picking.id, active_model="stock.picking")
)
)
return_wizard_form.invoice_state = "2binvoiced"
self.return_wizard = return_wizard_form.save()

result_wizard = self.return_wizard.create_returns()
self.assertTrue(result_wizard, "Create returns wizard fail.")
picking_devolution = self.env["stock.picking"].browse(
result_wizard.get("res_id")
)
return picking_devolution

def _change_user_company(self, company):
self.env.user.company_ids += company
self.env.user.company_id = company

def test_02_sale_stock_return(self):
"""
Test a SO with a product invoiced on delivery. Deliver and invoice
the SO, then do a return
of the picking. Check that a refund invoice is well generated.
"""
# intial so
self.set_sale_invoicing_policy()
self.partner = self.env.ref("l10n_br_base.res_partner_address_ak2")
self.product = self.env.ref("product.product_delivery_01")
so_vals = {
Expand Down Expand Up @@ -224,7 +157,7 @@ def test_picking_sale_order_product_and_service(self):
"""
Test Sale Order with product and service
"""

self.set_sale_invoicing_policy()
sale_order_2 = self.env.ref("l10n_br_sale_stock.main_company-sale_order_2")
sale_order_2.action_confirm()
# Metodo de criação da fatura a partir do sale.order
Expand Down Expand Up @@ -330,6 +263,22 @@ def test_picking_sale_order_product_and_service(self):
# Field additional_data failed to transfer from
# sale.order.line to account.move.line
"additional_data",
# Ao chamar o _onchange_product_id_fiscal no stock.move o
# partner_id usado no mapeamento é o do objeto, nesse teste
# 'Akretion Aluminio - SP' por ser o Endereço de Entrega
# partner_shipping_id, porém esse não é o partner_invoice_id
# 'Akretion Sao Paulo' essa diferença ocasiona diferentes
# 'Linhas de Operações Fiscal'/fiscal_operation_line_id entre:
# Objeto | Linha de Operações Fiscal
# _______________________________|____________________________
# sale.order.line | 'Revenda não Contribuinte'
# stock.move e account.move.line | 'Revenda'
# TODO: O mapeamento da 'Linha de Operações Fiscal' precisa
# considerar os casos onde o partner_id do objeto não é o
# partner_invoice_id. Por enquanto o campo não está sendo validado
# para evitar erros aqui já que isso precisa ser resolvido em outro
# modulo ou talvez aqui porém seria apenas uma correção temporaria.
"fiscal_operation_line_id",
]

common_fields = list(set(acl_fields) & set(sol_fields) - set(skipped_fields))
Expand Down Expand Up @@ -388,6 +337,7 @@ def test_picking_invoicing_partner_shipping_invoiced(self):
picking and 3 moves per picking, but Partner to Shipping is
different from Partner to Invoice.
"""
self.set_sale_invoicing_policy()
sale_order_1 = self.env.ref("l10n_br_sale_stock.main_company-sale_order_1")
sale_order_1.action_confirm()
picking = sale_order_1.picking_ids
Expand Down Expand Up @@ -443,7 +393,7 @@ def test_ungrouping_pickings_partner_shipping_different(self):
picking and 3 moves per picking, the 3 has the same Partner to
Invoice but one has Partner to Shipping so shouldn't be grouping.
"""

self.set_sale_invoicing_policy()
sale_order_1 = self.env.ref("l10n_br_sale_stock.main_company-sale_order_1")
sale_order_1.action_confirm()
picking = sale_order_1.picking_ids
Expand Down Expand Up @@ -496,6 +446,7 @@ def test_synchronize_sale_partner_shipping_in_stock_picking(self):
"""
Test the synchronize Sale Partner Shipping in Stock Picking
"""
self.set_sale_invoicing_policy()
sale_order_1 = self.env.ref("l10n_br_sale_stock.main_company-sale_order_1")
sale_order_1.action_confirm()
picking = sale_order_1.picking_ids
Expand All @@ -509,7 +460,8 @@ def test_lucro_presumido_company(self):
"""
Test Lucro Presumido Company
"""
self._change_user_company(self.company_lucro_presumido)
self._change_user_company(self.env.ref("l10n_br_base.empresa_lucro_presumido"))
self.set_sale_invoicing_policy()
sale_order_1 = self.env.ref("l10n_br_sale_stock.lucro_presumido-sale_order_1")
sale_order_1.action_confirm()
picking = sale_order_1.picking_ids
Expand Down Expand Up @@ -544,7 +496,13 @@ def test_lucro_presumido_company(self):
# preenche um valor para evitar o erro.
if hasattr(invoice, "payment_mode_id"):
payment_modes = self.env["account.payment.mode"].search(
[("company_id", "=", self.company_lucro_presumido.id)]
[
(
"company_id",
"=",
self.env.ref("l10n_br_base.empresa_lucro_presumido").id,
)
]
)
payment_mode = payment_modes[0]
payment_mode.fiscal_payment_mode = "15"
Expand All @@ -554,6 +512,7 @@ def test_lucro_presumido_company(self):

def test_down_payment(self):
"""Test the case with Down Payment"""
self.set_sale_invoicing_policy()
sale_order_1 = self.env.ref("l10n_br_sale_stock.main_company-sale_order_1")
sale_order_1.action_confirm()
# Create Invoice Sale
Expand Down Expand Up @@ -627,3 +586,27 @@ def test_down_payment(self):
)
assert down_payment_line, "Invoice without Down Payment line."
invoice.action_post()

def test_compatible_with_international_case(self):
"""Test of compatible with international case or without Fiscal Operation,
create Invoice but not for Brazil."""
self.set_sale_invoicing_policy()
so_international = self.env.ref("sale.sale_order_3")
so_international.fiscal_operation_id = False
so_international.action_confirm()
picking = so_international.picking_ids
self.picking_move_state(picking)
invoice = self.create_invoice_wizard(picking)
invoice.action_post()
# Caso Internacional não deve ter Documento Fiscal associado
self.assertFalse(
invoice.fiscal_document_id,
"International case should not has Fiscal Document.",
)
# Teste Retorno
picking_devolution = self.return_picking_wizard(picking)
invoice_devolution = self.create_invoice_wizard(picking_devolution)
self.assertFalse(
invoice_devolution.fiscal_document_id,
"International case should not has Fiscal Document.",
)

0 comments on commit a8b843d

Please sign in to comment.