size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
1,576
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Sale Product Configurator", 'version': '1.0', 'category': 'Hidden', 'summary': "Configure your products", 'description': """ Technical module installed when the user checks the "module_sale_product_configurator" setting. The main purpose is to override the sale_order view to allow configuring products in the SO form. It also enables the "optional products" feature. """, 'depends': ['sale'], 'data': [ 'security/ir.model.access.csv', 'views/templates.xml', 'views/sale_views.xml', 'wizard/sale_product_configurator_views.xml', ], 'demo': [ 'data/sale_demo.xml', ], 'assets': { 'web.assets_backend': [ 'sale/static/src/js/variant_mixin.js', 'sale_product_configurator/static/src/js/product_configurator_renderer.js', 'sale_product_configurator/static/src/js/product_configurator_controller.js', 'sale_product_configurator/static/src/js/product_configurator_view.js', 'sale_product_configurator/static/src/js/product_configurator_widget.js', 'sale_product_configurator/static/src/js/product_configurator_modal.js', ], 'web.assets_tests': [ 'sale_product_configurator/static/tests/tours/**/*', ], 'web.qunit_suite_tests': [ 'sale_product_configurator/static/tests/product_configurator.test.js', ], }, 'license': 'LGPL-3', }
36.651163
1,576
7,565
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests from .common import TestProductConfiguratorCommon @odoo.tests.tagged('post_install', '-at_install', 'kzh') class TestUi(odoo.tests.HttpCase, TestProductConfiguratorCommon): def setUp(self): super(TestUi, self).setUp() self.custom_pricelist = self.env['product.pricelist'].create({ 'name': 'Custom pricelist (TEST)', 'item_ids': [(0, 0, { 'base': 'list_price', 'applied_on': '1_product', 'product_tmpl_id': self.product_product_custo_desk.id, 'price_discount': 20, 'min_quantity': 2, 'compute_price': 'formula' })] }) def test_01_product_configurator(self): # To be able to test the product configurator, admin user must have access to "variants" feature, so we give him the right group for that self.env.ref('base.user_admin').write({'groups_id': [(4, self.env.ref('product.group_product_variant').id)]}) self.start_tour("/web", 'sale_product_configurator_tour', login="admin") def test_02_product_configurator_advanced(self): # group_product_variant: use the product configurator # group_sale_pricelist: display the pricelist to determine when it is changed after choosing # group_delivery_invoice_address: show the shipping address (needed for a trigger) # the partner self.env.ref('base.user_admin').write({ 'groups_id': [ (4, self.env.ref('product.group_product_variant').id), (4, self.env.ref('product.group_product_pricelist').id), (4, self.env.ref('sale.group_delivery_invoice_address').id), ], }) # Prepare relevant test data # This is not included in demo data to avoid useless noise product_attributes = self.env['product.attribute'].create([{ 'name': 'PA1', 'display_type': 'radio', 'create_variant': 'dynamic' }, { 'name': 'PA2', 'display_type': 'radio', 'create_variant': 'always' }, { 'name': 'PA3', 'display_type': 'radio', 'create_variant': 'dynamic' }, { 'name': 'PA4', 'display_type': 'select', 'create_variant': 'no_variant' }, { 'name': 'PA5', 'display_type': 'select', 'create_variant': 'no_variant' }, { 'name': 'PA7', 'display_type': 'color', 'create_variant': 'no_variant' }, { 'name': 'PA8', 'display_type': 'radio', 'create_variant': 'no_variant' }]) self.env['product.attribute.value'].create([{ 'name': 'PAV' + str(i), 'is_custom': i == 9, 'attribute_id': product_attribute.id } for i in range(1, 11) for product_attribute in product_attributes]) product_template = self.product_product_custo_desk self.env['product.template.attribute.line'].create([{ 'attribute_id': product_attribute.id, 'product_tmpl_id': product_template.id, 'value_ids': [(6, 0, product_attribute.value_ids.ids)], } for product_attribute in product_attributes]) self.start_tour("/web", 'sale_product_configurator_advanced_tour', login="admin") def test_03_product_configurator_edition(self): # To be able to test the product configurator, admin user must have access to "variants" feature, so we give him the right group for that self.env.ref('base.user_admin').write({'groups_id': [(4, self.env.ref('product.group_product_variant').id)]}) self.start_tour("/web", 'sale_product_configurator_edition_tour', login="admin") def test_04_product_configurator_single_custom_value(self): # group_product_variant: use the product configurator # group_sale_pricelist: display the pricelist to determine when it is changed after choosing # the partner self.env.ref('base.user_admin').write({ 'groups_id': [ (4, self.env.ref('product.group_product_variant').id), (4, self.env.ref('product.group_product_pricelist').id), ], }) # Prepare relevant test data # This is not included in demo data to avoid useless noise product_attributes = self.env['product.attribute'].create([{ 'name': 'product attribute', 'display_type': 'radio', 'create_variant': 'always' }]) product_attribute_values = self.env['product.attribute.value'].create([{ 'name': 'single product attribute value', 'is_custom': True, 'attribute_id': product_attributes[0].id }]) product_template = self.product_product_custo_desk self.env['product.template.attribute.line'].create([{ 'attribute_id': product_attributes[0].id, 'product_tmpl_id': product_template.id, 'value_ids': [(6, 0, [product_attribute_values[0].id])] }]) self.start_tour("/web", 'sale_product_configurator_single_custom_attribute_tour', login="admin") def test_05_product_configurator_pricelist(self): """The goal of this test is to make sure pricelist rules are correctly applied on the backend product configurator. Also testing B2C setting: no impact on the backend configurator. """ admin = self.env.ref('base.user_admin') # Activate B2C self.env.ref('account.group_show_line_subtotals_tax_excluded').users -= admin self.env.ref('account.group_show_line_subtotals_tax_included').users |= admin # Active pricelist on SO self.env.ref('product.group_product_pricelist').users |= admin # Add a 15% tax on desk tax = self.env['account.tax'].create({'name': "Test tax", 'amount': 15}) self.product_product_custo_desk.taxes_id = tax # Remove tax from Conference Chair and Chair floor protection self.product_product_conf_chair.taxes_id = None self.product_product_conf_chair_floor_protect.taxes_id = None self.start_tour("/web", 'sale_product_configurator_pricelist_tour', login="admin") def test_06_product_configurator_optional_products(self): """The goal of this test is to check that the product configurator window opens correctly and lets you select optional products even if the main product does not have variants. """ # add an optional product to the office chair and the custo desk for testing purposes office_chair = self.env['product.product'].create({ 'name': 'Office Chair Black', }) custo_desk = self.product_product_custo_desk.product_variant_ids[0] office_chair.update({ 'optional_product_ids': [(6, 0, [self.product_product_conf_chair_floor_protect.id])] }) custo_desk.update({ 'optional_product_ids': [(6, 0, [office_chair.product_tmpl_id.id, self.product_product_conf_chair.id])] }) self.product_product_custo_desk.optional_product_ids = [(4, self.product_product_conf_chair.id)] self.start_tour("/web", 'sale_product_configurator_optional_products_tour', login="admin")
44.239766
7,565
4,895
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 from odoo.tests.common import TransactionCase from odoo.modules.module import get_module_resource class TestProductConfiguratorCommon(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Setup attributes and attributes values cls.product_attribute_1 = cls.env['product.attribute'].create({ 'name': 'Legs', 'sequence': 10, }) product_attribute_value_1 = cls.env['product.attribute.value'].create({ 'name': 'Steel', 'attribute_id': cls.product_attribute_1.id, 'sequence': 1, }) product_attribute_value_2 = cls.env['product.attribute.value'].create({ 'name': 'Aluminium', 'attribute_id': cls.product_attribute_1.id, 'sequence': 2, }) product_attribute_2 = cls.env['product.attribute'].create({ 'name': 'Color', 'sequence': 20, }) product_attribute_value_3 = cls.env['product.attribute.value'].create({ 'name': 'White', 'attribute_id': product_attribute_2.id, 'sequence': 1, }) product_attribute_value_4 = cls.env['product.attribute.value'].create({ 'name': 'Black', 'attribute_id': product_attribute_2.id, 'sequence': 2, }) # Create product template cls.product_product_custo_desk = cls.env['product.template'].create({ 'name': 'Customizable Desk (TEST)', 'standard_price': 500.0, 'list_price': 750.0, }) # Generate variants cls.env['product.template.attribute.line'].create([{ 'product_tmpl_id': cls.product_product_custo_desk.id, 'attribute_id': cls.product_attribute_1.id, 'value_ids': [(4, product_attribute_value_1.id), (4, product_attribute_value_2.id)], }, { 'product_tmpl_id': cls.product_product_custo_desk.id, 'attribute_id': product_attribute_2.id, 'value_ids': [(4, product_attribute_value_3.id), (4, product_attribute_value_4.id)], }]) # Apply a price_extra for the attribute Aluminium cls.product_product_custo_desk.attribute_line_ids[0].product_template_value_ids[1].price_extra = 50.40 # Add a Custom attribute product_attribute_value_custom = cls.env['product.attribute.value'].create({ 'name': 'Custom', 'attribute_id': cls.product_attribute_1.id, 'sequence': 3, 'is_custom': True }) cls.product_product_custo_desk.attribute_line_ids[0].write({'value_ids': [(4, product_attribute_value_custom.id)]}) # Disable the aluminium + black product cls.product_product_custo_desk.product_variant_ids[3].active = False # Setup a first optional product img_path = get_module_resource('product', 'static', 'img', 'product_product_11-image.png') img_content = base64.b64encode(open(img_path, "rb").read()) cls.product_product_conf_chair = cls.env['product.template'].create({ 'name': 'Conference Chair (TEST)', 'image_1920': img_content, 'list_price': 16.50, }) cls.env['product.template.attribute.line'].create({ 'product_tmpl_id': cls.product_product_conf_chair.id, 'attribute_id': cls.product_attribute_1.id, 'value_ids': [(4, product_attribute_value_1.id), (4, product_attribute_value_2.id)], }) cls.product_product_conf_chair.attribute_line_ids[0].product_template_value_ids[1].price_extra = 6.40 cls.product_product_custo_desk.optional_product_ids = [(4, cls.product_product_conf_chair.id)] # Setup a second optional product cls.product_product_conf_chair_floor_protect = cls.env['product.template'].create({ 'name': 'Chair floor protection', 'list_price': 12.0, }) cls.product_product_conf_chair.optional_product_ids = [(4, cls.product_product_conf_chair_floor_protect.id)] def _create_pricelist(cls, pricelists): for pricelist in pricelists: if not pricelist.item_ids.filtered(lambda i: i.product_tmpl_id == cls.product_product_custo_desk and i.price_discount == 20): cls.env['product.pricelist.item'].create({ 'base': 'list_price', 'applied_on': '1_product', 'pricelist_id': pricelist.id, 'product_tmpl_id': cls.product_product_custo_desk.id, 'price_discount': 20, 'min_quantity': 2, 'compute_price': 'formula', }) pricelist.discount_policy = 'without_discount'
42.938596
4,895
1,155
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class SaleProductConfigurator(models.TransientModel): _name = 'sale.product.configurator' _description = 'Sale Product Configurator' product_template_id = fields.Many2one( 'product.template', string="Product", required=True, domain=[('sale_ok', '=', True), ('attribute_line_ids.value_ids', '!=', False)]) quantity = fields.Integer('Quantity') pricelist_id = fields.Many2one('product.pricelist', 'Pricelist', readonly=True) product_template_attribute_value_ids = fields.Many2many( 'product.template.attribute.value', 'product_configurator_template_attribute_value_rel', string='Attribute Values', readonly=True) product_custom_attribute_value_ids = fields.Many2many( 'product.attribute.custom.value', 'product_configurator_custom_attribute_value_rel', string="Custom Values") product_no_variant_attribute_value_ids = fields.Many2many( 'product.template.attribute.value', 'product_configurator_no_variant_attribute_value_rel', string="Extra Values")
55
1,155
473
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" is_configurable_product = fields.Boolean('Is the product configurable?', related="product_template_id.has_configurable_attributes") product_template_attribute_value_ids = fields.Many2many(related='product_id.product_template_attribute_value_ids', readonly=True)
43
473
2,305
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api class ProductTemplate(models.Model): _inherit = 'product.template' _check_company_auto = True optional_product_ids = fields.Many2many( 'product.template', 'product_optional_rel', 'src_id', 'dest_id', string='Optional Products', help="Optional Products are suggested " "whenever the customer hits *Add to Cart* (cross-sell strategy, " "e.g. for computers: warranty, software, etc.).", check_company=True) @api.depends('attribute_line_ids.value_ids.is_custom', 'attribute_line_ids.attribute_id.create_variant') def _compute_has_configurable_attributes(self): """ A product is considered configurable if: - It has dynamic attributes - It has any attribute line with at least 2 attribute values configured - It has at least one custom attribute value """ for product in self: product.has_configurable_attributes = any(attribute.create_variant == 'dynamic' for attribute in product.mapped('attribute_line_ids.attribute_id')) \ or any(len(attribute_line_id.value_ids) >= 2 for attribute_line_id in product.attribute_line_ids) \ or any(attribute_value.is_custom for attribute_value in product.mapped('attribute_line_ids.value_ids')) def get_single_product_variant(self): """ Method used by the product configurator to check if the product is configurable or not. We need to open the product configurator if the product: - is configurable (see has_configurable_attributes) - has optional products """ self.ensure_one() res = super(ProductTemplate, self).get_single_product_variant() if res.get('product_id', False): has_optional_products = False for optional_product in self.product_variant_id.optional_product_ids: if optional_product.has_dynamic_attributes() or optional_product._get_possible_variants(self.product_variant_id.product_template_attribute_value_ids): has_optional_products = True break res.update({'has_optional_products': has_optional_products}) return res
53.604651
2,305
4,306
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http from odoo.http import request class ProductConfiguratorController(http.Controller): @http.route(['/sale_product_configurator/configure'], type='json', auth="user", methods=['POST']) def configure(self, product_template_id, pricelist_id, **kw): add_qty = float(kw.get('add_qty', 1)) product_template = request.env['product.template'].browse(int(product_template_id)) pricelist = self._get_pricelist(pricelist_id) product_combination = False attribute_value_ids = set(kw.get('product_template_attribute_value_ids', [])) attribute_value_ids |= set(kw.get('product_no_variant_attribute_value_ids', [])) if attribute_value_ids: product_combination = request.env['product.template.attribute.value'].browse(attribute_value_ids) if pricelist: product_template = product_template.with_context(pricelist=pricelist.id, partner=request.env.user.partner_id) return request.env['ir.ui.view']._render_template("sale_product_configurator.configure", { 'product': product_template, 'pricelist': pricelist, 'add_qty': add_qty, 'product_combination': product_combination }) @http.route(['/sale_product_configurator/show_advanced_configurator'], type='json', auth="user", methods=['POST']) def show_advanced_configurator(self, product_id, variant_values, pricelist_id, **kw): pricelist = self._get_pricelist(pricelist_id) return self._show_advanced_configurator(product_id, variant_values, pricelist, False, **kw) @http.route(['/sale_product_configurator/optional_product_items'], type='json', auth="user", methods=['POST']) def optional_product_items(self, product_id, pricelist_id, **kw): pricelist = self._get_pricelist(pricelist_id) return self._optional_product_items(product_id, pricelist, **kw) def _optional_product_items(self, product_id, pricelist, **kw): add_qty = float(kw.get('add_qty', 1)) product = request.env['product.product'].browse(int(product_id)) parent_combination = product.product_template_attribute_value_ids if product.env.context.get('no_variant_attribute_values'): # Add "no_variant" attribute values' exclusions # They are kept in the context since they are not linked to this product variant parent_combination |= product.env.context.get('no_variant_attribute_values') return request.env['ir.ui.view']._render_template("sale_product_configurator.optional_product_items", { 'product': product, 'parent_name': product.name, 'parent_combination': parent_combination, 'pricelist': pricelist, 'add_qty': add_qty, }) def _show_advanced_configurator(self, product_id, variant_values, pricelist, handle_stock, **kw): product = request.env['product.product'].browse(int(product_id)) combination = request.env['product.template.attribute.value'].browse(variant_values) add_qty = float(kw.get('add_qty', 1)) no_variant_attribute_values = combination.filtered( lambda product_template_attribute_value: product_template_attribute_value.attribute_id.create_variant == 'no_variant' ) if no_variant_attribute_values: product = product.with_context(no_variant_attribute_values=no_variant_attribute_values) return request.env['ir.ui.view']._render_template("sale_product_configurator.optional_products_modal", { 'product': product, 'combination': combination, 'add_qty': add_qty, 'parent_name': product.name, 'variant_values': variant_values, 'pricelist': pricelist, 'handle_stock': handle_stock, 'already_configured': kw.get("already_configured", False), 'no_attribute': kw.get('no_attribute', False), 'custom_attribute': kw.get('custom_attribute', False) }) def _get_pricelist(self, pricelist_id, pricelist_fallback=False): return request.env['product.pricelist'].browse(int(pricelist_id or 0))
51.261905
4,306
691
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Indian - Point of Sale', 'icon': '/l10n_in/static/description/icon.png', 'version': '1.0', 'description': """GST Point of Sale""", 'category': 'Accounting/Localizations/Point of Sale', 'depends': [ 'l10n_in', 'point_of_sale' ], 'demo': [ 'data/product_demo.xml', ], 'auto_install': True, 'assets': { 'point_of_sale.assets': [ 'l10n_in_pos/static/src/js/**/*', ], 'web.assets_qweb': [ 'l10n_in_pos/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
25.592593
691
1,871
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class PosOrder(models.Model): _inherit = 'pos.order' #TODO: remove in master @api.model def _get_account_move_line_group_data_type_key(self, data_type, values, options={}): res = super(PosOrder, self)._get_account_move_line_group_data_type_key(data_type, values, options) if data_type == 'tax' and res: if self.env['account.tax'].browse(values['tax_line_id']).company_id.account_fiscal_country_id.code == 'IN': return res + (values['product_uom_id'], values['product_id']) return res #TODO: remove in master def _prepare_account_move_line(self, line, partner_id, current_company, currency_id, rounding_method): res = super(PosOrder, self)._prepare_account_move_line(line, partner_id, current_company, currency_id, rounding_method) for line_values in res: if line_values.get('data_type') in ['tax','product']: line_values['values'].update({ 'product_id': line.product_id.id, 'product_uom_id': line.product_id.uom_id.id }) return res def _prepare_invoice_vals(self): vals = super()._prepare_invoice_vals() if self.session_id.company_id.country_id.code == 'IN': partner = self.partner_id l10n_in_gst_treatment = partner.l10n_in_gst_treatment if not l10n_in_gst_treatment and partner.country_id and partner.country_id.code != 'IN': l10n_in_gst_treatment = 'overseas' if not l10n_in_gst_treatment: l10n_in_gst_treatment = partner.vat and 'regular' or 'consumer' vals['l10n_in_gst_treatment'] = l10n_in_gst_treatment return vals
49.236842
1,871
1,150
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2010 kazacube (http://kazacube.com). { 'name': 'Morocco - Accounting', 'author': 'kazacube', 'category': 'Accounting/Localizations/Account Charts', 'description': """ This is the base module to manage the accounting chart for Morocco. ==================================================================== Ce Module charge le modèle du plan de comptes standard Marocain et permet de générer les états comptables aux normes marocaines (Bilan, CPC (comptes de produits et charges), balance générale à 6 colonnes, Grand livre cumulatif...). L'intégration comptable a été validé avec l'aide du Cabinet d'expertise comptable Seddik au cours du troisième trimestre 2010.""", 'website': 'http://www.kazacube.com', 'depends': ['base', 'account'], 'data': [ 'data/l10n_ma_chart_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_report_data.xml', 'data/account_tax_data.xml', 'data/account_chart_template_data.xml', ], 'license': 'LGPL-3', }
39.241379
1,138
2,628
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Belgium - Accounting', 'version': '2.0', 'category': 'Accounting/Localizations/Account Charts', 'description': """ This is the base module to manage the accounting chart for Belgium in Odoo. ============================================================================== After installing this module, the Configuration wizard for accounting is launched. * We have the account templates which can be helpful to generate Charts of Accounts. * On that particular wizard, you will be asked to pass the name of the company, the chart template to follow, the no. of digits to generate, the code for your account and bank account, currency to create journals. Thus, the pure copy of Chart Template is generated. Wizards provided by this module: -------------------------------- * Partner VAT Intra: Enlist the partners with their related VAT and invoiced amounts. Prepares an XML file format. **Path to access :** Invoicing/Reporting/Legal Reports/Belgium Statements/Partner VAT Intra * Periodical VAT Declaration: Prepares an XML file for Vat Declaration of the Main company of the User currently Logged in. **Path to access :** Invoicing/Reporting/Legal Reports/Belgium Statements/Periodical VAT Declaration * Annual Listing Of VAT-Subjected Customers: Prepares an XML file for Vat Declaration of the Main company of the User currently Logged in Based on Fiscal year. **Path to access :** Invoicing/Reporting/Legal Reports/Belgium Statements/Annual Listing Of VAT-Subjected Customers """, 'author': 'Noviat, Odoo SA', 'depends': [ 'account', 'base_iban', 'base_vat', 'l10n_multilang', ], 'data': [ 'data/account_chart_template_data.xml', 'data/account.account.template.csv', 'data/account_pcmn_belgium_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_report_data.xml', 'data/account_tax_template_data.xml', 'data/l10n_be_sequence_data.xml', 'data/fiscal_templates_data.xml', 'data/account_fiscal_position_tax_template_data.xml', 'data/account_reconcile_model_template.xml', 'data/account.group.template.csv', 'data/account_chart_template_configure_data.xml', 'data/menuitem_data.xml', ], 'demo': [ 'demo/l10n_be_demo.xml', 'demo/demo_company.xml', ], 'post_init_hook': 'load_translations', 'license': 'LGPL-3', }
40.430769
2,628
1,948
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved. import random import re from odoo import api, fields, models, _ from odoo.exceptions import UserError """ account.move object: add support for Belgian structured communication """ class AccountMove(models.Model): _inherit = 'account.move' def _get_invoice_reference_be_partner(self): """ This computes the reference based on the belgian national standard “OGM-VCS”. For instance, if an invoice is issued for the partner with internal reference 'food buyer 654', the digits will be extracted and used as the data. This will lead to a check number equal to 72 and the reference will be '+++000/0000/65472+++'. If no reference is set for the partner, its id in the database will be used. """ self.ensure_one() bbacomm = (re.sub('\D', '', self.partner_id.ref or '') or str(self.partner_id.id))[-10:].rjust(10, '0') base = int(bbacomm) mod = base % 97 or 97 reference = '+++%s/%s/%s%02d+++' % (bbacomm[:3], bbacomm[3:7], bbacomm[7:], mod) return reference def _get_invoice_reference_be_invoice(self): """ This computes the reference based on the belgian national standard “OGM-VCS”. The data of the reference is the database id number of the invoice. For instance, if an invoice is issued with id 654, the check number is 72 so the reference will be '+++000/0000/65472+++'. """ self.ensure_one() base = self.id bbacomm = str(base).rjust(10, '0') base = int(bbacomm) mod = base % 97 or 97 reference = '+++%s/%s/%s%02d+++' % (bbacomm[:3], bbacomm[3:7], bbacomm[7:], mod) return reference
38.8
1,940
382
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class AccountJournal(models.Model): _inherit = 'account.journal' invoice_reference_model = fields.Selection(selection_add=[ ('be', 'Belgium') ], ondelete={'be': lambda recs: recs.write({'invoice_reference_model': 'odoo'})})
34.727273
382
882
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved. from odoo import api, models class ResCompany(models.Model): _inherit = 'res.company' @api.depends('vat', 'country_id') def _compute_company_registry(self): # OVERRIDE # If a belgian company has a VAT number then it's company registry is it's VAT Number (without country code). super(ResCompany, self)._compute_company_registry() for company in self.filtered(lambda comp: comp.country_id.code == 'BE' and comp.vat): vat_country, vat_number = self.env['res.partner']._split_vat(company.vat) if vat_country == 'be' and self.env['res.partner'].simple_vat_check(vat_country, vat_number): company.company_registry = vat_number
44.1
882
670
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields class AccountChartTemplate(models.Model): _inherit = 'account.chart.template' @api.model def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None): journal_data = super(AccountChartTemplate, self)._prepare_all_journals( acc_template_ref, company, journals_dict) for journal in journal_data: if journal['type'] in ('sale', 'purchase') and company.country_id.code == "BE": journal.update({'refund_sequence': True}) return journal_data
39.411765
670
682
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Define Taxes as Python Code", 'summary': "Use python code to define taxes", 'description': """ A tax defined as python code consists of two snippets of python code which are executed in a local environment containing data such as the unit price, product or partner. "Applicable Code" defines if the tax is to be applied. "Python Code" defines the amount of the tax. """, 'category': 'Accounting/Accounting', 'version': '1.0', 'depends': ['account'], 'data': [ 'views/account_tax_views.xml', ], 'license': 'LGPL-3', }
32.47619
682
2,267
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.test_tax import TestTaxCommon from odoo.tests import tagged @tagged('post_install', '-at_install') class TestTaxPython(TestTaxCommon): @classmethod def setUpClass(cls): super(TestTaxPython, cls).setUpClass() cls.python_tax = cls.env['account.tax'].create({ 'name': 'Python TAx', 'amount_type': 'code', 'amount': 0.0, 'python_compute': 'result = ((price_unit * quantity) - ((price_unit * quantity) / 1.12)) * 0.5', 'sequence': 1, }) def test_tax_python_basic(self): res = self.python_tax.compute_all(130.0) self._check_compute_all_results( 136.96, # 'total_included' 130.0, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # -------------------------------------------------- (130.0, 6.96), # | 1 | 6% | t | # -------------------------------------------------- ], res ) def test_tax_python_price_include(self): self.python_tax.price_include = True res = self.python_tax.compute_all(130.0) self._check_compute_all_results( 130, # 'total_included' 123.04, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (123.04, 6.96), # | 1 | 6% | t | # --------------------------------------------------- ], res ) res = (self.python_tax + self.python_tax).compute_all(130.0) self._check_compute_all_results( 130, # 'total_included' 116.07, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (116.07, 6.96), # | 1 | 6% | t | (116.07, 6.97), # | 1 | 6% | t | # --------------------------------------------------- ], res )
37.163934
2,267
5,156
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, _ from odoo.tools.safe_eval import safe_eval from odoo.exceptions import UserError class AccountTaxPython(models.Model): _inherit = "account.tax" amount_type = fields.Selection(selection_add=[ ('code', 'Python Code') ], ondelete={'code': lambda recs: recs.write({'amount_type': 'percent', 'active': False})}) python_compute = fields.Text(string='Python Code', default="result = price_unit * 0.10", help="Compute the amount of the tax by setting the variable 'result'.\n\n" ":param base_amount: float, actual amount on which the tax is applied\n" ":param price_unit: float\n" ":param quantity: float\n" ":param company: res.company recordset singleton\n" ":param product: product.product recordset singleton or None\n" ":param partner: res.partner recordset singleton or None") python_applicable = fields.Text(string='Applicable Code', default="result = True", help="Determine if the tax will be applied by setting the variable 'result' to True or False.\n\n" ":param price_unit: float\n" ":param quantity: float\n" ":param company: res.company recordset singleton\n" ":param product: product.product recordset singleton or None\n" ":param partner: res.partner recordset singleton or None") def _compute_amount(self, base_amount, price_unit, quantity=1.0, product=None, partner=None): self.ensure_one() if product and product._name == 'product.template': product = product.product_variant_id if self.amount_type == 'code': company = self.env.company localdict = {'base_amount': base_amount, 'price_unit':price_unit, 'quantity': quantity, 'product':product, 'partner':partner, 'company': company} try: safe_eval(self.python_compute, localdict, mode="exec", nocopy=True) except Exception as e: raise UserError(_("You entered invalid code %r in %r taxes\n\nError : %s") % (self.python_compute, self.name, e)) from e return localdict['result'] return super(AccountTaxPython, self)._compute_amount(base_amount, price_unit, quantity, product, partner) def compute_all(self, price_unit, currency=None, quantity=1.0, product=None, partner=None, is_refund=False, handle_price_include=True, include_caba_tags=False): taxes = self.filtered(lambda r: r.amount_type != 'code') company = self.env.company if product and product._name == 'product.template': product = product.product_variant_id for tax in self.filtered(lambda r: r.amount_type == 'code'): localdict = self._context.get('tax_computation_context', {}) localdict.update({'price_unit': price_unit, 'quantity': quantity, 'product': product, 'partner': partner, 'company': company}) try: safe_eval(tax.python_applicable, localdict, mode="exec", nocopy=True) except Exception as e: raise UserError(_("You entered invalid code %r in %r taxes\n\nError : %s") % (tax.python_applicable, tax.name, e)) from e if localdict.get('result', False): taxes += tax return super(AccountTaxPython, taxes).compute_all(price_unit, currency, quantity, product, partner, is_refund=is_refund, handle_price_include=handle_price_include, include_caba_tags=include_caba_tags) class AccountTaxTemplatePython(models.Model): _inherit = 'account.tax.template' amount_type = fields.Selection(selection_add=[ ('code', 'Python Code') ], ondelete={'code': 'cascade'}) python_compute = fields.Text(string='Python Code', default="result = price_unit * 0.10", help="Compute the amount of the tax by setting the variable 'result'.\n\n" ":param base_amount: float, actual amount on which the tax is applied\n" ":param price_unit: float\n" ":param quantity: float\n" ":param product: product.product recordset singleton or None\n" ":param partner: res.partner recordset singleton or None") python_applicable = fields.Text(string='Applicable Code', default="result = True", help="Determine if the tax will be applied by setting the variable 'result' to True or False.\n\n" ":param price_unit: float\n" ":param quantity: float\n" ":param product: product.product recordset singleton or None\n" ":param partner: res.partner recordset singleton or None") def _get_tax_vals(self, company, tax_template_to_tax): """ This method generates a dictionnary of all the values for the tax that will be created. """ self.ensure_one() res = super(AccountTaxTemplatePython, self)._get_tax_vals(company, tax_template_to_tax) res['python_compute'] = self.python_compute res['python_applicable'] = self.python_applicable return res
56.659341
5,156
288
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Germany - Sale', 'category': 'Accounting/Localizations', 'depends': [ 'l10n_de', 'sale', ], 'auto_install': True, 'license': 'LGPL-3', }
22.153846
288
2,382
py
PYTHON
15.0
from odoo import models, fields, _ from odoo.tools import format_date class SaleOrder(models.Model): _inherit = 'sale.order' l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data') l10n_de_document_title = fields.Char(compute='_compute_l10n_de_document_title') l10n_de_addresses = fields.Binary(compute='_compute_l10n_de_addresses') def _compute_l10n_de_template_data(self): for record in self: record.l10n_de_template_data = data = [] if record.state in ('draft', 'sent'): if record.name: data.append((_("Quotation No."), record.name)) if record.date_order: data.append((_("Quotation Date"), format_date(self.env, record.date_order))) if record.validity_date: data.append((_("Expiration"), format_date(self.env, record.validity_date))) else: if record.name: data.append((_("Order No."), record.name)) if record.date_order: data.append((_("Order Date"), format_date(self.env, record.date_order))) if record.client_order_ref: data.append((_('Customer Reference'), record.client_order_ref)) if record.user_id: data.append((_("Salesperson"), record.user_id.name)) if 'incoterm' in record._fields and record.incoterm: data.append((_("Incoterm"), record.incoterm.code)) def _compute_l10n_de_document_title(self): for record in self: if self._context.get('proforma'): record.l10n_de_document_title = _('Pro Forma Invoice') elif record.state in ('draft', 'sent'): record.l10n_de_document_title = _('Quotation') else: record.l10n_de_document_title = _('Sales Order') def _compute_l10n_de_addresses(self): for record in self: record.l10n_de_addresses = data = [] if record.partner_shipping_id == record.partner_invoice_id: data.append((_("Invoicing and Shipping Address:"), record.partner_shipping_id)) else: data.append((_("Shipping Address:"), record.partner_shipping_id)) data.append((_("Invoicing Address:"), record.partner_invoice_id))
47.64
2,382
939
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Shopper's Wishlist", 'summary': 'Allow shoppers to enlist products', 'description': """ Allow shoppers of your eCommerce store to create personalized collections of products they want to buy and save them for future reference. """, 'author': 'Odoo SA', 'category': 'Website/Website', 'version': '1.0', 'depends': ['website_sale'], 'data': [ 'security/website_sale_wishlist_security.xml', 'security/ir.model.access.csv', 'views/website_sale_wishlist_template.xml', 'views/snippets.xml', ], 'installable': True, 'assets': { 'web.assets_frontend': [ 'website_sale_wishlist/static/src/**/*', ], 'web.assets_tests': [ 'website_sale_wishlist/static/tests/**/*', ], }, 'license': 'LGPL-3', }
32.37931
939
2,551
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.tagged('-at_install', 'post_install') class TestUi(odoo.tests.HttpCase): def test_01_wishlist_tour(self): self.env['product.template'].search([]).write({'website_published': False}) # Setup attributes and attributes values self.product_attribute_1 = self.env['product.attribute'].create({ 'name': 'Legs', 'sequence': 10, }) product_attribute_value_1 = self.env['product.attribute.value'].create({ 'name': 'Steel', 'attribute_id': self.product_attribute_1.id, 'sequence': 1, }) product_attribute_value_2 = self.env['product.attribute.value'].create({ 'name': 'Aluminium', 'attribute_id': self.product_attribute_1.id, 'sequence': 2, }) product_attribute_2 = self.env['product.attribute'].create({ 'name': 'Color', 'sequence': 20, }) product_attribute_value_3 = self.env['product.attribute.value'].create({ 'name': 'White', 'attribute_id': product_attribute_2.id, 'sequence': 1, }) product_attribute_value_4 = self.env['product.attribute.value'].create({ 'name': 'Black', 'attribute_id': product_attribute_2.id, 'sequence': 2, }) # Create product template self.product_product_4_product_template = self.env['product.template'].create({ 'name': 'Customizable Desk (TEST)', 'standard_price': 500.0, 'list_price': 750.0, 'website_published': True, }) # Generate variants self.env['product.template.attribute.line'].create([{ 'product_tmpl_id': self.product_product_4_product_template.id, 'attribute_id': self.product_attribute_1.id, 'value_ids': [(4, product_attribute_value_1.id), (4, product_attribute_value_2.id)], }, { 'product_tmpl_id': self.product_product_4_product_template.id, 'attribute_id': product_attribute_2.id, 'value_ids': [(4, product_attribute_value_3.id), (4, product_attribute_value_4.id)], }]) self.env.ref('base.user_admin').name = 'Mitchell Admin' self.start_tour("/", 'shop_wishlist') def test_02_wishlist_admin_tour(self): self.start_tour("/", 'shop_wishlist_admin', login="admin")
38.651515
2,551
3,901
py
PYTHON
15.0
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from odoo import api, fields, models from odoo.http import request class ProductWishlist(models.Model): _name = 'product.wishlist' _description = 'Product Wishlist' _sql_constraints = [ ("product_unique_partner_id", "UNIQUE(product_id, partner_id)", "Duplicated wishlisted product for this partner."), ] partner_id = fields.Many2one('res.partner', string='Owner') product_id = fields.Many2one('product.product', string='Product', required=True) currency_id = fields.Many2one('res.currency', related='pricelist_id.currency_id', readonly=True) pricelist_id = fields.Many2one('product.pricelist', string='Pricelist', help='Pricelist when added') price = fields.Monetary(currency_field='currency_id', string='Price', help='Price of the product when it has been added in the wishlist') website_id = fields.Many2one('website', ondelete='cascade', required=True) active = fields.Boolean(default=True, required=True) @api.model def current(self): """Get all wishlist items that belong to current user or session, filter products that are unpublished.""" if not request: return self if request.website.is_public_user(): wish = self.sudo().search([('id', 'in', request.session.get('wishlist_ids', []))]) else: wish = self.search([("partner_id", "=", self.env.user.partner_id.id), ('website_id', '=', request.website.id)]) return wish.filtered(lambda x: x.sudo().product_id.product_tmpl_id.website_published and x.sudo().product_id.product_tmpl_id.sale_ok) @api.model def _add_to_wishlist(self, pricelist_id, currency_id, website_id, price, product_id, partner_id=False): wish = self.env['product.wishlist'].create({ 'partner_id': partner_id, 'product_id': product_id, 'currency_id': currency_id, 'pricelist_id': pricelist_id, 'price': price, 'website_id': website_id, }) return wish @api.model def _check_wishlist_from_session(self): """Assign all wishlist withtout partner from this the current session""" session_wishes = self.sudo().search([('id', 'in', request.session.get('wishlist_ids', []))]) partner_wishes = self.sudo().search([("partner_id", "=", self.env.user.partner_id.id)]) partner_products = partner_wishes.mapped("product_id") # Remove session products already present for the user duplicated_wishes = session_wishes.filtered(lambda wish: wish.product_id <= partner_products) session_wishes -= duplicated_wishes duplicated_wishes.unlink() # Assign the rest to the user session_wishes.write({"partner_id": self.env.user.partner_id.id}) request.session.pop('wishlist_ids') @api.autovacuum def _gc_sessions(self, *args, **kwargs): """Remove wishlists for unexisting sessions.""" self.with_context(active_test=False).search([ ("create_date", "<", fields.Datetime.to_string(datetime.now() - timedelta(weeks=kwargs.get('wishlist_week', 5)))), ("partner_id", "=", False), ]).unlink() class ResPartner(models.Model): _inherit = 'res.partner' wishlist_ids = fields.One2many('product.wishlist', 'partner_id', string='Wishlist', domain=[('active', '=', True)]) class ProductTemplate(models.Model): _inherit = 'product.template' def _is_in_wishlist(self): self.ensure_one() return self in self.env['product.wishlist'].current().mapped('product_id.product_tmpl_id') class ProductProduct(models.Model): _inherit = 'product.product' def _is_in_wishlist(self): self.ensure_one() return self in self.env['product.wishlist'].current().mapped('product_id')
42.402174
3,901
475
py
PYTHON
15.0
from odoo import api, fields, models from odoo.http import request class ResUsers(models.Model): _inherit = "res.users" def _check_credentials(self, password, env): """Make all wishlists from session belong to its owner user.""" result = super(ResUsers, self)._check_credentials(password, env) if request and request.session.get('wishlist_ids'): self.env["product.wishlist"]._check_wishlist_from_session() return result
36.538462
475
2,243
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import http from odoo.http import request from odoo.addons.website_sale.controllers.main import WebsiteSale import json class WebsiteSaleWishlist(WebsiteSale): @http.route(['/shop/wishlist/add'], type='json', auth="public", website=True) def add_to_wishlist(self, product_id, price=False, **kw): if not price: pricelist_context, pl = self._get_pricelist_context() p = request.env['product.product'].with_context(pricelist_context, display_default_code=False).browse(product_id) price = p._get_combination_info_variant()['price'] Wishlist = request.env['product.wishlist'] if request.website.is_public_user(): Wishlist = Wishlist.sudo() partner_id = False else: partner_id = request.env.user.partner_id.id wish_id = Wishlist._add_to_wishlist( pl.id, pl.currency_id.id, request.website.id, price, product_id, partner_id ) if not partner_id: request.session['wishlist_ids'] = request.session.get('wishlist_ids', []) + [wish_id.id] return wish_id @http.route(['/shop/wishlist'], type='http', auth="public", website=True, sitemap=False) def get_wishlist(self, count=False, **kw): values = request.env['product.wishlist'].with_context(display_default_code=False).current() if count: return request.make_response(json.dumps(values.mapped('product_id').ids)) if not len(values): return request.redirect("/shop") return request.render("website_sale_wishlist.product_wishlist", dict(wishes=values)) @http.route(['/shop/wishlist/remove/<model("product.wishlist"):wish>'], type='json', auth="public", website=True) def rm_from_wishlist(self, wish, **kw): if request.website.is_public_user(): wish_ids = request.session.get('wishlist_ids') or [] if wish.id in wish_ids: request.session['wishlist_ids'].remove(wish.id) request.session.modified = True wish.sudo().unlink() else: wish.unlink() return True
38.016949
2,243
482
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { "name": "Microsoft Outlook", "version": "1.0", "category": "Hidden", "description": "Outlook support for outgoing mail servers", "depends": [ "mail", ], "data": [ "views/ir_mail_server_views.xml", "views/res_config_settings_views.xml", "views/templates.xml", ], "auto_install": False, "license": "LGPL-3", }
25.368421
482
2,754
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 from odoo import _, api, models from odoo.exceptions import UserError class IrMailServer(models.Model): """Add the Outlook OAuth authentication on the outgoing mail servers.""" _name = 'ir.mail_server' _inherit = ['ir.mail_server', 'microsoft.outlook.mixin'] _OUTLOOK_SCOPE = 'https://outlook.office.com/SMTP.Send' @api.constrains('use_microsoft_outlook_service', 'smtp_pass', 'smtp_encryption') def _check_use_microsoft_outlook_service(self): for server in self: if not server.use_microsoft_outlook_service: continue if server.smtp_pass: raise UserError(_( 'Please leave the password field empty for Outlook mail server %r. ' 'The OAuth process does not require it') % server.name) if server.smtp_encryption != 'starttls': raise UserError(_( 'Incorrect Connection Security for Outlook mail server %r. ' 'Please set it to "TLS (STARTTLS)".') % server.name) if not server.smtp_user: raise UserError(_( 'Please fill the "Username" field with your Outlook/Office365 username (your email address). ' 'This should be the same account as the one used for the Outlook OAuthentication Token.')) @api.onchange('smtp_encryption') def _onchange_encryption(self): """Do not change the SMTP configuration if it's a Outlook server (e.g. the port which is already set)""" if not self.use_microsoft_outlook_service: super()._onchange_encryption() @api.onchange('use_microsoft_outlook_service') def _onchange_use_microsoft_outlook_service(self): if self.use_microsoft_outlook_service: self.smtp_host = 'smtp.outlook.com' self.smtp_encryption = 'starttls' self.smtp_port = 587 else: self.microsoft_outlook_refresh_token = False self.microsoft_outlook_access_token = False self.microsoft_outlook_access_token_expiration = False def _smtp_login(self, connection, smtp_user, smtp_password): if len(self) == 1 and self.use_microsoft_outlook_service: auth_string = self._generate_outlook_oauth2_string(smtp_user) oauth_param = base64.b64encode(auth_string.encode()).decode() connection.ehlo() connection.docmd('AUTH', 'XOAUTH2 %s' % oauth_param) else: super()._smtp_login(connection, smtp_user, smtp_password)
41.104478
2,754
8,568
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import logging import time import requests from werkzeug.urls import url_encode, url_join from odoo import _, api, fields, models from odoo.exceptions import AccessError, UserError from odoo.tools.misc import hmac _logger = logging.getLogger(__name__) class MicrosoftOutlookMixin(models.AbstractModel): _name = 'microsoft.outlook.mixin' _description = 'Microsoft Outlook Mixin' _OUTLOOK_SCOPE = None use_microsoft_outlook_service = fields.Boolean('Outlook Authentication') is_microsoft_outlook_configured = fields.Boolean('Is Outlook Credential Configured', compute='_compute_is_microsoft_outlook_configured') microsoft_outlook_refresh_token = fields.Char(string='Outlook Refresh Token', groups='base.group_system', copy=False) microsoft_outlook_access_token = fields.Char(string='Outlook Access Token', groups='base.group_system', copy=False) microsoft_outlook_access_token_expiration = fields.Integer(string='Outlook Access Token Expiration Timestamp', groups='base.group_system', copy=False) microsoft_outlook_uri = fields.Char(compute='_compute_outlook_uri', string='Authentication URI', help='The URL to generate the authorization code from Outlook', groups='base.group_system') @api.depends('use_microsoft_outlook_service') def _compute_is_microsoft_outlook_configured(self): Config = self.env['ir.config_parameter'].sudo() microsoft_outlook_client_id = Config.get_param('microsoft_outlook_client_id') microsoft_outlook_client_secret = Config.get_param('microsoft_outlook_client_secret') self.is_microsoft_outlook_configured = microsoft_outlook_client_id and microsoft_outlook_client_secret @api.depends('use_microsoft_outlook_service') def _compute_outlook_uri(self): Config = self.env['ir.config_parameter'].sudo() base_url = self.get_base_url() microsoft_outlook_client_id = Config.get_param('microsoft_outlook_client_id') for record in self: if not record.id or not record.use_microsoft_outlook_service or not record.is_microsoft_outlook_configured: record.microsoft_outlook_uri = False continue record.microsoft_outlook_uri = url_join(self._get_microsoft_endpoint(), 'authorize?%s' % url_encode({ 'client_id': microsoft_outlook_client_id, 'response_type': 'code', 'redirect_uri': url_join(base_url, '/microsoft_outlook/confirm'), 'response_mode': 'query', # offline_access is needed to have the refresh_token 'scope': 'offline_access %s' % self._OUTLOOK_SCOPE, 'state': json.dumps({ 'model': record._name, 'id': record.id, 'csrf_token': record._get_outlook_csrf_token(), }) })) def open_microsoft_outlook_uri(self): """Open the URL to accept the Outlook permission. This is done with an action, so we can force the user the save the form. We need him to save the form so the current mail server record exist in DB, and we can include the record ID in the URL. """ self.ensure_one() if not self.env.user.has_group('base.group_system'): raise AccessError(_('Only the administrator can link an Outlook mail server.')) if not self.use_microsoft_outlook_service or not self.is_microsoft_outlook_configured: raise UserError(_('Please configure your Outlook credentials.')) return { 'type': 'ir.actions.act_url', 'url': self.microsoft_outlook_uri, } def _fetch_outlook_refresh_token(self, authorization_code): """Request the refresh token and the initial access token from the authorization code. :return: refresh_token, access_token, access_token_expiration """ response = self._fetch_outlook_token('authorization_code', code=authorization_code) return ( response['refresh_token'], response['access_token'], int(time.time()) + response['expires_in'], ) def _fetch_outlook_access_token(self, refresh_token): """Refresh the access token thanks to the refresh token. :return: access_token, access_token_expiration """ response = self._fetch_outlook_token('refresh_token', refresh_token=refresh_token) return ( response['refresh_token'], response['access_token'], int(time.time()) + response['expires_in'], ) def _fetch_outlook_token(self, grant_type, **values): """Generic method to request an access token or a refresh token. Return the JSON response of the Outlook API and manage the errors which can occur. :param grant_type: Depends the action we want to do (refresh_token or authorization_code) :param values: Additional parameters that will be given to the Outlook endpoint """ Config = self.env['ir.config_parameter'].sudo() base_url = self.get_base_url() microsoft_outlook_client_id = Config.get_param('microsoft_outlook_client_id') microsoft_outlook_client_secret = Config.get_param('microsoft_outlook_client_secret') response = requests.post( url_join(self._get_microsoft_endpoint(), 'token'), data={ 'client_id': microsoft_outlook_client_id, 'client_secret': microsoft_outlook_client_secret, 'scope': 'offline_access %s' % self._OUTLOOK_SCOPE, 'redirect_uri': url_join(base_url, '/microsoft_outlook/confirm'), 'grant_type': grant_type, **values, }, timeout=10, ) if not response.ok: try: error_description = response.json()['error_description'] except Exception: error_description = _('Unknown error.') raise UserError(_('An error occurred when fetching the access token. %s') % error_description) return response.json() def _generate_outlook_oauth2_string(self, login): """Generate a OAuth2 string which can be used for authentication. :param user: Email address of the Outlook account to authenticate :return: The SASL argument for the OAuth2 mechanism. """ self.ensure_one() now_timestamp = int(time.time()) if not self.microsoft_outlook_access_token \ or not self.microsoft_outlook_access_token_expiration \ or self.microsoft_outlook_access_token_expiration < now_timestamp: if not self.microsoft_outlook_refresh_token: raise UserError(_('Please login your Outlook mail server before using it.')) ( self.microsoft_outlook_refresh_token, self.microsoft_outlook_access_token, self.microsoft_outlook_access_token_expiration, ) = self._fetch_outlook_access_token(self.microsoft_outlook_refresh_token) _logger.info( 'Microsoft Outlook: fetch new access token. It expires in %i minutes', (self.microsoft_outlook_access_token_expiration - now_timestamp) // 60) else: _logger.info( 'Microsoft Outlook: reuse existing access token. It expires in %i minutes', (self.microsoft_outlook_access_token_expiration - now_timestamp) // 60) return 'user=%s\1auth=Bearer %s\1\1' % (login, self.microsoft_outlook_access_token) def _get_outlook_csrf_token(self): """Generate a CSRF token that will be verified in `microsoft_outlook_callback`. This will prevent a malicious person to make an admin user disconnect the mail servers. """ self.ensure_one() _logger.info('Microsoft Outlook: generate CSRF token for %s #%i', self._name, self.id) return hmac( env=self.env(su=True), scope='microsoft_outlook_oauth', message=(self._name, self.id), ) @api.model def _get_microsoft_endpoint(self): return self.env["ir.config_parameter"].sudo().get_param( 'microsoft_outlook.endpoint', 'https://login.microsoftonline.com/common/oauth2/v2.0/', )
43.714286
8,568
470
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' microsoft_outlook_client_identifier = fields.Char('Outlook Client Id', config_parameter='microsoft_outlook_client_id') microsoft_outlook_client_secret = fields.Char('Outlook Client Secret', config_parameter='microsoft_outlook_client_secret')
42.727273
470
2,848
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import logging import werkzeug from werkzeug.exceptions import Forbidden from odoo import http from odoo.exceptions import UserError from odoo.http import request from odoo.tools import consteq _logger = logging.getLogger(__name__) class MicrosoftOutlookController(http.Controller): @http.route('/microsoft_outlook/confirm', type='http', auth='user') def microsoft_outlook_callback(self, code=None, state=None, error_description=None, **kwargs): """Callback URL during the OAuth process. Outlook redirects the user browser to this endpoint with the authorization code. We will fetch the refresh token and the access token thanks to this authorization code and save those values on the given mail server. """ if not request.env.user.has_group('base.group_system'): _logger.error('Microsoft Outlook: Non system user try to link an Outlook account.') raise Forbidden() try: state = json.loads(state) model_name = state['model'] rec_id = state['id'] csrf_token = state['csrf_token'] except Exception: _logger.error('Microsoft Outlook: Wrong state value %r.', state) raise Forbidden() if error_description: return request.render('microsoft_outlook.microsoft_outlook_oauth_error', { 'error': error_description, 'model_name': model_name, 'rec_id': rec_id, }) model = request.env[model_name] if not issubclass(type(model), request.env.registry['microsoft.outlook.mixin']): # The model must inherits from the "microsoft.outlook.mixin" mixin raise Forbidden() record = model.browse(rec_id).exists() if not record: raise Forbidden() if not csrf_token or not consteq(csrf_token, record._get_outlook_csrf_token()): _logger.error('Microsoft Outlook: Wrong CSRF token during Outlook authentication.') raise Forbidden() try: refresh_token, access_token, expiration = record._fetch_outlook_refresh_token(code) except UserError as e: return request.render('microsoft_outlook.microsoft_outlook_oauth_error', { 'error': str(e.name), 'model_name': model_name, 'rec_id': rec_id, }) record.write({ 'microsoft_outlook_refresh_token': refresh_token, 'microsoft_outlook_access_token': access_token, 'microsoft_outlook_access_token_expiration': expiration, }) return request.redirect(f'/web?#id={rec_id}&model={model_name}&view_type=form')
37.473684
2,848
1,652
py
PYTHON
15.0
#-*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2009-2010 Soluciones Tecnologócias Prisma S.A. All Rights Reserved. # José Rodrigo Fernández Menegazzo, Soluciones Tecnologócias Prisma S.A. # (http://www.solucionesprisma.com) # # This module provides a minimal Guatemalan chart of accounts that can be use # to build upon a more complex one. It also includes a chart of taxes and # the Quetzal currency. # # This module is based on the UK minimal chart of accounts: # Copyright (c) 2004-2009 Seath Solutions Ltd. All Rights Reserved. # Geoff Gardiner, Seath Solutions Ltd (http://www.seathsolutions.com/) # # This module works with OpenERP 6.0 # { 'name': 'Guatemala - Accounting', 'version': '3.0', 'category': 'Accounting/Localizations/Account Charts', 'description': """ This is the base module to manage the accounting chart for Guatemala. ===================================================================== Agrega una nomenclatura contable para Guatemala. También icluye impuestos y la moneda del Quetzal. -- Adds accounting chart for Guatemala. It also includes taxes and the Quetzal currency.""", 'author': 'José Rodrigo Fernández Menegazzo', 'website': 'http://solucionesprisma.com/', 'depends': ['base', 'account'], 'data': [ 'data/l10n_gt_chart_data.xml', 'data/account.account.template.csv', 'data/l10n_gt_chart_post_data.xml', 'data/account_tax_group_data.xml', 'data/account_chart_template_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
36.555556
1,645
1,571
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2009 - now Grzegorz Grzelak grzegorz.grzelak@openglobe.pl { 'name' : 'Poland - Accounting', 'version' : '2.0', 'author' : 'Grzegorz Grzelak (OpenGLOBE)', 'website': 'http://www.openglobe.pl', 'category': 'Accounting/Localizations/Account Charts', 'description': """ This is the module to manage the accounting chart and taxes for Poland in Odoo. ================================================================================== To jest moduł do tworzenia wzorcowego planu kont, podatków, obszarów podatkowych i rejestrów podatkowych. Moduł ustawia też konta do kupna i sprzedaży towarów zakładając, że wszystkie towary są w obrocie hurtowym. Niniejszy moduł jest przeznaczony dla odoo 8.0. Wewnętrzny numer wersji OpenGLOBE 1.02 """, 'depends' : [ 'account', 'base_iban', 'base_vat', ], 'data': [ 'data/l10n_pl_chart_data.xml', 'data/account.account.template.csv', 'data/res.country.state.csv', 'data/l10n_pl_chart_post_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_report_data.xml', 'data/account_tax_data.xml', 'data/account_fiscal_position_data.xml', 'data/account_chart_template_data.xml' ], 'demo': [ 'demo/demo_company.xml', ], 'post_init_hook': '_preserve_tag_on_taxes', 'license': 'LGPL-3', }
35.386364
1,557
290
py
PYTHON
15.0
from openerp.modules.registry import RegistryManager def migrate(cr, version): registry = RegistryManager.get(cr.dbname) from openerp.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_pl')
48.333333
290
1,822
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Forum', 'category': 'Website/Website', 'sequence': 265, 'summary': 'Manage a forum with FAQ and Q&A', 'version': '1.1', 'description': """ Ask questions, get answers, no distractions """, 'website': 'https://www.odoo.com/app/forum', 'depends': [ 'auth_signup', 'website_mail', 'website_profile', ], 'data': [ 'data/forum_default_faq.xml', 'data/forum_data.xml', 'data/mail_data.xml', 'data/mail_templates.xml', 'views/forum.xml', 'views/res_users_views.xml', 'views/website_forum.xml', 'views/website_forum_profile.xml', 'views/ir_qweb.xml', 'views/snippets/snippets.xml', 'security/ir.model.access.csv', 'security/website_forum_security.xml', 'data/badges_question.xml', 'data/badges_answer.xml', 'data/badges_participation.xml', 'data/badges_moderation.xml', ], 'demo': [ 'data/forum_demo.xml', ], 'installable': True, 'application': True, 'assets': { 'website.assets_editor': [ 'website_forum/static/src/js/tours/website_forum.js', 'website_forum/static/src/js/website_forum.editor.js', ], 'web.assets_tests': [ 'website_forum/static/tests/**/*', ], 'web.assets_frontend': [ 'website_forum/static/src/scss/website_forum.scss', 'website_forum/static/src/js/website_forum.js', 'website_forum/static/src/js/website_forum.share.js', ], 'web.assets_qweb': [ 'website_forum/static/src/xml/*.xml', ], }, 'license': 'LGPL-3', }
30.366667
1,822
587
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.base.tests.common import HttpCaseWithUserDemo from odoo.tests import tagged @tagged('post_install', '-at_install') class TestUi(HttpCaseWithUserDemo): def test_01_admin_forum_tour(self): self.start_tour("/", 'question', login="admin", step_delay=100) def test_02_demo_question(self): forum = self.env.ref('website_forum.forum_help') demo = self.user_demo demo.karma = forum.karma_post + 1 self.start_tour("/", 'forum_question', login="demo")
34.529412
587
22,437
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from .common import KARMA, TestForumCommon from odoo import http from odoo.addons.http_routing.models.ir_http import slug from odoo.exceptions import UserError, AccessError from odoo.tests import HttpCase from odoo.tools import mute_logger from psycopg2 import IntegrityError class TestForum(TestForumCommon): def test_crud_rights(self): Post = self.env['forum.post'] Vote = self.env['forum.post.vote'] self.user_portal.karma = 500 self.user_employee.karma = 500 # create some posts self.admin_post = self.post self.portal_post = Post.with_user(self.user_portal).create({ 'name': 'Post from Portal User', 'content': 'I am not a bird.', 'forum_id': self.forum.id, }) self.employee_post = Post.with_user(self.user_employee).create({ 'name': 'Post from Employee User', 'content': 'I am not a bird.', 'forum_id': self.forum.id, }) # vote on some posts self.employee_vote_on_admin_post = Vote.with_user(self.user_employee).create({ 'post_id': self.admin_post.id, 'vote': '1', }) self.portal_vote_on_admin_post = Vote.with_user(self.user_portal).create({ 'post_id': self.admin_post.id, 'vote': '1', }) self.admin_vote_on_portal_post = Vote.create({ 'post_id': self.portal_post.id, 'vote': '1', }) self.admin_vote_on_employee_post = Vote.create({ 'post_id': self.employee_post.id, 'vote': '1', }) # One should not be able to modify someone else's vote with self.assertRaises(UserError): self.admin_vote_on_portal_post.with_user(self.user_employee).write({ 'vote': '-1', }) with self.assertRaises(UserError): self.admin_vote_on_employee_post.with_user(self.user_portal).write({ 'vote': '-1', }) # One should not be able to give his vote to someone else self.employee_vote_on_admin_post.with_user(self.user_employee).write({ 'user_id': 1, }) self.assertEqual(self.employee_vote_on_admin_post.user_id, self.user_employee, 'User employee should not be able to give its vote ownership to someone else') # One should not be able to change his vote's post to a post of his own (would be self voting) with self.assertRaises(UserError): self.employee_vote_on_admin_post.with_user(self.user_employee).write({ 'post_id': self.employee_post.id, }) # One should not be able to give his vote to someone else self.portal_vote_on_admin_post.with_user(self.user_portal).write({ 'user_id': 1, }) self.assertEqual(self.portal_vote_on_admin_post.user_id, self.user_portal, 'User portal should not be able to give its vote ownership to someone else') # One should not be able to change his vote's post to a post of his own (would be self voting) with self.assertRaises(UserError): self.portal_vote_on_admin_post.with_user(self.user_portal).write({ 'post_id': self.portal_post.id, }) # One should not be able to vote for its own post with self.assertRaises(UserError): Vote.with_user(self.user_employee).create({ 'post_id': self.employee_post.id, 'vote': '1', }) # One should not be able to vote for its own post with self.assertRaises(UserError): Vote.with_user(self.user_portal).create({ 'post_id': self.portal_post.id, 'vote': '1', }) with mute_logger('odoo.sql_db'): with self.assertRaises(IntegrityError): with self.cr.savepoint(): # One should not be able to vote more than once on a same post Vote.with_user(self.user_employee).create({ 'post_id': self.admin_post.id, 'vote': '1', }) with self.assertRaises(IntegrityError): with self.cr.savepoint(): # One should not be able to vote more than once on a same post Vote.with_user(self.user_employee).create({ 'post_id': self.admin_post.id, 'vote': '1', }) # One should not be able to create a vote for someone else new_employee_vote = Vote.with_user(self.user_employee).create({ 'post_id': self.portal_post.id, 'user_id': 1, 'vote': '1', }) self.assertEqual(new_employee_vote.user_id, self.user_employee, 'Creating a vote for someone else should not be allowed. It should create it for yourself instead') # One should not be able to create a vote for someone else new_portal_vote = Vote.with_user(self.user_portal).create({ 'post_id': self.employee_post.id, 'user_id': 1, 'vote': '1', }) self.assertEqual(new_portal_vote.user_id, self.user_portal, 'Creating a vote for someone else should not be allowed. It should create it for yourself instead') @mute_logger('odoo.addons.base.models.ir_model', 'odoo.models') def test_ask(self): Post = self.env['forum.post'] # Public user asks a question: not allowed with self.assertRaises(AccessError): Post.with_user(self.user_public).create({ 'name': " Question ?", 'forum_id': self.forum.id, }) # Portal user asks a question with tags: not allowed, unsufficient karma with self.assertRaises(AccessError): Post.with_user(self.user_portal).create({ 'name': " Q_0", 'forum_id': self.forum.id, 'tag_ids': [(0, 0, {'name': 'Tag0', 'forum_id': self.forum.id})] }) # Portal user asks a question with tags: ok if enough karma self.user_portal.karma = KARMA['tag_create'] Post.with_user(self.user_portal).create({ 'name': " Q0", 'forum_id': self.forum.id, 'tag_ids': [(0, 0, {'name': 'Tag1', 'forum_id': self.forum.id})] }) self.assertEqual(self.user_portal.karma, KARMA['tag_create'], 'website_forum: wrong karma generation when asking question') self.user_portal.karma = KARMA['post'] Post.with_user(self.user_portal).create({ 'name': " Q0", 'forum_id': self.forum.id, 'tag_ids': [(0, 0, {'name': 'Tag42', 'forum_id': self.forum.id})] }) self.assertEqual(self.user_portal.karma, KARMA['post'] + KARMA['gen_que_new'], 'website_forum: wrong karma generation when asking question') @mute_logger('odoo.addons.base.models.ir_model', 'odoo.models') def test_answer(self): Post = self.env['forum.post'] # Answers its own question: not allowed, unsufficient karma with self.assertRaises(AccessError): Post.with_user(self.user_employee).create({ 'name': " A0", 'forum_id': self.forum.id, 'parent_id': self.post.id, }) # Answers on question: ok if enough karma self.user_employee.karma = KARMA['ans'] Post.with_user(self.user_employee).create({ 'name': " A0", 'forum_id': self.forum.id, 'parent_id': self.post.id, }) self.assertEqual(self.user_employee.karma, KARMA['ans'], 'website_forum: wrong karma generation when answering question') @mute_logger('odoo.addons.base.models.ir_model', 'odoo.models') def test_vote_crash(self): Post = self.env['forum.post'] self.user_employee.karma = KARMA['ans'] emp_answer = Post.with_user(self.user_employee).create({ 'name': 'TestAnswer', 'forum_id': self.forum.id, 'parent_id': self.post.id}) # upvote its own post with self.assertRaises(UserError): emp_answer.vote(upvote=True) # not enough karma with self.assertRaises(AccessError): self.post.with_user(self.user_portal).vote(upvote=True) def test_vote(self): def check_vote_records_count_and_integrity(expected_total_votes_count): groups = self.env['forum.post.vote'].read_group([], fields=['__count'], groupby=['post_id', 'user_id'], lazy=False) self.assertEqual(len(groups), expected_total_votes_count) for post_user_group in groups: self.assertEqual(post_user_group['__count'], 1) check_vote_records_count_and_integrity(2) self.post.create_uid.karma = KARMA['ask'] self.user_portal.karma = KARMA['dwv'] initial_vote_count = self.post.vote_count post_as_portal = self.post.with_user(self.user_portal) res = post_as_portal.vote(upvote=True) self.assertEqual(res['user_vote'], '1') self.assertEqual(res['vote_count'], initial_vote_count + 1) self.assertEqual(post_as_portal.user_vote, 1) self.assertEqual(self.post.create_uid.karma, KARMA['ask'] + KARMA['gen_que_upv'], 'website_forum: wrong karma generation of upvoted question author') # On voting again with the same value, nothing changes res = post_as_portal.vote(upvote=True) self.assertEqual(res['vote_count'], initial_vote_count + 1) self.assertEqual(res['user_vote'], '1') self.post.invalidate_cache() self.assertEqual(post_as_portal.user_vote, 1) # On reverting vote, vote cancels res = post_as_portal.vote(upvote=False) self.assertEqual(res['vote_count'], initial_vote_count) self.assertEqual(res['user_vote'], '0') self.post.invalidate_cache() self.assertEqual(post_as_portal.user_vote, 0) # Everything works from "0" too res = post_as_portal.vote(upvote=False) self.assertEqual(res['vote_count'], initial_vote_count - 1) self.assertEqual(res['user_vote'], '-1') self.post.invalidate_cache() self.assertEqual(post_as_portal.user_vote, -1) check_vote_records_count_and_integrity(3) @mute_logger('odoo.addons.base.models.ir_model', 'odoo.models') def test_downvote_crash(self): Post = self.env['forum.post'] self.user_employee.karma = KARMA['ans'] emp_answer = Post.with_user(self.user_employee).create({ 'name': 'TestAnswer', 'forum_id': self.forum.id, 'parent_id': self.post.id}) # downvote its own post with self.assertRaises(UserError): emp_answer.vote(upvote=False) # not enough karma with self.assertRaises(AccessError): self.post.with_user(self.user_portal).vote(upvote=False) def test_downvote(self): self.post.create_uid.karma = 50 self.user_portal.karma = KARMA['dwv'] self.post.with_user(self.user_portal).vote(upvote=False) self.assertEqual(self.post.create_uid.karma, 50 + KARMA['gen_que_dwv'], 'website_forum: wrong karma generation of downvoted question author') def test_comment_crash(self): with self.assertRaises(AccessError): self.post.with_user(self.user_portal).message_post(body='Should crash', message_type='comment') def test_comment(self): self.post.with_user(self.user_employee).message_post(body='Test0', message_type='notification') self.user_employee.karma = KARMA['com_all'] self.post.with_user(self.user_employee).message_post(body='Test1', message_type='comment') self.assertEqual(len(self.post.message_ids), 4, 'website_forum: wrong behavior of message_post') def test_flag_a_post(self): Post = self.env['forum.post'] self.user_portal.karma = KARMA['ask'] post = Post.with_user(self.user_portal).create({ 'name': "Q0", 'forum_id': self.forum.id, }) # portal user flags a post: not allowed, unsufficient karma with self.assertRaises(AccessError): post.with_user(self.user_portal).flag() # portal user flags a post: ok if enough karma self.user_portal.karma = KARMA['flag'] post.state = 'active' post.with_user(self.user_portal).flag() self.assertEqual(post.state, 'flagged', 'website_forum: wrong state when flagging a post') def test_validate_a_post(self): Post = self.env['forum.post'] self.user_portal.karma = KARMA['ask'] post = Post.with_user(self.user_portal).create({ 'name': "Q0", 'forum_id': self.forum.id, }) # portal user validate a post: not allowed, unsufficient karma with self.assertRaises(AccessError): post.with_user(self.user_portal).validate() # portal user validate a pending post self.user_portal.karma = KARMA['moderate'] post.state = 'pending' init_karma = post.create_uid.karma post.with_user(self.user_portal).validate() self.assertEqual(post.state, 'active', 'website_forum: wrong state when validate a post after pending') self.assertEqual(post.create_uid.karma, init_karma + KARMA['gen_que_new'], 'website_forum: wrong karma when validate a post after pending') # portal user validate a flagged post: ok if enough karma self.user_portal.karma = KARMA['moderate'] post.state = 'flagged' post.with_user(self.user_portal).validate() self.assertEqual(post.state, 'active', 'website_forum: wrong state when validate a post after flagged') # portal user validate an offensive post: ok if enough karma self.user_portal.karma = KARMA['moderate'] post.state = 'offensive' init_karma = post.create_uid.karma post.with_user(self.user_portal).validate() self.assertEqual(post.state, 'active', 'website_forum: wrong state when validate a post after offensive') def test_refuse_a_post(self): Post = self.env['forum.post'] self.user_portal.karma = KARMA['ask'] post = Post.with_user(self.user_portal).create({ 'name': "Q0", 'forum_id': self.forum.id, }) # portal user validate a post: not allowed, unsufficient karma with self.assertRaises(AccessError): post.with_user(self.user_portal).refuse() # portal user validate a pending post self.user_portal.karma = KARMA['moderate'] post.state = 'pending' init_karma = post.create_uid.karma post.with_user(self.user_portal).refuse() self.assertEqual(post.moderator_id, self.user_portal, 'website_forum: wrong moderator_id when refusing') self.assertEqual(post.create_uid.karma, init_karma, 'website_forum: wrong karma when refusing a post') def test_mark_a_post_as_offensive(self): Post = self.env['forum.post'] self.user_portal.karma = KARMA['ask'] post = Post.with_user(self.user_portal).create({ 'name': "Q0", 'forum_id': self.forum.id, }) # portal user mark a post as offensive: not allowed, unsufficient karma with self.assertRaises(AccessError): post.with_user(self.user_portal).mark_as_offensive(12) # portal user mark a post as offensive self.user_portal.karma = KARMA['moderate'] post.state = 'flagged' init_karma = post.create_uid.karma post.with_user(self.user_portal).mark_as_offensive(12) self.assertEqual(post.state, 'offensive', 'website_forum: wrong state when marking a post as offensive') self.assertEqual(post.create_uid.karma, init_karma + KARMA['gen_ans_flag'], 'website_forum: wrong karma when marking a post as offensive') def test_convert_answer_to_comment_crash(self): Post = self.env['forum.post'] # converting a question does nothing new_msg = self.post.with_user(self.user_portal).convert_answer_to_comment() self.assertEqual(new_msg.id, False, 'website_forum: question to comment conversion failed') self.assertEqual(Post.search([('name', '=', 'TestQuestion')])[0].forum_id.name, 'TestForum', 'website_forum: question to comment conversion failed') with self.assertRaises(AccessError): self.answer.with_user(self.user_portal).convert_answer_to_comment() def test_convert_answer_to_comment(self): self.user_portal.karma = KARMA['com_conv_all'] post_author = self.answer.create_uid.partner_id new_msg = self.answer.with_user(self.user_portal).convert_answer_to_comment() self.assertEqual(len(new_msg), 1, 'website_forum: wrong answer to comment conversion') self.assertEqual(new_msg.author_id, post_author, 'website_forum: wrong answer to comment conversion') self.assertIn('I am an anteater', new_msg.body, 'website_forum: wrong answer to comment conversion') def test_edit_post_crash(self): with self.assertRaises(AccessError): self.post.with_user(self.user_portal).write({'name': 'I am not your father.'}) def test_edit_post(self): self.post.create_uid.karma = KARMA['edit_own'] self.post.write({'name': 'Actually I am your dog.'}) self.user_portal.karma = KARMA['edit_all'] self.post.with_user(self.user_portal).write({'name': 'Actually I am your cat.'}) def test_close_post_crash(self): with self.assertRaises(AccessError): self.post.with_user(self.user_portal).close(None) def test_close_post_own(self): self.post.create_uid.karma = KARMA['close_own'] self.post.close(None) def test_close_post_all(self): self.user_portal.karma = KARMA['close_all'] self.post.with_user(self.user_portal).close(None) def test_deactivate_post_crash(self): with self.assertRaises(AccessError): self.post.with_user(self.user_portal).write({'active': False}) def test_deactivate_post_own(self): self.post.create_uid.karma = KARMA['unlink_own'] self.post.write({'active': False}) def test_deactivate_post_all(self): self.user_portal.karma = KARMA['unlink_all'] self.post.with_user(self.user_portal).write({'active': False}) def test_unlink_post_crash(self): with self.assertRaises(AccessError): self.post.with_user(self.user_portal).unlink() def test_unlink_post_own(self): self.post.create_uid.karma = KARMA['unlink_own'] self.post.unlink() def test_unlink_post_all(self): self.user_portal.karma = KARMA['unlink_all'] self.post.with_user(self.user_portal).unlink() def test_forum_mode_questions(self): Forum = self.env['forum.forum'] forum_questions = Forum.create({ 'name': 'Questions Forum', 'mode': 'questions', 'active': True }) Post = self.env['forum.post'] questions_post = Post.create({ 'name': 'My First Post', 'forum_id': forum_questions.id, 'parent_id': self.post.id, }) answer_to_questions_post = Post.create({ 'name': 'This is an answer', 'forum_id': forum_questions.id, 'parent_id': questions_post.id, }) self.assertEqual( not questions_post.uid_has_answered or questions_post.forum_id.mode == 'discussions', False) self.assertEqual( questions_post.uid_has_answered and questions_post.forum_id.mode == 'questions', True) def test_forum_mode_discussions(self): Forum = self.env['forum.forum'] forum_discussions = Forum.create({ 'name': 'Discussions Forum', 'mode': 'discussions', 'active': True }) Post = self.env['forum.post'] discussions_post = Post.create({ 'name': 'My First Post', 'forum_id': forum_discussions.id, 'parent_id': self.post.id, }) answer_to_discussions_post = Post.create({ 'name': 'This is an answer', 'forum_id': forum_discussions.id, 'parent_id': discussions_post.id, }) self.assertEqual( not discussions_post.uid_has_answered or discussions_post.forum_id.mode == 'discussions', True) self.assertEqual( discussions_post.uid_has_answered and discussions_post.forum_id.mode == 'questions', False) def test_tag_creation_multi_forum(self): Post = self.env['forum.post'] forum_1 = self.forum forum_2 = forum_1.copy({ 'name': 'Questions Forum' }) self.user_portal.karma = KARMA['tag_create'] Post.with_user(self.user_portal).create({ 'name': "Post Forum 1", 'forum_id': forum_1.id, 'tag_ids': forum_1._tag_to_write_vals('_Food'), }) Post.with_user(self.user_portal).create({ 'name': "Post Forum 2", 'forum_id': forum_2.id, 'tag_ids': forum_2._tag_to_write_vals('_Food'), }) food_tags = self.env['forum.tag'].search([('name', '=', 'Food')]) self.assertEqual(len(food_tags), 2, "One Food tag should have been created in each forum.") self.assertIn(forum_1, food_tags.forum_id, "One Food tag should have been created for forum 1.") self.assertIn(forum_2, food_tags.forum_id, "One Food tag should have been created for forum 2.") class TestWebsiteForum(TestForumCommon, HttpCase): def test_forum_post_compose_message_without_branding(self): self.authenticate("admin", "admin") self.url_open(f"/forum/{slug(self.forum)}/new", { "post_name": "test_branding", "content": "<p>test</p>", "csrf_token": http.WebRequest.csrf_token(self), }) post = self.env["forum.post"].search([('forum_id', '=', self.forum.id), ('name', '=', 'test_branding')]) self.assertNotIn("data-oe-", post.message_ids.body)
43.908023
22,437
1,511
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.website_forum.tests.common import TestForumCommon class TestForumTag(TestForumCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.env['forum.tag'].search([]).unlink() cls.tags = cls.env['forum.tag'].create( [{'forum_id': cls.forum.id, 'name': f'Test Tag {tag_idx}'} for tag_idx in range(1, 3)] ) cls.env['forum.post'].create( [{'name': 'Posting about tag 1', 'forum_id': cls.forum.id, 'tag_ids': [[6, 0, [cls.tags[0].id]]]}] ) def _check_tags_post_counts(self, tags, expected_counts): self.assertEqual(tags.mapped('posts_count'), expected_counts) def test_tag_posts_count(self): self._check_tags_post_counts(self.tags, [1, 0]) post_tag_1 = self.env['forum.post'].create( [{'name': 'Posting about tag 1 again', 'forum_id': self.forum.id, 'tag_ids': [[6, 0, [self.tags[0].id]]]}] ) self._check_tags_post_counts(self.tags, [2, 0]) post_tags = self.env['forum.post'].create( [{'name': 'Posting about tag 2 now', 'forum_id': self.forum.id, 'tag_ids': [[6, 0, self.tags.ids]]}] ) self._check_tags_post_counts(self.tags, [3, 1]) post_tag_1.active = False self._check_tags_post_counts(self.tags, [2, 1]) post_tags.close(None) self._check_tags_post_counts(self.tags, [1, 0])
43.171429
1,511
3,628
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common KARMA = { 'ask': 5, 'ans': 10, 'com_own': 5, 'com_all': 10, 'com_conv_all': 50, 'upv': 5, 'dwv': 10, 'edit_own': 10, 'edit_all': 20, 'close_own': 10, 'close_all': 20, 'unlink_own': 10, 'unlink_all': 20, 'post': 100, 'flag': 500, 'moderate': 1000, 'gen_que_new': 1, 'gen_que_upv': 5, 'gen_que_dwv': -10, 'gen_ans_upv': 10, 'gen_ans_dwv': -20, 'gen_ans_flag': -45, 'tag_create': 30, } class TestForumCommon(common.TransactionCase): @classmethod def setUpClass(cls): super(TestForumCommon, cls).setUpClass() Forum = cls.env['forum.forum'] Post = cls.env['forum.post'] # Test users TestUsersEnv = cls.env['res.users'].with_context({'no_reset_password': True}) group_employee_id = cls.env.ref('base.group_user').id group_portal_id = cls.env.ref('base.group_portal').id group_public_id = cls.env.ref('base.group_public').id cls.user_employee = TestUsersEnv.create({ 'name': 'Armande Employee', 'login': 'Armande', 'email': 'armande.employee@example.com', 'karma': 0, 'groups_id': [(6, 0, [group_employee_id])] }) cls.user_portal = TestUsersEnv.create({ 'name': 'Beatrice Portal', 'login': 'Beatrice', 'email': 'beatrice.employee@example.com', 'karma': 0, 'groups_id': [(6, 0, [group_portal_id])] }) cls.user_public = TestUsersEnv.create({ 'name': 'Cedric Public', 'login': 'Cedric', 'email': 'cedric.employee@example.com', 'karma': 0, 'groups_id': [(6, 0, [group_public_id])] }) # Test forum cls.forum = Forum.create({ 'name': 'TestForum', 'karma_ask': KARMA['ask'], 'karma_answer': KARMA['ans'], 'karma_comment_own': KARMA['com_own'], 'karma_comment_all': KARMA['com_all'], 'karma_answer_accept_own': 9999, 'karma_answer_accept_all': 9999, 'karma_upvote': KARMA['upv'], 'karma_downvote': KARMA['dwv'], 'karma_edit_own': KARMA['edit_own'], 'karma_edit_all': KARMA['edit_all'], 'karma_close_own': KARMA['close_own'], 'karma_close_all': KARMA['close_all'], 'karma_unlink_own': KARMA['unlink_own'], 'karma_unlink_all': KARMA['unlink_all'], 'karma_post': KARMA['post'], 'karma_comment_convert_all': KARMA['com_conv_all'], 'karma_gen_question_new': KARMA['gen_que_new'], 'karma_gen_question_upvote': KARMA['gen_que_upv'], 'karma_gen_question_downvote': KARMA['gen_que_dwv'], 'karma_gen_answer_upvote': KARMA['gen_ans_upv'], 'karma_gen_answer_downvote': KARMA['gen_ans_dwv'], 'karma_gen_answer_accept': 9999, 'karma_gen_answer_accepted': 9999, 'karma_gen_answer_flagged': KARMA['gen_ans_flag'], }) cls.post = Post.create({ 'name': 'TestQuestion', 'content': 'I am not a bird.', 'forum_id': cls.forum.id, 'tag_ids': [(0, 0, {'name': 'Tag2', 'forum_id': cls.forum.id})] }) cls.answer = Post.create({ 'name': 'TestAnswer', 'content': 'I am an anteater.', 'forum_id': cls.forum.id, 'parent_id': cls.post.id, })
37.791667
3,628
59,089
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import math import re from datetime import datetime from odoo import api, fields, models, tools, SUPERUSER_ID, _ from odoo.exceptions import UserError, ValidationError, AccessError from odoo.tools import misc, sql from odoo.tools.translate import html_translate from odoo.addons.http_routing.models.ir_http import slug, unslug _logger = logging.getLogger(__name__) class Forum(models.Model): _name = 'forum.forum' _description = 'Forum' _inherit = [ 'mail.thread', 'image.mixin', 'website.seo.metadata', 'website.multi.mixin', 'website.searchable.mixin', ] _order = "sequence" # description and use name = fields.Char('Forum Name', required=True, translate=True) sequence = fields.Integer('Sequence', default=1) mode = fields.Selection([ ('questions', 'Questions (1 answer)'), ('discussions', 'Discussions (multiple answers)')], string='Mode', required=True, default='questions', help='Questions mode: only one answer allowed\n Discussions mode: multiple answers allowed') privacy = fields.Selection([ ('public', 'Public'), ('connected', 'Signed In'), ('private', 'Some users')], help="Public: Forum is public\nSigned In: Forum is visible for signed in users\nSome users: Forum and their content are hidden for non members of selected group", default='public') authorized_group_id = fields.Many2one('res.groups', 'Authorized Group') menu_id = fields.Many2one('website.menu', 'Menu', copy=False) active = fields.Boolean(default=True) faq = fields.Html('Guidelines', translate=html_translate, sanitize=False) description = fields.Text('Description', translate=True) teaser = fields.Text('Teaser', compute='_compute_teaser', store=True) welcome_message = fields.Html( 'Welcome Message', translate=True, default="""<section> <div class="container py-5"> <div class="row"> <div class="col-lg-12"> <h1 class="text-center">Welcome!</h1> <p class="text-400 text-center"> This community is for professionals and enthusiasts of our products and services. <br/>Share and discuss the best content and new marketing ideas, build your professional profile and become a better marketer together. </p> </div> <div class="col text-center mt-3"> <a href="#" class="js_close_intro btn btn-outline-light mr-2">Hide Intro</a> <a class="btn btn-light forum_register_url" href="/web/login">Register</a> </div> </div> </div> </section>""", sanitize_attributes=False, sanitize_form=False) default_order = fields.Selection([ ('create_date desc', 'Newest'), ('write_date desc', 'Last Updated'), ('vote_count desc', 'Most Voted'), ('relevancy desc', 'Relevance'), ('child_count desc', 'Answered')], string='Default', required=True, default='write_date desc') relevancy_post_vote = fields.Float('First Relevance Parameter', default=0.8, help="This formula is used in order to sort by relevance. The variable 'votes' represents number of votes for a post, and 'days' is number of days since the post creation") relevancy_time_decay = fields.Float('Second Relevance Parameter', default=1.8) allow_bump = fields.Boolean('Allow Bump', default=True, help='Check this box to display a popup for posts older than 10 days ' 'without any given answer. The popup will offer to share it on social ' 'networks. When shared, a question is bumped at the top of the forum.') allow_share = fields.Boolean('Sharing Options', default=True, help='After posting the user will be proposed to share its question ' 'or answer on social networks, enabling social network propagation ' 'of the forum content.') # posts statistics post_ids = fields.One2many('forum.post', 'forum_id', string='Posts') last_post_id = fields.Many2one('forum.post', compute='_compute_last_post') total_posts = fields.Integer('# Posts', compute='_compute_forum_statistics') total_views = fields.Integer('# Views', compute='_compute_forum_statistics') total_answers = fields.Integer('# Answers', compute='_compute_forum_statistics') total_favorites = fields.Integer('# Favorites', compute='_compute_forum_statistics') count_posts_waiting_validation = fields.Integer(string="Number of posts waiting for validation", compute='_compute_count_posts_waiting_validation') count_flagged_posts = fields.Integer(string='Number of flagged posts', compute='_compute_count_flagged_posts') # karma generation karma_gen_question_new = fields.Integer(string='Asking a question', default=2) karma_gen_question_upvote = fields.Integer(string='Question upvoted', default=5) karma_gen_question_downvote = fields.Integer(string='Question downvoted', default=-2) karma_gen_answer_upvote = fields.Integer(string='Answer upvoted', default=10) karma_gen_answer_downvote = fields.Integer(string='Answer downvoted', default=-2) karma_gen_answer_accept = fields.Integer(string='Accepting an answer', default=2) karma_gen_answer_accepted = fields.Integer(string='Answer accepted', default=15) karma_gen_answer_flagged = fields.Integer(string='Answer flagged', default=-100) # karma-based actions karma_ask = fields.Integer(string='Ask questions', default=3) karma_answer = fields.Integer(string='Answer questions', default=3) karma_edit_own = fields.Integer(string='Edit own posts', default=1) karma_edit_all = fields.Integer(string='Edit all posts', default=300) karma_edit_retag = fields.Integer(string='Change question tags', default=75) karma_close_own = fields.Integer(string='Close own posts', default=100) karma_close_all = fields.Integer(string='Close all posts', default=500) karma_unlink_own = fields.Integer(string='Delete own posts', default=500) karma_unlink_all = fields.Integer(string='Delete all posts', default=1000) karma_tag_create = fields.Integer(string='Create new tags', default=30) karma_upvote = fields.Integer(string='Upvote', default=5) karma_downvote = fields.Integer(string='Downvote', default=50) karma_answer_accept_own = fields.Integer(string='Accept an answer on own questions', default=20) karma_answer_accept_all = fields.Integer(string='Accept an answer to all questions', default=500) karma_comment_own = fields.Integer(string='Comment own posts', default=1) karma_comment_all = fields.Integer(string='Comment all posts', default=1) karma_comment_convert_own = fields.Integer(string='Convert own answers to comments and vice versa', default=50) karma_comment_convert_all = fields.Integer(string='Convert all answers to comments and vice versa', default=500) karma_comment_unlink_own = fields.Integer(string='Unlink own comments', default=50) karma_comment_unlink_all = fields.Integer(string='Unlink all comments', default=500) karma_flag = fields.Integer(string='Flag a post as offensive', default=500) karma_dofollow = fields.Integer(string='Nofollow links', help='If the author has not enough karma, a nofollow attribute is added to links', default=500) karma_editor = fields.Integer(string='Editor Features: image and links', default=30) karma_user_bio = fields.Integer(string='Display detailed user biography', default=750) karma_post = fields.Integer(string='Ask questions without validation', default=100) karma_moderate = fields.Integer(string='Moderate posts', default=1000) @api.depends('post_ids') def _compute_last_post(self): for forum in self: forum.last_post_id = forum.post_ids.search([('forum_id', '=', forum.id), ('parent_id', '=', False), ('state', '=', 'active')], order='create_date desc', limit=1) @api.depends('description') def _compute_teaser(self): for forum in self: if forum.description: desc = forum.description.replace('\n', ' ') if len(forum.description) > 180: forum.teaser = desc[:180] + '...' else: forum.teaser = forum.description else: forum.teaser = "" @api.depends('post_ids.state', 'post_ids.views', 'post_ids.child_count', 'post_ids.favourite_count') def _compute_forum_statistics(self): default_stats = {'total_posts': 0, 'total_views': 0, 'total_answers': 0, 'total_favorites': 0} if not self.ids: self.update(default_stats) return result = {cid: dict(default_stats) for cid in self.ids} read_group_res = self.env['forum.post'].read_group( [('forum_id', 'in', self.ids), ('state', 'in', ('active', 'close')), ('parent_id', '=', False)], ['forum_id', 'views', 'child_count', 'favourite_count'], groupby=['forum_id'], lazy=False) for res_group in read_group_res: cid = res_group['forum_id'][0] result[cid]['total_posts'] += res_group.get('__count', 0) result[cid]['total_views'] += res_group.get('views', 0) result[cid]['total_answers'] += res_group.get('child_count', 0) result[cid]['total_favorites'] += 1 if res_group.get('favourite_count', 0) else 0 for record in self: record.update(result[record.id]) def _compute_count_posts_waiting_validation(self): for forum in self: domain = [('forum_id', '=', forum.id), ('state', '=', 'pending')] forum.count_posts_waiting_validation = self.env['forum.post'].search_count(domain) def _compute_count_flagged_posts(self): for forum in self: domain = [('forum_id', '=', forum.id), ('state', '=', 'flagged')] forum.count_flagged_posts = self.env['forum.post'].search_count(domain) def _set_default_faq(self): for forum in self: forum.faq = self.env['ir.ui.view']._render_template('website_forum.faq_accordion', {"forum": forum}) @api.model_create_multi def create(self, vals_list): forums = super( Forum, self.with_context(mail_create_nolog=True, mail_create_nosubscribe=True) ).create(vals_list) forums._set_default_faq() # will trigger a write and call update_website_count return forums def write(self, vals): if 'privacy' in vals: if not vals['privacy']: # The forum is neither public, neither private, remove menu to avoid conflict self.menu_id.unlink() elif vals['privacy'] == 'public': # The forum is public, the menu must be also public vals['authorized_group_id'] = False self.menu_id.write({'group_ids': [(5, 0, 0)]}) elif vals['privacy'] == 'connected': vals['authorized_group_id'] = False self.menu_id.write({'group_ids': [(6, 0, [self.env.ref('base.group_portal').id, self.env.ref('base.group_user').id])]}) if 'authorized_group_id' in vals and vals['authorized_group_id']: self.menu_id.write({'group_ids': [(6, 0, [vals['authorized_group_id']])]}) res = super(Forum, self).write(vals) if 'active' in vals: # archiving/unarchiving a forum does it on its posts, too self.env['forum.post'].with_context(active_test=False).search([('forum_id', 'in', self.ids)]).write({'active': vals['active']}) if 'active' in vals or 'website_id' in vals: self._update_website_count() return res def unlink(self): self._update_website_count() return super(Forum, self).unlink() @api.model # TODO: Remove me, this is not an `api.model` method def _tag_to_write_vals(self, tags=''): Tag = self.env['forum.tag'] post_tags = [] existing_keep = [] user = self.env.user for tag in (tag for tag in tags.split(',') if tag): if tag.startswith('_'): # it's a new tag # check that not already created meanwhile or maybe excluded by the limit on the search tag_ids = Tag.search([('name', '=', tag[1:]), ('forum_id', '=', self.id)]) if tag_ids: existing_keep.append(int(tag_ids[0])) else: # check if user have Karma needed to create need tag if user.exists() and user.karma >= self.karma_tag_create and len(tag) and len(tag[1:].strip()): post_tags.append((0, 0, {'name': tag[1:], 'forum_id': self.id})) else: existing_keep.append(int(tag)) post_tags.insert(0, [6, 0, existing_keep]) return post_tags def _compute_website_url(self): return '/forum/%s' % (slug(self)) def get_tags_first_char(self): """ get set of first letter of forum tags """ tags = self.env['forum.tag'].search([('forum_id', '=', self.id), ('posts_count', '>', 0)]) return sorted(set([tag.name[0].upper() for tag in tags if len(tag.name)])) def go_to_website(self): self.ensure_one() return { 'type': 'ir.actions.act_url', 'target': 'self', 'url': self._compute_website_url(), } @api.model def _update_website_count(self): for website in self.env['website'].sudo().search([]): website.forums_count = self.env['forum.forum'].sudo().search_count(website.website_domain()) @api.model def _search_get_detail(self, website, order, options): with_description = options['displayDescription'] search_fields = ['name'] fetch_fields = ['id', 'name'] mapping = { 'name': {'name': 'name', 'type': 'text', 'match': True}, 'website_url': {'name': 'website_url', 'type': 'text', 'truncate': False}, } if with_description: search_fields.append('description') fetch_fields.append('description') mapping['description'] = {'name': 'description', 'type': 'text', 'match': True} return { 'model': 'forum.forum', 'base_domain': [website.website_domain()], 'search_fields': search_fields, 'fetch_fields': fetch_fields, 'mapping': mapping, 'icon': 'fa-comments-o', 'order': 'name desc, id desc' if 'name desc' in order else 'name asc, id desc', } def _search_render_results(self, fetch_fields, mapping, icon, limit): results_data = super()._search_render_results(fetch_fields, mapping, icon, limit) for forum, data in zip(self, results_data): data['website_url'] = forum._compute_website_url() return results_data class Post(models.Model): _name = 'forum.post' _description = 'Forum Post' _inherit = [ 'mail.thread', 'website.seo.metadata', 'website.searchable.mixin', ] _order = "is_correct DESC, vote_count DESC, write_date DESC" name = fields.Char('Title') forum_id = fields.Many2one('forum.forum', string='Forum', required=True) content = fields.Html('Content', strip_style=True) plain_content = fields.Text('Plain Content', compute='_get_plain_content', store=True) tag_ids = fields.Many2many('forum.tag', 'forum_tag_rel', 'forum_id', 'forum_tag_id', string='Tags') state = fields.Selection([('active', 'Active'), ('pending', 'Waiting Validation'), ('close', 'Closed'), ('offensive', 'Offensive'), ('flagged', 'Flagged')], string='Status', default='active') views = fields.Integer('Views', default=0, readonly=True, copy=False) active = fields.Boolean('Active', default=True) website_message_ids = fields.One2many(domain=lambda self: [('model', '=', self._name), ('message_type', 'in', ['email', 'comment'])]) website_id = fields.Many2one(related='forum_id.website_id', readonly=True) # history create_date = fields.Datetime('Asked on', index=True, readonly=True) create_uid = fields.Many2one('res.users', string='Created by', index=True, readonly=True) write_date = fields.Datetime('Updated on', index=True, readonly=True) bump_date = fields.Datetime('Bumped on', readonly=True, help="Technical field allowing to bump a question. Writing on this field will trigger " "a write on write_date and therefore bump the post. Directly writing on write_date " "is currently not supported and this field is a workaround.") write_uid = fields.Many2one('res.users', string='Updated by', index=True, readonly=True) relevancy = fields.Float('Relevance', compute="_compute_relevancy", store=True) # vote vote_ids = fields.One2many('forum.post.vote', 'post_id', string='Votes') user_vote = fields.Integer('My Vote', compute='_get_user_vote') vote_count = fields.Integer('Total Votes', compute='_get_vote_count', store=True) # favorite favourite_ids = fields.Many2many('res.users', string='Favourite') user_favourite = fields.Boolean('Is Favourite', compute='_get_user_favourite') favourite_count = fields.Integer('Favorite', compute='_get_favorite_count', store=True) # hierarchy is_correct = fields.Boolean('Correct', help='Correct answer or answer accepted') parent_id = fields.Many2one('forum.post', string='Question', ondelete='cascade', readonly=True, index=True) self_reply = fields.Boolean('Reply to own question', compute='_is_self_reply', store=True) child_ids = fields.One2many('forum.post', 'parent_id', string='Post Answers', domain=lambda self: [('forum_id', 'in', self.forum_id.ids)]) child_count = fields.Integer('Answers', compute='_get_child_count', store=True) uid_has_answered = fields.Boolean('Has Answered', compute='_get_uid_has_answered') has_validated_answer = fields.Boolean('Is answered', compute='_get_has_validated_answer', store=True) # offensive moderation tools flag_user_id = fields.Many2one('res.users', string='Flagged by') moderator_id = fields.Many2one('res.users', string='Reviewed by', readonly=True) # closing closed_reason_id = fields.Many2one('forum.post.reason', string='Reason', copy=False) closed_uid = fields.Many2one('res.users', string='Closed by', index=True, readonly=True, copy=False) closed_date = fields.Datetime('Closed on', readonly=True, copy=False) # karma calculation and access karma_accept = fields.Integer('Convert comment to answer', compute='_get_post_karma_rights', compute_sudo=False) karma_edit = fields.Integer('Karma to edit', compute='_get_post_karma_rights', compute_sudo=False) karma_close = fields.Integer('Karma to close', compute='_get_post_karma_rights', compute_sudo=False) karma_unlink = fields.Integer('Karma to unlink', compute='_get_post_karma_rights', compute_sudo=False) karma_comment = fields.Integer('Karma to comment', compute='_get_post_karma_rights', compute_sudo=False) karma_comment_convert = fields.Integer('Karma to convert comment to answer', compute='_get_post_karma_rights', compute_sudo=False) karma_flag = fields.Integer('Flag a post as offensive', compute='_get_post_karma_rights', compute_sudo=False) can_ask = fields.Boolean('Can Ask', compute='_get_post_karma_rights', compute_sudo=False) can_answer = fields.Boolean('Can Answer', compute='_get_post_karma_rights', compute_sudo=False) can_accept = fields.Boolean('Can Accept', compute='_get_post_karma_rights', compute_sudo=False) can_edit = fields.Boolean('Can Edit', compute='_get_post_karma_rights', compute_sudo=False) can_close = fields.Boolean('Can Close', compute='_get_post_karma_rights', compute_sudo=False) can_unlink = fields.Boolean('Can Unlink', compute='_get_post_karma_rights', compute_sudo=False) can_upvote = fields.Boolean('Can Upvote', compute='_get_post_karma_rights', compute_sudo=False) can_downvote = fields.Boolean('Can Downvote', compute='_get_post_karma_rights', compute_sudo=False) can_comment = fields.Boolean('Can Comment', compute='_get_post_karma_rights', compute_sudo=False) can_comment_convert = fields.Boolean('Can Convert to Comment', compute='_get_post_karma_rights', compute_sudo=False) can_view = fields.Boolean('Can View', compute='_get_post_karma_rights', search='_search_can_view', compute_sudo=False) can_display_biography = fields.Boolean("Is the author's biography visible from his post", compute='_get_post_karma_rights', compute_sudo=False) can_post = fields.Boolean('Can Automatically be Validated', compute='_get_post_karma_rights', compute_sudo=False) can_flag = fields.Boolean('Can Flag', compute='_get_post_karma_rights', compute_sudo=False) can_moderate = fields.Boolean('Can Moderate', compute='_get_post_karma_rights', compute_sudo=False) def _search_can_view(self, operator, value): if operator not in ('=', '!=', '<>'): raise ValueError('Invalid operator: %s' % (operator,)) if not value: operator = operator == "=" and '!=' or '=' value = True user = self.env.user # Won't impact sitemap, search() in converter is forced as public user if self.env.is_admin(): return [(1, '=', 1)] req = """ SELECT p.id FROM forum_post p LEFT JOIN res_users u ON p.create_uid = u.id LEFT JOIN forum_forum f ON p.forum_id = f.id WHERE (p.create_uid = %s and f.karma_close_own <= %s) or (p.create_uid != %s and f.karma_close_all <= %s) or ( u.karma > 0 and (p.active or p.create_uid = %s) ) """ op = operator == "=" and "inselect" or "not inselect" # don't use param named because orm will add other param (test_active, ...) return [('id', op, (req, (user.id, user.karma, user.id, user.karma, user.id)))] @api.depends('content') def _get_plain_content(self): for post in self: post.plain_content = tools.html2plaintext(post.content)[0:500] if post.content else False @api.depends('vote_count', 'forum_id.relevancy_post_vote', 'forum_id.relevancy_time_decay') def _compute_relevancy(self): for post in self: if post.create_date: days = (datetime.today() - post.create_date).days post.relevancy = math.copysign(1, post.vote_count) * (abs(post.vote_count - 1) ** post.forum_id.relevancy_post_vote / (days + 2) ** post.forum_id.relevancy_time_decay) else: post.relevancy = 0 def _get_user_vote(self): votes = self.env['forum.post.vote'].search_read([('post_id', 'in', self._ids), ('user_id', '=', self._uid)], ['vote', 'post_id']) mapped_vote = dict([(v['post_id'][0], v['vote']) for v in votes]) for vote in self: vote.user_vote = mapped_vote.get(vote.id, 0) @api.depends('vote_ids.vote') def _get_vote_count(self): read_group_res = self.env['forum.post.vote'].read_group([('post_id', 'in', self._ids)], ['post_id', 'vote'], ['post_id', 'vote'], lazy=False) result = dict.fromkeys(self._ids, 0) for data in read_group_res: result[data['post_id'][0]] += data['__count'] * int(data['vote']) for post in self: post.vote_count = result[post.id] def _get_user_favourite(self): for post in self: post.user_favourite = post._uid in post.favourite_ids.ids @api.depends('favourite_ids') def _get_favorite_count(self): for post in self: post.favourite_count = len(post.favourite_ids) @api.depends('create_uid', 'parent_id') def _is_self_reply(self): for post in self: post.self_reply = post.parent_id.create_uid.id == post._uid @api.depends('child_ids') def _get_child_count(self): for post in self: post.child_count = len(post.child_ids) def _get_uid_has_answered(self): for post in self: post.uid_has_answered = post._uid in post.child_ids.create_uid.ids @api.depends('child_ids.is_correct') def _get_has_validated_answer(self): for post in self: post.has_validated_answer = any(answer.is_correct for answer in post.child_ids) @api.depends_context('uid') def _get_post_karma_rights(self): user = self.env.user is_admin = self.env.is_admin() # sudoed recordset instead of individual posts so values can be # prefetched in bulk for post, post_sudo in zip(self, self.sudo()): is_creator = post.create_uid == user post.karma_accept = post.forum_id.karma_answer_accept_own if post.parent_id.create_uid == user else post.forum_id.karma_answer_accept_all post.karma_edit = post.forum_id.karma_edit_own if is_creator else post.forum_id.karma_edit_all post.karma_close = post.forum_id.karma_close_own if is_creator else post.forum_id.karma_close_all post.karma_unlink = post.forum_id.karma_unlink_own if is_creator else post.forum_id.karma_unlink_all post.karma_comment = post.forum_id.karma_comment_own if is_creator else post.forum_id.karma_comment_all post.karma_comment_convert = post.forum_id.karma_comment_convert_own if is_creator else post.forum_id.karma_comment_convert_all post.karma_flag = post.forum_id.karma_flag post.can_ask = is_admin or user.karma >= post.forum_id.karma_ask post.can_answer = is_admin or user.karma >= post.forum_id.karma_answer post.can_accept = is_admin or user.karma >= post.karma_accept post.can_edit = is_admin or user.karma >= post.karma_edit post.can_close = is_admin or user.karma >= post.karma_close post.can_unlink = is_admin or user.karma >= post.karma_unlink post.can_upvote = is_admin or user.karma >= post.forum_id.karma_upvote or post.user_vote == -1 post.can_downvote = is_admin or user.karma >= post.forum_id.karma_downvote or post.user_vote == 1 post.can_comment = is_admin or user.karma >= post.karma_comment post.can_comment_convert = is_admin or user.karma >= post.karma_comment_convert post.can_view = is_admin or user.karma >= post.karma_close or (post_sudo.create_uid.karma > 0 and (post_sudo.active or post_sudo.create_uid == user)) post.can_display_biography = is_admin or post_sudo.create_uid.karma >= post.forum_id.karma_user_bio post.can_post = is_admin or user.karma >= post.forum_id.karma_post post.can_flag = is_admin or user.karma >= post.forum_id.karma_flag post.can_moderate = is_admin or user.karma >= post.forum_id.karma_moderate def _update_content(self, content, forum_id): forum = self.env['forum.forum'].browse(forum_id) if content and self.env.user.karma < forum.karma_dofollow: for match in re.findall(r'<a\s.*href=".*?">', content): match = re.escape(match) # replace parenthesis or special char in regex content = re.sub(match, match[:3] + 'rel="nofollow" ' + match[3:], content) if self.env.user.karma < forum.karma_editor: filter_regexp = r'(<img.*?>)|(<a[^>]*?href[^>]*?>)|(<[a-z|A-Z]+[^>]*style\s*=\s*[\'"][^\'"]*\s*background[^:]*:[^url;]*url)' content_match = re.search(filter_regexp, content, re.I) if content_match: raise AccessError(_('%d karma required to post an image or link.', forum.karma_editor)) return content def _default_website_meta(self): res = super(Post, self)._default_website_meta() res['default_opengraph']['og:title'] = res['default_twitter']['twitter:title'] = self.name res['default_opengraph']['og:description'] = res['default_twitter']['twitter:description'] = self.plain_content res['default_opengraph']['og:image'] = res['default_twitter']['twitter:image'] = self.env['website'].image_url(self.create_uid, 'image_1024') res['default_twitter']['twitter:card'] = 'summary' res['default_meta_description'] = self.plain_content return res @api.constrains('parent_id') def _check_parent_id(self): if not self._check_recursion(): raise ValidationError(_('You cannot create recursive forum posts.')) @api.model def create(self, vals): if 'content' in vals and vals.get('forum_id'): vals['content'] = self._update_content(vals['content'], vals['forum_id']) post = super(Post, self.with_context(mail_create_nolog=True)).create(vals) # deleted or closed questions if post.parent_id and (post.parent_id.state == 'close' or post.parent_id.active is False): raise UserError(_('Posting answer on a [Deleted] or [Closed] question is not possible.')) # karma-based access if not post.parent_id and not post.can_ask: raise AccessError(_('%d karma required to create a new question.', post.forum_id.karma_ask)) elif post.parent_id and not post.can_answer: raise AccessError(_('%d karma required to answer a question.', post.forum_id.karma_answer)) if not post.parent_id and not post.can_post: post.sudo().state = 'pending' # add karma for posting new questions if not post.parent_id and post.state == 'active': self.env.user.sudo().add_karma(post.forum_id.karma_gen_question_new) post.post_notification() return post @api.model def _get_mail_message_access(self, res_ids, operation, model_name=None): # XDO FIXME: to be correctly fixed with new _get_mail_message_access and filter access rule if operation in ('write', 'unlink') and (not model_name or model_name == 'forum.post'): # Make sure only author or moderator can edit/delete messages for post in self.browse(res_ids): if not post.can_edit: raise AccessError(_('%d karma required to edit a post.', post.karma_edit)) return super(Post, self)._get_mail_message_access(res_ids, operation, model_name=model_name) def write(self, vals): trusted_keys = ['active', 'is_correct', 'tag_ids'] # fields where security is checked manually if 'content' in vals: vals['content'] = self._update_content(vals['content'], self.forum_id.id) tag_ids = False if 'tag_ids' in vals: tag_ids = set(self.new({'tag_ids': vals['tag_ids']}).tag_ids.ids) for post in self: if 'state' in vals: if vals['state'] in ['active', 'close']: if not post.can_close: raise AccessError(_('%d karma required to close or reopen a post.', post.karma_close)) trusted_keys += ['state', 'closed_uid', 'closed_date', 'closed_reason_id'] elif vals['state'] == 'flagged': if not post.can_flag: raise AccessError(_('%d karma required to flag a post.', post.forum_id.karma_flag)) trusted_keys += ['state', 'flag_user_id'] if 'active' in vals: if not post.can_unlink: raise AccessError(_('%d karma required to delete or reactivate a post.', post.karma_unlink)) if 'is_correct' in vals: if not post.can_accept: raise AccessError(_('%d karma required to accept or refuse an answer.', post.karma_accept)) # update karma except for self-acceptance mult = 1 if vals['is_correct'] else -1 if vals['is_correct'] != post.is_correct and post.create_uid.id != self._uid: post.create_uid.sudo().add_karma(post.forum_id.karma_gen_answer_accepted * mult) self.env.user.sudo().add_karma(post.forum_id.karma_gen_answer_accept * mult) if tag_ids: if set(post.tag_ids.ids) != tag_ids and self.env.user.karma < post.forum_id.karma_edit_retag: raise AccessError(_('%d karma required to retag.', post.forum_id.karma_edit_retag)) if any(key not in trusted_keys for key in vals) and not post.can_edit: raise AccessError(_('%d karma required to edit a post.', post.karma_edit)) res = super(Post, self).write(vals) # if post content modify, notify followers if 'content' in vals or 'name' in vals: for post in self: if post.parent_id: body, subtype_xmlid = _('Answer Edited'), 'website_forum.mt_answer_edit' obj_id = post.parent_id else: body, subtype_xmlid = _('Question Edited'), 'website_forum.mt_question_edit' obj_id = post obj_id.message_post(body=body, subtype_xmlid=subtype_xmlid) if 'active' in vals: answers = self.env['forum.post'].with_context(active_test=False).search([('parent_id', 'in', self.ids)]) if answers: answers.write({'active': vals['active']}) return res def post_notification(self): for post in self: tag_partners = post.tag_ids.sudo().mapped('message_partner_ids') if post.state == 'active' and post.parent_id: post.parent_id.message_post_with_view( 'website_forum.forum_post_template_new_answer', subject=_('Re: %s', post.parent_id.name), partner_ids=[(4, p.id) for p in tag_partners], subtype_id=self.env['ir.model.data']._xmlid_to_res_id('website_forum.mt_answer_new')) elif post.state == 'active' and not post.parent_id: post.message_post_with_view( 'website_forum.forum_post_template_new_question', subject=post.name, partner_ids=[(4, p.id) for p in tag_partners], subtype_id=self.env['ir.model.data']._xmlid_to_res_id('website_forum.mt_question_new')) elif post.state == 'pending' and not post.parent_id: # TDE FIXME: in master, you should probably use a subtype; # however here we remove subtype but set partner_ids partners = post.sudo().message_partner_ids | tag_partners partners = partners.filtered(lambda partner: partner.user_ids and any(user.karma >= post.forum_id.karma_moderate for user in partner.user_ids)) post.message_post_with_view( 'website_forum.forum_post_template_validation', subject=post.name, partner_ids=partners.ids, subtype_id=self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note')) return True def reopen(self): if any(post.parent_id or post.state != 'close' for post in self): return False reason_offensive = self.env.ref('website_forum.reason_7') reason_spam = self.env.ref('website_forum.reason_8') for post in self: if post.closed_reason_id in (reason_offensive, reason_spam): _logger.info('Upvoting user <%s>, reopening spam/offensive question', post.create_uid) karma = post.forum_id.karma_gen_answer_flagged if post.closed_reason_id == reason_spam: # If first post, increase the karma to add count_post = post.search_count([('parent_id', '=', False), ('forum_id', '=', post.forum_id.id), ('create_uid', '=', post.create_uid.id)]) if count_post == 1: karma *= 10 post.create_uid.sudo().add_karma(karma * -1) self.sudo().write({'state': 'active'}) def close(self, reason_id): if any(post.parent_id for post in self): return False reason_offensive = self.env.ref('website_forum.reason_7').id reason_spam = self.env.ref('website_forum.reason_8').id if reason_id in (reason_offensive, reason_spam): for post in self: _logger.info('Downvoting user <%s> for posting spam/offensive contents', post.create_uid) karma = post.forum_id.karma_gen_answer_flagged if reason_id == reason_spam: # If first post, increase the karma to remove count_post = post.search_count([('parent_id', '=', False), ('forum_id', '=', post.forum_id.id), ('create_uid', '=', post.create_uid.id)]) if count_post == 1: karma *= 10 post.create_uid.sudo().add_karma(karma) self.write({ 'state': 'close', 'closed_uid': self._uid, 'closed_date': datetime.today().strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT), 'closed_reason_id': reason_id, }) return True def validate(self): for post in self: if not post.can_moderate: raise AccessError(_('%d karma required to validate a post.', post.forum_id.karma_moderate)) # if state == pending, no karma previously added for the new question if post.state == 'pending': post.create_uid.sudo().add_karma(post.forum_id.karma_gen_question_new) post.write({ 'state': 'active', 'active': True, 'moderator_id': self.env.user.id, }) post.post_notification() return True def refuse(self): for post in self: if not post.can_moderate: raise AccessError(_('%d karma required to refuse a post.', post.forum_id.karma_moderate)) post.moderator_id = self.env.user return True def flag(self): res = [] for post in self: if not post.can_flag: raise AccessError(_('%d karma required to flag a post.', post.forum_id.karma_flag)) if post.state == 'flagged': res.append({'error': 'post_already_flagged'}) elif post.state == 'active': # TODO: potential performance bottleneck, can be batched post.write({ 'state': 'flagged', 'flag_user_id': self.env.user.id, }) res.append( post.can_moderate and {'success': 'post_flagged_moderator'} or {'success': 'post_flagged_non_moderator'} ) else: res.append({'error': 'post_non_flaggable'}) return res def mark_as_offensive(self, reason_id): for post in self: if not post.can_moderate: raise AccessError(_('%d karma required to mark a post as offensive.', post.forum_id.karma_moderate)) # remove some karma _logger.info('Downvoting user <%s> for posting spam/offensive contents', post.create_uid) post.create_uid.sudo().add_karma(post.forum_id.karma_gen_answer_flagged) # TODO: potential bottleneck, could be done in batch post.write({ 'state': 'offensive', 'moderator_id': self.env.user.id, 'closed_date': fields.Datetime.now(), 'closed_reason_id': reason_id, 'active': False, }) return True def mark_as_offensive_batch(self, key, values): spams = self.browse() if key == 'create_uid': spams = self.filtered(lambda x: x.create_uid.id in values) elif key == 'country_id': spams = self.filtered(lambda x: x.create_uid.country_id.id in values) elif key == 'post_id': spams = self.filtered(lambda x: x.id in values) reason_id = self.env.ref('website_forum.reason_8').id _logger.info('User %s marked as spams (in batch): %s' % (self.env.uid, spams)) return spams.mark_as_offensive(reason_id) @api.ondelete(at_uninstall=False) def _unlink_if_enough_karma(self): for post in self: if not post.can_unlink: raise AccessError(_('%d karma required to unlink a post.', post.karma_unlink)) def unlink(self): # if unlinking an answer with accepted answer: remove provided karma for post in self: if post.is_correct: post.create_uid.sudo().add_karma(post.forum_id.karma_gen_answer_accepted * -1) self.env.user.sudo().add_karma(post.forum_id.karma_gen_answer_accepted * -1) return super(Post, self).unlink() def bump(self): """ Bump a question: trigger a write_date by writing on a dummy bump_date field. One cannot bump a question more than once every 10 days. """ self.ensure_one() if self.forum_id.allow_bump and not self.child_ids and (datetime.today() - datetime.strptime(self.write_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)).days > 9: # write through super to bypass karma; sudo to allow public user to bump any post return self.sudo().write({'bump_date': fields.Datetime.now()}) return False def vote(self, upvote=True): self.ensure_one() Vote = self.env['forum.post.vote'] existing_vote = Vote.search([('post_id', '=', self.id), ('user_id', '=', self._uid)]) new_vote_value = '1' if upvote else '-1' if existing_vote: if upvote: new_vote_value = '0' if existing_vote.vote == '-1' else '1' else: new_vote_value = '0' if existing_vote.vote == '1' else '-1' existing_vote.vote = new_vote_value else: Vote.create({'post_id': self.id, 'vote': new_vote_value}) return {'vote_count': self.vote_count, 'user_vote': new_vote_value} def convert_answer_to_comment(self): """ Tools to convert an answer (forum.post) to a comment (mail.message). The original post is unlinked and a new comment is posted on the question using the post create_uid as the comment's author. """ self.ensure_one() if not self.parent_id: return self.env['mail.message'] # karma-based action check: use the post field that computed own/all value if not self.can_comment_convert: raise AccessError(_('%d karma required to convert an answer to a comment.', self.karma_comment_convert)) # post the message question = self.parent_id self_sudo = self.sudo() values = { 'author_id': self_sudo.create_uid.partner_id.id, # use sudo here because of access to res.users model 'email_from': self_sudo.create_uid.email_formatted, # use sudo here because of access to res.users model 'body': tools.html_sanitize(self.content, sanitize_attributes=True, strip_style=True, strip_classes=True), 'message_type': 'comment', 'subtype_xmlid': 'mail.mt_comment', 'date': self.create_date, } # done with the author user to have create_uid correctly set new_message = question.with_user(self_sudo.create_uid.id).with_context(mail_create_nosubscribe=True).sudo().message_post(**values).sudo(False) # unlink the original answer, using SUPERUSER_ID to avoid karma issues self.sudo().unlink() return new_message @api.model def convert_comment_to_answer(self, message_id, default=None): """ Tool to convert a comment (mail.message) into an answer (forum.post). The original comment is unlinked and a new answer from the comment's author is created. Nothing is done if the comment's author already answered the question. """ comment = self.env['mail.message'].sudo().browse(message_id) post = self.browse(comment.res_id) if not comment.author_id or not comment.author_id.user_ids: # only comment posted by users can be converted return False # karma-based action check: must check the message's author to know if own / all is_author = comment.author_id.id == self.env.user.partner_id.id karma_own = post.forum_id.karma_comment_convert_own karma_all = post.forum_id.karma_comment_convert_all karma_convert = is_author and karma_own or karma_all can_convert = self.env.user.karma >= karma_convert if not can_convert: if is_author and karma_own < karma_all: raise AccessError(_('%d karma required to convert your comment to an answer.', karma_own)) else: raise AccessError(_('%d karma required to convert a comment to an answer.', karma_all)) # check the message's author has not already an answer question = post.parent_id if post.parent_id else post post_create_uid = comment.author_id.user_ids[0] if any(answer.create_uid.id == post_create_uid.id for answer in question.child_ids): return False # create the new post post_values = { 'forum_id': question.forum_id.id, 'content': comment.body, 'parent_id': question.id, 'name': _('Re: %s') % (question.name or ''), } # done with the author user to have create_uid correctly set new_post = self.with_user(post_create_uid).sudo().create(post_values).sudo(False) # delete comment comment.unlink() return new_post def unlink_comment(self, message_id): result = [] for post in self: user = self.env.user comment = self.env['mail.message'].sudo().browse(message_id) if not comment.model == 'forum.post' or not comment.res_id == post.id: result.append(False) continue # karma-based action check: must check the message's author to know if own or all karma_unlink = ( comment.author_id.id == user.partner_id.id and post.forum_id.karma_comment_unlink_own or post.forum_id.karma_comment_unlink_all ) can_unlink = user.karma >= karma_unlink if not can_unlink: raise AccessError(_('%d karma required to unlink a comment.', karma_unlink)) result.append(comment.unlink()) return result def _set_viewed(self): self.ensure_one() return sql.increment_field_skiplock(self, 'views') def get_access_action(self, access_uid=None): """ Instead of the classic form view, redirect to the post on the website directly """ self.ensure_one() return { 'type': 'ir.actions.act_url', 'url': '/forum/%s/%s' % (self.forum_id.id, self.id), 'target': 'self', 'target_type': 'public', 'res_id': self.id, } def _notify_get_groups(self, msg_vals=None): """ Add access button to everyone if the document is active. """ groups = super(Post, self)._notify_get_groups(msg_vals=msg_vals) if self.state == 'active': for group_name, group_method, group_data in groups: group_data['has_button_access'] = True return groups @api.returns('mail.message', lambda value: value.id) def message_post(self, *, message_type='notification', **kwargs): if self.ids and message_type == 'comment': # user comments have a restriction on karma # add followers of comments on the parent post if self.parent_id: partner_ids = kwargs.get('partner_ids', []) comment_subtype = self.sudo().env.ref('mail.mt_comment') question_followers = self.env['mail.followers'].sudo().search([ ('res_model', '=', self._name), ('res_id', '=', self.parent_id.id), ('partner_id', '!=', False), ]).filtered(lambda fol: comment_subtype in fol.subtype_ids).mapped('partner_id') partner_ids += question_followers.ids kwargs['partner_ids'] = partner_ids self.ensure_one() if not self.can_comment: raise AccessError(_('%d karma required to comment.', self.karma_comment)) if not kwargs.get('record_name') and self.parent_id: kwargs['record_name'] = self.parent_id.name return super(Post, self).message_post(message_type=message_type, **kwargs) def _notify_record_by_inbox(self, message, recipients_data, msg_vals=False, **kwargs): """ Override to avoid keeping all notified recipients of a comment. We avoid tracking needaction on post comments. Only emails should be sufficient. """ if msg_vals.get('message_type', message.message_type) == 'comment': return return super(Post, self)._notify_record_by_inbox(message, recipients_data, msg_vals=msg_vals, **kwargs) def _compute_website_url(self): return '/forum/{forum}/{post}{anchor}'.format( forum=slug(self.forum_id), post=slug(self), anchor=self.parent_id and '#answer_%d' % self.id or '' ) def go_to_website(self): self.ensure_one() return { 'type': 'ir.actions.act_url', 'target': 'self', 'url': self._compute_website_url(), } @api.model def _search_get_detail(self, website, order, options): with_description = options['displayDescription'] with_date = options['displayDetail'] search_fields = ['name'] fetch_fields = ['id', 'name'] mapping = { 'name': {'name': 'name', 'type': 'text', 'match': True}, 'website_url': {'name': 'website_url', 'type': 'text', 'truncate': False}, } domain = website.website_domain() domain += [('parent_id', '=', False), ('state', '=', 'active'), ('can_view', '=', True)] forum = options.get('forum') if forum: domain += [('forum_id', '=', unslug(forum)[1])] tags = options.get('tag') if tags: domain += [('tag_ids', 'in', [unslug(tag)[1] for tag in tags.split(',')])] filters = options.get('filters') if filters == 'unanswered': domain += [('child_ids', '=', False)] elif filters == 'solved': domain += [('has_validated_answer', '=', True)] elif filters == 'unsolved': domain += [('has_validated_answer', '=', False)] user = self.env.user my = options.get('my') if my == 'mine': domain += [('create_uid', '=', user.id)] elif my == 'followed': domain += [('message_partner_ids', '=', user.partner_id.id)] elif my == 'tagged': domain += [('tag_ids.message_partner_ids', '=', user.partner_id.id)] elif my == 'favourites': domain += [('favourite_ids', '=', user.id)] # 'sorting' from the form's "Order by" overrides order during auto-completion order = options.get('sorting', order) if 'is_published' in order: parts = [part for part in order.split(',') if 'is_published' not in part] order = ','.join(parts) if with_description: search_fields.append('content') fetch_fields.append('content') mapping['description'] = {'name': 'content', 'type': 'text', 'html': True, 'match': True} if with_date: fetch_fields.append('write_date') mapping['detail'] = {'name': 'date', 'type': 'html'} return { 'model': 'forum.post', 'base_domain': [domain], 'search_fields': search_fields, 'fetch_fields': fetch_fields, 'mapping': mapping, 'icon': 'fa-comment-o', 'order': order, } def _search_render_results(self, fetch_fields, mapping, icon, limit): with_date = 'detail' in mapping results_data = super()._search_render_results(fetch_fields, mapping, icon, limit) for post, data in zip(self, results_data): data['website_url'] = post._compute_website_url() if with_date: data['date'] = self.env['ir.qweb.field.date'].record_to_html(post, 'write_date', {}) return results_data class PostReason(models.Model): _name = "forum.post.reason" _description = "Post Closing Reason" _order = 'name' name = fields.Char(string='Closing Reason', required=True, translate=True) reason_type = fields.Selection([('basic', 'Basic'), ('offensive', 'Offensive')], string='Reason Type', default='basic') class Vote(models.Model): _name = 'forum.post.vote' _description = 'Post Vote' _order = 'create_date desc, id desc' post_id = fields.Many2one('forum.post', string='Post', ondelete='cascade', required=True) user_id = fields.Many2one('res.users', string='User', required=True, default=lambda self: self._uid) vote = fields.Selection([('1', '1'), ('-1', '-1'), ('0', '0')], string='Vote', required=True, default='1') create_date = fields.Datetime('Create Date', index=True, readonly=True) forum_id = fields.Many2one('forum.forum', string='Forum', related="post_id.forum_id", store=True, readonly=False) recipient_id = fields.Many2one('res.users', string='To', related="post_id.create_uid", store=True, readonly=False) _sql_constraints = [ ('vote_uniq', 'unique (post_id, user_id)', "Vote already exists !"), ] def _get_karma_value(self, old_vote, new_vote, up_karma, down_karma): _karma_upd = { '-1': {'-1': 0, '0': -1 * down_karma, '1': -1 * down_karma + up_karma}, '0': {'-1': 1 * down_karma, '0': 0, '1': up_karma}, '1': {'-1': -1 * up_karma + down_karma, '0': -1 * up_karma, '1': 0} } return _karma_upd[old_vote][new_vote] @api.model def create(self, vals): # can't modify owner of a vote if not self.env.is_admin(): vals.pop('user_id', None) vote = super(Vote, self).create(vals) vote._check_general_rights() vote._check_karma_rights(vote.vote == '1') # karma update vote._vote_update_karma('0', vote.vote) return vote def write(self, values): # can't modify owner of a vote if not self.env.is_admin(): values.pop('user_id', None) for vote in self: vote._check_general_rights(values) if 'vote' in values: if (values['vote'] == '1' or vote.vote == '-1' and values['vote'] == '0'): upvote = True elif (values['vote'] == '-1' or vote.vote == '1' and values['vote'] == '0'): upvote = False vote._check_karma_rights(upvote) # karma update vote._vote_update_karma(vote.vote, values['vote']) res = super(Vote, self).write(values) return res def _check_general_rights(self, vals={}): post = self.post_id if vals.get('post_id'): post = self.env['forum.post'].browse(vals.get('post_id')) if not self.env.is_admin(): # own post check if self._uid == post.create_uid.id: raise UserError(_('It is not allowed to vote for its own post.')) # own vote check if self._uid != self.user_id.id: raise UserError(_('It is not allowed to modify someone else\'s vote.')) def _check_karma_rights(self, upvote=None): # karma check if upvote and not self.post_id.can_upvote: raise AccessError(_('%d karma required to upvote.', self.post_id.forum_id.karma_upvote)) elif not upvote and not self.post_id.can_downvote: raise AccessError(_('%d karma required to downvote.', self.post_id.forum_id.karma_downvote)) def _vote_update_karma(self, old_vote, new_vote): if self.post_id.parent_id: karma_value = self._get_karma_value(old_vote, new_vote, self.forum_id.karma_gen_answer_upvote, self.forum_id.karma_gen_answer_downvote) else: karma_value = self._get_karma_value(old_vote, new_vote, self.forum_id.karma_gen_question_upvote, self.forum_id.karma_gen_question_downvote) self.recipient_id.sudo().add_karma(karma_value) class Tags(models.Model): _name = "forum.tag" _description = "Forum Tag" _inherit = ['mail.thread', 'website.seo.metadata'] name = fields.Char('Name', required=True) forum_id = fields.Many2one('forum.forum', string='Forum', required=True) post_ids = fields.Many2many( 'forum.post', 'forum_tag_rel', 'forum_tag_id', 'forum_id', string='Posts', domain=[('state', '=', 'active')]) posts_count = fields.Integer('Number of Posts', compute='_get_posts_count', store=True) _sql_constraints = [ ('name_uniq', 'unique (name, forum_id)', "Tag name already exists !"), ] @api.depends("post_ids", "post_ids.tag_ids", "post_ids.state", "post_ids.active") def _get_posts_count(self): for tag in self: tag.posts_count = len(tag.post_ids) # state filter is in field domain @api.model def create(self, vals): forum = self.env['forum.forum'].browse(vals.get('forum_id')) if self.env.user.karma < forum.karma_tag_create: raise AccessError(_('%d karma required to create a new Tag.', forum.karma_tag_create)) return super(Tags, self.with_context(mail_create_nolog=True, mail_create_nosubscribe=True)).create(vals)
50.676672
59,089
1,020
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class Users(models.Model): _inherit = 'res.users' create_date = fields.Datetime('Create Date', readonly=True, index=True) forum_waiting_posts_count = fields.Integer('Waiting post', compute="_get_user_waiting_post") def _get_user_waiting_post(self): for user in self: Post = self.env['forum.post'] domain = [('parent_id', '=', False), ('state', '=', 'pending'), ('create_uid', '=', user.id)] user.forum_waiting_posts_count = Post.search_count(domain) # Wrapper for call_kw with inherits def open_website_url(self): return self.mapped('partner_id').open_website_url() def get_gamification_redirection_data(self): res = super(Users, self).get_gamification_redirection_data() res.append({ 'url': '/forum', 'label': 'See our Forum' }) return res
35.172414
1,020
1,723
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, _ from odoo.addons.http_routing.models.ir_http import url_for class Website(models.Model): _inherit = 'website' @api.model def get_default_forum_count(self): self.forums_count = self.env['forum.forum'].search_count(self.website_domain()) forums_count = fields.Integer(readonly=True, default=get_default_forum_count) def get_suggested_controllers(self): suggested_controllers = super(Website, self).get_suggested_controllers() suggested_controllers.append((_('Forum'), url_for('/forum'), 'website_forum')) return suggested_controllers def configurator_get_footer_links(self): links = super().configurator_get_footer_links() links.append({'text': _("Forum"), 'href': '/forum'}) return links def configurator_set_menu_links(self, menu_company, module_data): # Forum menu should only be a footer link, not a menu forum_menu = self.env['website.menu'].search([('url', '=', '/forum'), ('website_id', '=', self.id)]) forum_menu.unlink() super().configurator_set_menu_links(menu_company, module_data) def _search_get_details(self, search_type, order, options): result = super()._search_get_details(search_type, order, options) if search_type in ['forums', 'forums_only', 'all']: result.append(self.env['forum.forum']._search_get_detail(self, order, options)) if search_type in ['forums', 'forum_posts_only', 'all']: result.append(self.env['forum.post']._search_get_detail(self, order, options)) return result
44.179487
1,723
343
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class Challenge(models.Model): _inherit = 'gamification.challenge' challenge_category = fields.Selection(selection_add=[ ('forum', 'Website / Forum') ], ondelete={'forum': 'set default'})
28.583333
343
33,445
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import lxml import requests import logging import werkzeug.exceptions import werkzeug.urls import werkzeug.wrappers from datetime import datetime from odoo import http, tools, _ from odoo.addons.http_routing.models.ir_http import slug from odoo.addons.website.models.ir_http import sitemap_qs2dom from odoo.addons.website_profile.controllers.main import WebsiteProfile from odoo.addons.portal.controllers.portal import _build_url_w_params from odoo.exceptions import UserError from odoo.http import request from odoo.osv import expression _logger = logging.getLogger(__name__) class WebsiteForum(WebsiteProfile): _post_per_page = 10 _user_per_page = 30 def _prepare_user_values(self, **kwargs): values = super(WebsiteForum, self)._prepare_user_values(**kwargs) values['forum_welcome_message'] = request.httprequest.cookies.get('forum_welcome_message', False) values.update({ 'header': kwargs.get('header', dict()), 'searches': kwargs.get('searches', dict()), }) if kwargs.get('forum'): values['forum'] = kwargs.get('forum') elif kwargs.get('forum_id'): values['forum'] = request.env['forum.forum'].browse(kwargs.pop('forum_id')) return values # Forum # -------------------------------------------------- @http.route(['/forum'], type='http', auth="public", website=True, sitemap=True) def forum(self, **kwargs): domain = request.website.website_domain() forums = request.env['forum.forum'].search(domain) if len(forums) == 1: return request.redirect('/forum/%s' % slug(forums[0]), code=302) return request.render("website_forum.forum_all", { 'forums': forums }) @http.route('/forum/new', type='json', auth="user", methods=['POST'], website=True) def forum_create(self, forum_name="New Forum", forum_mode="questions", forum_privacy="public", forum_privacy_group=False, add_menu=False): forum = { 'name': forum_name, 'mode': forum_mode, 'privacy': forum_privacy, 'website_id': request.website.id, } if forum_privacy == 'private' and forum_privacy_group: forum['authorized_group_id'] = forum_privacy_group forum_id = request.env['forum.forum'].create(forum) if add_menu: group = [int(forum_privacy_group)] if forum_privacy == 'private' else [request.env.ref('base.group_portal').id, request.env.ref('base.group_user').id] menu_id = request.env['website.menu'].create({ 'name': forum_name, 'url': "/forum/%s" % slug(forum_id), 'parent_id': request.website.menu_id.id, 'website_id': request.website.id, 'group_ids': [(6, 0, group)] }) forum_id.menu_id = menu_id return "/forum/%s" % slug(forum_id) def sitemap_forum(env, rule, qs): Forum = env['forum.forum'] dom = sitemap_qs2dom(qs, '/forum', Forum._rec_name) dom += env['website'].get_current_website().website_domain() for f in Forum.search(dom): loc = '/forum/%s' % slug(f) if not qs or qs.lower() in loc: yield {'loc': loc} @http.route(['/forum/<model("forum.forum"):forum>', '/forum/<model("forum.forum"):forum>/page/<int:page>', '''/forum/<model("forum.forum"):forum>/tag/<model("forum.tag"):tag>/questions''', '''/forum/<model("forum.forum"):forum>/tag/<model("forum.tag"):tag>/questions/page/<int:page>''', ], type='http', auth="public", website=True, sitemap=sitemap_forum) def questions(self, forum, tag=None, page=1, filters='all', my=None, sorting=None, search='', **post): Post = request.env['forum.post'] if sorting: # check that sorting is valid # retro-compatibily for V8 and google links try: sorting = werkzeug.urls.url_unquote_plus(sorting) Post._generate_order_by(sorting, None) except (UserError, ValueError): sorting = False if not sorting: sorting = forum.default_order options = { 'displayDescription': False, 'displayDetail': False, 'displayExtraDetail': False, 'displayExtraLink': False, 'displayImage': False, 'allowFuzzy': not post.get('noFuzzy'), 'forum': str(forum.id) if forum else None, 'tag': str(tag.id) if tag else None, 'filters': filters, 'my': my, } question_count, details, fuzzy_search_term = request.website._search_with_fuzzy("forum_posts_only", search, limit=page * self._post_per_page, order=sorting, options=options) question_ids = details[0].get('results', Post) question_ids = question_ids[(page - 1) * self._post_per_page:page * self._post_per_page] if tag: url = "/forum/%s/tag/%s/questions" % (slug(forum), slug(tag)) else: url = "/forum/%s" % slug(forum) url_args = { 'sorting': sorting } if search: url_args['search'] = search if filters: url_args['filters'] = filters if my: url_args['my'] = my pager = request.website.pager(url=url, total=question_count, page=page, step=self._post_per_page, scope=self._post_per_page, url_args=url_args) values = self._prepare_user_values(forum=forum, searches=post, header={'ask_hide': not forum.active}) values.update({ 'main_object': tag or forum, 'edit_in_backend': not tag, 'question_ids': question_ids, 'question_count': question_count, 'search_count': question_count, 'pager': pager, 'tag': tag, 'filters': filters, 'my': my, 'sorting': sorting, 'search': fuzzy_search_term or search, 'original_search': fuzzy_search_term and search, }) return request.render("website_forum.forum_index", values) @http.route(['''/forum/<model("forum.forum"):forum>/faq'''], type='http', auth="public", website=True, sitemap=True) def forum_faq(self, forum, **post): values = self._prepare_user_values(forum=forum, searches=dict(), header={'is_guidelines': True}, **post) return request.render("website_forum.faq", values) @http.route(['/forum/<model("forum.forum"):forum>/faq/karma'], type='http', auth="public", website=True, sitemap=False) def forum_faq_karma(self, forum, **post): values = self._prepare_user_values(forum=forum, header={'is_guidelines': True, 'is_karma': True}, **post) return request.render("website_forum.faq_karma", values) @http.route('/forum/get_tags', type='http', auth="public", methods=['GET'], website=True, sitemap=False) def tag_read(self, query='', limit=25, **post): # TODO: In master always check the forum_id domain part and add forum_id # as required method param, not in **post forum_id = post.get('forum_id') domain = [('name', '=ilike', (query or '') + "%")] if forum_id: domain = expression.AND([domain, [('forum_id', '=', int(forum_id))]]) data = request.env['forum.tag'].search_read( domain=domain, fields=['id', 'name'], limit=int(limit), ) return request.make_response( json.dumps(data), headers=[("Content-Type", "application/json")] ) @http.route(['/forum/<model("forum.forum"):forum>/tag', '/forum/<model("forum.forum"):forum>/tag/<string:tag_char>'], type='http', auth="public", website=True, sitemap=False) def tags(self, forum, tag_char=None, **post): # build the list of tag first char, with their value as tag_char param Ex : [('All', 'all'), ('C', 'c'), ('G', 'g'), ('Z', z)] first_char_tag = forum.get_tags_first_char() first_char_list = [(t, t.lower()) for t in first_char_tag if t.isalnum()] first_char_list.insert(0, (_('All'), 'all')) active_char_tag = tag_char and tag_char.lower() or 'all' # generate domain for searched tags domain = [('forum_id', '=', forum.id), ('posts_count', '>', 0)] order_by = 'name' if active_char_tag and active_char_tag != 'all': domain.append(('name', '=ilike', tools.escape_psql(active_char_tag) + '%')) order_by = 'posts_count DESC' tags = request.env['forum.tag'].search(domain, limit=None, order=order_by) # prepare values and render template values = self._prepare_user_values(forum=forum, searches={'tags': True}, **post) values.update({ 'tags': tags, 'pager_tag_chars': first_char_list, 'active_char_tag': active_char_tag, }) return request.render("website_forum.tag", values) # Questions # -------------------------------------------------- @http.route('/forum/get_url_title', type='json', auth="user", methods=['POST'], website=True) def get_url_title(self, **kwargs): try: req = requests.get(kwargs.get('url')) req.raise_for_status() arch = lxml.html.fromstring(req.content) return arch.find(".//title").text except IOError: return False @http.route(['''/forum/<model("forum.forum"):forum>/question/<model("forum.post", "[('forum_id','=',forum.id),('parent_id','=',False),('can_view', '=', True)]"):question>'''], type='http', auth="public", website=True, sitemap=False) def old_question(self, forum, question, **post): # Compatibility pre-v14 return request.redirect(_build_url_w_params("/forum/%s/%s" % (slug(forum), slug(question)), request.params), code=301) @http.route(['''/forum/<model("forum.forum"):forum>/<model("forum.post", "[('forum_id','=',forum.id),('parent_id','=',False),('can_view', '=', True)]"):question>'''], type='http', auth="public", website=True, sitemap=True) def question(self, forum, question, **post): if not forum.active: return request.render("website_forum.header", {'forum': forum}) # Hide posts from abusers (negative karma), except for moderators if not question.can_view: raise werkzeug.exceptions.NotFound() # Hide pending posts from non-moderators and non-creator user = request.env.user if question.state == 'pending' and user.karma < forum.karma_post and question.create_uid != user: raise werkzeug.exceptions.NotFound() if question.parent_id: redirect_url = "/forum/%s/%s" % (slug(forum), slug(question.parent_id)) return request.redirect(redirect_url, 301) filters = 'question' values = self._prepare_user_values(forum=forum, searches=post) values.update({ 'main_object': question, 'question': question, 'can_bump': (question.forum_id.allow_bump and not question.child_count and (datetime.today() - question.write_date).days > 9), 'header': {'question_data': True}, 'filters': filters, 'reversed': reversed, }) if (request.httprequest.referrer or "").startswith(request.httprequest.url_root): values['back_button_url'] = request.httprequest.referrer # increment view counter question.sudo()._set_viewed() return request.render("website_forum.post_description_full", values) @http.route('/forum/<model("forum.forum"):forum>/question/<model("forum.post"):question>/toggle_favourite', type='json', auth="user", methods=['POST'], website=True) def question_toggle_favorite(self, forum, question, **post): if not request.session.uid: return {'error': 'anonymous_user'} favourite = not question.user_favourite question.sudo().favourite_ids = [(favourite and 4 or 3, request.uid)] if favourite: # Automatically add the user as follower of the posts that he # favorites (on unfavorite we chose to keep him as a follower until # he decides to not follow anymore). question.sudo().message_subscribe(request.env.user.partner_id.ids) return favourite @http.route('/forum/<model("forum.forum"):forum>/question/<model("forum.post"):question>/ask_for_close', type='http', auth="user", methods=['POST'], website=True) def question_ask_for_close(self, forum, question, **post): reasons = request.env['forum.post.reason'].search([('reason_type', '=', 'basic')]) values = self._prepare_user_values(**post) values.update({ 'question': question, 'forum': forum, 'reasons': reasons, }) return request.render("website_forum.close_post", values) @http.route('/forum/<model("forum.forum"):forum>/question/<model("forum.post"):question>/edit_answer', type='http', auth="user", website=True) def question_edit_answer(self, forum, question, **kwargs): for record in question.child_ids: if record.create_uid.id == request.uid: answer = record break return request.redirect("/forum/%s/post/%s/edit" % (slug(forum), slug(answer))) @http.route('/forum/<model("forum.forum"):forum>/question/<model("forum.post"):question>/close', type='http', auth="user", methods=['POST'], website=True) def question_close(self, forum, question, **post): question.close(reason_id=int(post.get('reason_id', False))) return request.redirect("/forum/%s/question/%s" % (slug(forum), slug(question))) @http.route('/forum/<model("forum.forum"):forum>/question/<model("forum.post"):question>/reopen', type='http', auth="user", methods=['POST'], website=True) def question_reopen(self, forum, question, **kwarg): question.reopen() return request.redirect("/forum/%s/%s" % (slug(forum), slug(question))) @http.route('/forum/<model("forum.forum"):forum>/question/<model("forum.post"):question>/delete', type='http', auth="user", methods=['POST'], website=True) def question_delete(self, forum, question, **kwarg): question.active = False return request.redirect("/forum/%s/%s" % (slug(forum), slug(question))) @http.route('/forum/<model("forum.forum"):forum>/question/<model("forum.post"):question>/undelete', type='http', auth="user", methods=['POST'], website=True) def question_undelete(self, forum, question, **kwarg): question.active = True return request.redirect("/forum/%s/%s" % (slug(forum), slug(question))) # Post # -------------------------------------------------- @http.route(['/forum/<model("forum.forum"):forum>/ask'], type='http', auth="user", website=True) def forum_post(self, forum, **post): user = request.env.user if not user.email or not tools.single_email_re.match(user.email): return request.redirect("/forum/%s/user/%s/edit?email_required=1" % (slug(forum), request.session.uid)) values = self._prepare_user_values(forum=forum, searches={}, header={'ask_hide': True}, new_question=True) return request.render("website_forum.new_question", values) @http.route(['/forum/<model("forum.forum"):forum>/new', '/forum/<model("forum.forum"):forum>/<model("forum.post"):post_parent>/reply'], type='http', auth="user", methods=['POST'], website=True) def post_create(self, forum, post_parent=None, **post): if post.get('content', '') == '<p><br></p>': return request.render('http_routing.http_error', { 'status_code': _('Bad Request'), 'status_message': post_parent and _('Reply should not be empty.') or _('Question should not be empty.') }) post_tag_ids = forum._tag_to_write_vals(post.get('post_tags', '')) if request.env.user.forum_waiting_posts_count: return request.redirect("/forum/%s/ask" % slug(forum)) new_question = request.env['forum.post'].create({ 'forum_id': forum.id, 'name': post.get('post_name') or (post_parent and 'Re: %s' % (post_parent.name or '')) or '', 'content': post.get('content', False), 'parent_id': post_parent and post_parent.id or False, 'tag_ids': post_tag_ids }) return request.redirect("/forum/%s/%s" % (slug(forum), post_parent and slug(post_parent) or new_question.id)) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/comment', type='http', auth="user", methods=['POST'], website=True) def post_comment(self, forum, post, **kwargs): question = post.parent_id if post.parent_id else post if kwargs.get('comment') and post.forum_id.id == forum.id: # TDE FIXME: check that post_id is the question or one of its answers body = tools.mail.plaintext2html(kwargs['comment']) post.with_context(mail_create_nosubscribe=True).message_post( body=body, message_type='comment', subtype_xmlid='mail.mt_comment') return request.redirect("/forum/%s/%s" % (slug(forum), slug(question))) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/toggle_correct', type='json', auth="public", website=True) def post_toggle_correct(self, forum, post, **kwargs): if post.parent_id is False: return request.redirect('/') if not request.session.uid: return {'error': 'anonymous_user'} # set all answers to False, only one can be accepted (post.parent_id.child_ids - post).write(dict(is_correct=False)) post.is_correct = not post.is_correct return post.is_correct @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/delete', type='http', auth="user", methods=['POST'], website=True) def post_delete(self, forum, post, **kwargs): question = post.parent_id post.unlink() if question: request.redirect("/forum/%s/%s" % (slug(forum), slug(question))) return request.redirect("/forum/%s" % slug(forum)) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/edit', type='http', auth="user", website=True) def post_edit(self, forum, post, **kwargs): tags = [dict(id=tag.id, name=tag.name) for tag in post.tag_ids] tags = json.dumps(tags) values = self._prepare_user_values(forum=forum) values.update({ 'tags': tags, 'post': post, 'is_edit': True, 'is_answer': bool(post.parent_id), 'searches': kwargs, 'content': post.name, }) return request.render("website_forum.edit_post", values) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/save', type='http', auth="user", methods=['POST'], website=True) def post_save(self, forum, post, **kwargs): vals = { 'content': kwargs.get('content'), } if 'post_name' in kwargs: if not kwargs.get('post_name').strip(): return request.render('http_routing.http_error', { 'status_code': _('Bad Request'), 'status_message': _('Title should not be empty.') }) vals['name'] = kwargs.get('post_name') vals['tag_ids'] = forum._tag_to_write_vals(kwargs.get('post_tags', '')) post.write(vals) question = post.parent_id if post.parent_id else post return request.redirect("/forum/%s/%s" % (slug(forum), slug(question))) # JSON utilities # -------------------------------------------------- @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/upvote', type='json', auth="public", website=True) def post_upvote(self, forum, post, **kwargs): if not request.session.uid: return {'error': 'anonymous_user'} if request.uid == post.create_uid.id: return {'error': 'own_post'} upvote = True if not post.user_vote > 0 else False return post.vote(upvote=upvote) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/downvote', type='json', auth="public", website=True) def post_downvote(self, forum, post, **kwargs): if not request.session.uid: return {'error': 'anonymous_user'} if request.uid == post.create_uid.id: return {'error': 'own_post'} upvote = True if post.user_vote < 0 else False return post.vote(upvote=upvote) @http.route('/forum/post/bump', type='json', auth="public", website=True) def post_bump(self, post_id, **kwarg): post = request.env['forum.post'].browse(int(post_id)) if not post.exists() or post.parent_id: return False return post.bump() # Moderation Tools # -------------------------------------------------- @http.route('/forum/<model("forum.forum"):forum>/validation_queue', type='http', auth="user", website=True) def validation_queue(self, forum, **kwargs): user = request.env.user if user.karma < forum.karma_moderate: raise werkzeug.exceptions.NotFound() Post = request.env['forum.post'] domain = [('forum_id', '=', forum.id), ('state', '=', 'pending')] posts_to_validate_ids = Post.search(domain) values = self._prepare_user_values(forum=forum) values.update({ 'posts_ids': posts_to_validate_ids.sudo(), 'queue_type': 'validation', }) return request.render("website_forum.moderation_queue", values) @http.route('/forum/<model("forum.forum"):forum>/flagged_queue', type='http', auth="user", website=True) def flagged_queue(self, forum, **kwargs): user = request.env.user if user.karma < forum.karma_moderate: raise werkzeug.exceptions.NotFound() Post = request.env['forum.post'] domain = [('forum_id', '=', forum.id), ('state', '=', 'flagged')] if kwargs.get('spam_post'): domain += [('name', 'ilike', kwargs.get('spam_post'))] flagged_posts_ids = Post.search(domain, order='write_date DESC') values = self._prepare_user_values(forum=forum) values.update({ 'posts_ids': flagged_posts_ids.sudo(), 'queue_type': 'flagged', 'flagged_queue_active': 1, }) return request.render("website_forum.moderation_queue", values) @http.route('/forum/<model("forum.forum"):forum>/offensive_posts', type='http', auth="user", website=True) def offensive_posts(self, forum, **kwargs): user = request.env.user if user.karma < forum.karma_moderate: raise werkzeug.exceptions.NotFound() Post = request.env['forum.post'] domain = [('forum_id', '=', forum.id), ('state', '=', 'offensive'), ('active', '=', False)] offensive_posts_ids = Post.search(domain, order='write_date DESC') values = self._prepare_user_values(forum=forum) values.update({ 'posts_ids': offensive_posts_ids.sudo(), 'queue_type': 'offensive', }) return request.render("website_forum.moderation_queue", values) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/validate', type='http', auth="user", website=True) def post_accept(self, forum, post, **kwargs): url = "/forum/%s/validation_queue" % (slug(forum)) if post.state == 'flagged': url = "/forum/%s/flagged_queue" % (slug(forum)) elif post.state == 'offensive': url = "/forum/%s/offensive_posts" % (slug(forum)) post.validate() return request.redirect(url) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/refuse', type='http', auth="user", website=True) def post_refuse(self, forum, post, **kwargs): post.refuse() return self.question_ask_for_close(forum, post) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/flag', type='json', auth="public", website=True) def post_flag(self, forum, post, **kwargs): if not request.session.uid: return {'error': 'anonymous_user'} return post.flag()[0] @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/ask_for_mark_as_offensive', type='http', auth="user", methods=['GET'], website=True) def post_ask_for_mark_as_offensive(self, forum, post, **kwargs): offensive_reasons = request.env['forum.post.reason'].search([('reason_type', '=', 'offensive')]) values = self._prepare_user_values(forum=forum) values.update({ 'question': post, 'forum': forum, 'reasons': offensive_reasons, 'offensive': True, }) return request.render("website_forum.close_post", values) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/mark_as_offensive', type='http', auth="user", methods=["POST"], website=True) def post_mark_as_offensive(self, forum, post, **kwargs): post.mark_as_offensive(reason_id=int(kwargs.get('reason_id', False))) url = '' if post.parent_id: url = "/forum/%s/%s/#answer-%s" % (slug(forum), post.parent_id.id, post.id) else: url = "/forum/%s/%s" % (slug(forum), slug(post)) return request.redirect(url) # User # -------------------------------------------------- @http.route(['/forum/<model("forum.forum"):forum>/partner/<int:partner_id>'], type='http', auth="public", website=True) def open_partner(self, forum, partner_id=0, **post): if partner_id: partner = request.env['res.partner'].sudo().search([('id', '=', partner_id)]) if partner and partner.user_ids: return request.redirect("/forum/%s/user/%d" % (slug(forum), partner.user_ids[0].id)) return request.redirect("/forum/%s" % slug(forum)) # Profile # ----------------------------------- @http.route(['/forum/<model("forum.forum"):forum>/user/<int:user_id>'], type='http', auth="public", website=True) def view_user_forum_profile(self, forum, user_id, forum_origin='/forum', **post): return request.redirect('/profile/user/' + str(user_id) + '?forum_id=' + str(forum.id) + '&forum_origin=' + str(forum_origin)) def _prepare_user_profile_values(self, user, **post): values = super(WebsiteForum, self)._prepare_user_profile_values(user, **post) if not post.get('no_forum'): if post.get('forum'): forums = post['forum'] elif post.get('forum_id'): forums = request.env['forum.forum'].browse(int(post['forum_id'])) values.update({ 'edit_button_url_param': 'forum_id=%s' % str(post['forum_id']), 'forum_filtered': forums.name, }) else: forums = request.env['forum.forum'].search([]) values.update(self._prepare_user_values(forum=forums[0] if len(forums) == 1 else True, **post)) if forums: values.update(self._prepare_open_forum_user(user, forums)) return values def _prepare_open_forum_user(self, user, forums, **kwargs): Post = request.env['forum.post'] Vote = request.env['forum.post.vote'] Activity = request.env['mail.message'] Followers = request.env['mail.followers'] Data = request.env["ir.model.data"] # questions and answers by user user_question_ids = Post.search([ ('parent_id', '=', False), ('forum_id', 'in', forums.ids), ('create_uid', '=', user.id)], order='create_date desc') count_user_questions = len(user_question_ids) min_karma_unlink = min(forums.mapped('karma_unlink_all')) # limit length of visible posts by default for performance reasons, except for the high # karma users (not many of them, and they need it to properly moderate the forum) post_display_limit = None if request.env.user.karma < min_karma_unlink: post_display_limit = 20 user_questions = user_question_ids[:post_display_limit] user_answer_ids = Post.search([ ('parent_id', '!=', False), ('forum_id', 'in', forums.ids), ('create_uid', '=', user.id)], order='create_date desc') count_user_answers = len(user_answer_ids) user_answers = user_answer_ids[:post_display_limit] # showing questions which user following post_ids = [follower.res_id for follower in Followers.sudo().search( [('res_model', '=', 'forum.post'), ('partner_id', '=', user.partner_id.id)])] followed = Post.search([('id', 'in', post_ids), ('forum_id', 'in', forums.ids), ('parent_id', '=', False)]) # showing Favourite questions of user. favourite = Post.search( [('favourite_ids', '=', user.id), ('forum_id', 'in', forums.ids), ('parent_id', '=', False)]) # votes which given on users questions and answers. data = Vote.read_group([('forum_id', 'in', forums.ids), ('recipient_id', '=', user.id)], ["vote"], groupby=["vote"]) up_votes, down_votes = 0, 0 for rec in data: if rec['vote'] == '1': up_votes = rec['vote_count'] elif rec['vote'] == '-1': down_votes = rec['vote_count'] # Votes which given by users on others questions and answers. vote_ids = Vote.search([('user_id', '=', user.id)]) # activity by user. comment = Data._xmlid_lookup('mail.mt_comment')[2] activities = Activity.search( [('res_id', 'in', (user_question_ids + user_answer_ids).ids), ('model', '=', 'forum.post'), ('subtype_id', '!=', comment)], order='date DESC', limit=100) posts = {} for act in activities: posts[act.res_id] = True posts_ids = Post.search([('id', 'in', list(posts))]) posts = {x.id: (x.parent_id or x, x.parent_id and x or False) for x in posts_ids} # TDE CLEANME MASTER: couldn't it be rewritten using a 'menu' key instead of one key for each menu ? if user == request.env.user: kwargs['my_profile'] = True else: kwargs['users'] = True values = { 'uid': request.env.user.id, 'user': user, 'main_object': user, 'searches': kwargs, 'questions': user_questions, 'count_questions': count_user_questions, 'answers': user_answers, 'count_answers': count_user_answers, 'followed': followed, 'favourite': favourite, 'up_votes': up_votes, 'down_votes': down_votes, 'activities': activities, 'posts': posts, 'vote_post': vote_ids, 'is_profile_page': True, 'badge_category': 'forum', } return values # Messaging # -------------------------------------------------- @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/comment/<model("mail.message"):comment>/convert_to_answer', type='http', auth="user", methods=['POST'], website=True) def convert_comment_to_answer(self, forum, post, comment, **kwarg): post = request.env['forum.post'].convert_comment_to_answer(comment.id) if not post: return request.redirect("/forum/%s" % slug(forum)) question = post.parent_id if post.parent_id else post return request.redirect("/forum/%s/%s" % (slug(forum), slug(question))) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/convert_to_comment', type='http', auth="user", methods=['POST'], website=True) def convert_answer_to_comment(self, forum, post, **kwarg): question = post.parent_id new_msg = post.convert_answer_to_comment() if not new_msg: return request.redirect("/forum/%s" % slug(forum)) return request.redirect("/forum/%s/%s" % (slug(forum), slug(question))) @http.route('/forum/<model("forum.forum"):forum>/post/<model("forum.post"):post>/comment/<model("mail.message"):comment>/delete', type='json', auth="user", website=True) def delete_comment(self, forum, post, comment, **kwarg): if not request.session.uid: return {'error': 'anonymous_user'} return post.unlink_comment(comment.id)[0]
47.305516
33,445
841
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Pakistan - Accounting', 'version': '1.0', 'category': 'Accounting/Localizations/Account Charts', 'description': """ This is the base module to manage chart of accounts and localization for the Pakistan """, 'author': 'Odoo S.A.', 'depends': ['account'], 'data': [ 'data/account_chart_template_data.xml', 'data/account.account.template.csv', 'data/l10n_pk_chart_data.xml', 'data/account.group.template.csv', 'data/account_tax_group.xml', 'data/account_tax_template_data.xml', 'data/account_chart_template_configure_data.xml', 'data/menuitem_data.xml', ], 'demo': [ 'demo/demo_company.xml' ], 'license': 'LGPL-3', }
33.64
841
598
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Dropship and Subcontracting Management', 'version': '0.1', 'category': 'Inventory/Purchase', 'description': """ This bridge module allows to manage subcontracting with the dropshipping module. """, 'depends': ['mrp_subcontracting', 'stock_dropshipping'], 'data': [ 'data/mrp_subcontracting_dropshipping_data.xml', 'views/stock_warehouse_views.xml', ], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
29.9
598
6,670
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon from odoo.tests import tagged, Form @tagged('post_install', '-at_install') class TestSubcontractingDropshippingValuation(ValuationReconciliationTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) categ_form = Form(cls.env['product.category']) categ_form.name = 'fifo auto' categ_form.parent_id = cls.env.ref('product.product_category_all') categ_form.property_cost_method = 'fifo' categ_form.property_valuation = 'real_time' cls.categ_fifo_auto = categ_form.save() (cls.product_a | cls.product_b).type = 'product' cls.bom_a = cls.env['mrp.bom'].create({ 'product_tmpl_id': cls.product_a.product_tmpl_id.id, 'type': 'subcontract', 'subcontractor_ids': [(6, 0, cls.partner_a.ids)], 'bom_line_ids': [ (0, 0, {'product_id': cls.product_b.id, 'product_qty': 1.0}), ], }) def test_valuation_subcontracted_and_dropshipped(self): """ Product: - FIFO + Auto - Subcontracted Purchase 2 from Subcontractor to a customer (dropship). Then return 1 to subcontractor and one to stock It should generate the correct valuations AMLs """ # pylint: disable=bad-whitespace all_amls_ids = self.env['account.move.line'].search_read([], ['id']) grp_multi_loc = self.env.ref('stock.group_stock_multi_locations') self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]}) (self.product_a | self.product_b).categ_id = self.categ_fifo_auto self.product_b.standard_price = 10 dropship_picking_type = self.env['stock.picking.type'].search([ ('company_id', '=', self.env.company.id), ('default_location_src_id.usage', '=', 'supplier'), ('default_location_dest_id.usage', '=', 'customer'), ], limit=1, order='sequence') po = self.env['purchase.order'].create({ "partner_id": self.partner_a.id, "picking_type_id": dropship_picking_type.id, "dest_address_id": self.partner_b.id, "order_line": [(0, 0, { 'product_id': self.product_a.id, 'name': self.product_a.name, 'product_qty': 2.0, 'price_unit': 100, 'taxes_id': False, })], }) po.button_confirm() delivery = po.picking_ids res = delivery.button_validate() Form(self.env['stock.immediate.transfer'].with_context(res['context'])).save().process() stock_in_acc_id = self.categ_fifo_auto.property_stock_account_input_categ_id.id stock_out_acc_id = self.categ_fifo_auto.property_stock_account_output_categ_id.id stock_valu_acc_id = self.categ_fifo_auto.property_stock_valuation_account_id.id amls = self.env['account.move.line'].search([('id', 'not in', all_amls_ids)]) all_amls_ids += amls.ids self.assertRecordValues(amls, [ # Compensation of dropshipping value {'account_id': stock_valu_acc_id, 'product_id': self.product_a.id, 'debit': 0.0, 'credit': 20.0}, {'account_id': stock_out_acc_id, 'product_id': self.product_a.id, 'debit': 20.0, 'credit': 0.0}, # Receipt from subcontractor {'account_id': stock_in_acc_id, 'product_id': self.product_a.id, 'debit': 0.0, 'credit': 220.0}, {'account_id': stock_valu_acc_id, 'product_id': self.product_a.id, 'debit': 220.0, 'credit': 0.0}, # Delivery to subcontractor {'account_id': stock_valu_acc_id, 'product_id': self.product_b.id, 'debit': 0.0, 'credit': 20.0}, {'account_id': stock_out_acc_id, 'product_id': self.product_b.id, 'debit': 20.0, 'credit': 0.0}, # Initial dropshipped value {'account_id': stock_valu_acc_id, 'product_id': self.product_a.id, 'debit': 0.0, 'credit': 200.0}, {'account_id': stock_out_acc_id, 'product_id': self.product_a.id, 'debit': 200.0, 'credit': 0.0}, ]) # return to subcontracting location sbc_location = self.env.company.subcontracting_location_id return_form = Form(self.env['stock.return.picking'].with_context(active_id=delivery.id, active_model='stock.picking')) return_form.location_id = sbc_location with return_form.product_return_moves.edit(0) as line: line.quantity = 1 return_wizard = return_form.save() return_id, _ = return_wizard._create_returns() return_picking = self.env['stock.picking'].browse(return_id) return_picking.move_lines.quantity_done = 1 return_picking.button_validate() amls = self.env['account.move.line'].search([('id', 'not in', all_amls_ids)]) all_amls_ids += amls.ids self.assertRecordValues(amls, [ {'account_id': stock_valu_acc_id, 'product_id': self.product_a.id, 'debit': 0.0, 'credit': 110.0}, {'account_id': stock_in_acc_id, 'product_id': self.product_a.id, 'debit': 110.0, 'credit': 0.0}, ]) # return to stock location warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1) stock_location = warehouse.lot_stock_id stock_location.return_location = True return_form = Form(self.env['stock.return.picking'].with_context(active_id=delivery.id, active_model='stock.picking')) return_form.location_id = stock_location with return_form.product_return_moves.edit(0) as line: line.quantity = 1 return_wizard = return_form.save() return_id, _ = return_wizard._create_returns() return_picking = self.env['stock.picking'].browse(return_id) return_picking.move_lines.quantity_done = 1 return_picking.button_validate() amls = self.env['account.move.line'].search([('id', 'not in', all_amls_ids)]) all_amls_ids += amls.ids self.assertRecordValues(amls, [ {'account_id': stock_out_acc_id, 'product_id': self.product_a.id, 'debit': 0.0, 'credit': 110.0}, {'account_id': stock_valu_acc_id, 'product_id': self.product_a.id, 'debit': 110.0, 'credit': 0.0}, ])
49.776119
6,670
12,700
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import Form from odoo.addons.mrp_subcontracting.tests.common import TestMrpSubcontractingCommon class TestSaleDropshippingFlows(TestMrpSubcontractingCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.supplier = cls.env["res.partner"].create({"name": "Supplier"}) cls.customer = cls.env["res.partner"].create({"name": "Customer"}) cls.dropship_route = cls.env.ref('stock_dropshipping.route_drop_shipping') def test_dropship_with_different_suppliers(self): """ Suppose a kit with 3 components supplied by 3 vendors When dropshipping this kit, if 2 components are delivered and if the last picking is cancelled, we should consider the kit as fully delivered. """ partners = self.env['res.partner'].create([{'name': 'Vendor %s' % i} for i in range(4)]) compo01, compo02, compo03, kit = self.env['product.product'].create([{ 'name': name, 'type': 'consu', 'route_ids': [(6, 0, [self.dropship_route.id])], 'seller_ids': [(0, 0, {'name': seller.id})], } for name, seller in zip(['Compo01', 'Compo02', 'Compo03', 'Kit'], partners)]) self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': compo01.id, 'product_qty': 1}), (0, 0, {'product_id': compo02.id, 'product_qty': 1}), (0, 0, {'product_id': compo03.id, 'product_qty': 1}), ], }) sale_order = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'picking_policy': 'direct', 'order_line': [ (0, 0, {'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 1}), ], }) sale_order.action_confirm() self.assertEqual(sale_order.order_line.qty_delivered, 0) purchase_orders = self.env['purchase.order'].search([('partner_id', 'in', partners.ids)]) purchase_orders.button_confirm() self.assertEqual(sale_order.order_line.qty_delivered, 0) # Deliver the first one picking = sale_order.picking_ids.filtered(lambda p: p.partner_id == partners[0]) action = picking.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() self.assertEqual(sale_order.order_line.qty_delivered, 0) # Deliver the third one picking = sale_order.picking_ids.filtered(lambda p: p.partner_id == partners[2]) action = picking.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() self.assertEqual(sale_order.order_line.qty_delivered, 0) # Cancel the second one sale_order.picking_ids[1].action_cancel() self.assertEqual(sale_order.order_line.qty_delivered, 1) def test_return_kit_and_delivered_qty(self): """ Sell a kit thanks to the dropshipping route, return it then deliver it again The delivered quantity should be correctly computed """ compo, kit = self.env['product.product'].create([{ 'name': n, 'type': 'consu', 'route_ids': [(6, 0, [self.dropship_route.id])], 'seller_ids': [(0, 0, {'name': self.supplier.id})], } for n in ['Compo', 'Kit']]) self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': compo.id, 'product_qty': 1}), ], }) sale_order = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'picking_policy': 'direct', 'order_line': [ (0, 0, {'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 1}), ], }) sale_order.action_confirm() self.env['purchase.order'].search([], order='id desc', limit=1).button_confirm() self.assertEqual(sale_order.order_line.qty_delivered, 0.0) picking = sale_order.picking_ids action = picking.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() self.assertEqual(sale_order.order_line.qty_delivered, 1.0) for case in ['return', 'deliver again']: delivered_before_case = 1.0 if case == 'return' else 0.0 delivered_after_case = 0.0 if case == 'return' else 1.0 return_form = Form(self.env['stock.return.picking'].with_context(active_ids=[picking.id], active_id=picking.id, active_model='stock.picking')) return_wizard = return_form.save() action = return_wizard.create_returns() picking = self.env['stock.picking'].browse(action['res_id']) self.assertEqual(sale_order.order_line.qty_delivered, delivered_before_case, "Incorrect delivered qty for case '%s'" % case) action = picking.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() self.assertEqual(sale_order.order_line.qty_delivered, delivered_after_case, "Incorrect delivered qty for case '%s'" % case) def test_partial_return_kit_and_delivered_qty(self): """ Suppose a kit with 4x the same dropshipped component Suppose a complex delivery process: - Deliver 2 (with backorder) - Return 2 - Deliver 1 (with backorder) - Deliver 1 (process "done") - Deliver 1 (from the return) - Deliver 1 (from the return) The test checks the all-or-nothing policy of the delivered quantity This quantity should be 1.0 after the last delivery """ compo, kit = self.env['product.product'].create([{ 'name': n, 'type': 'consu', 'route_ids': [(6, 0, [self.dropship_route.id])], 'seller_ids': [(0, 0, {'name': self.supplier.id})], } for n in ['Compo', 'Kit']]) self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': compo.id, 'product_qty': 4}), ], }) sale_order = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'picking_policy': 'direct', 'order_line': [ (0, 0, {'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 1}), ], }) sale_order.action_confirm() self.env['purchase.order'].search([], order='id desc', limit=1).button_confirm() self.assertEqual(sale_order.order_line.qty_delivered, 0.0, "Delivered components: 0/4") picking01 = sale_order.picking_ids picking01.move_lines.quantity_done = 2 action = picking01.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() self.assertEqual(sale_order.order_line.qty_delivered, 0.0, "Delivered components: 2/4") # Create a return of picking01 (with both components) return_form = Form(self.env['stock.return.picking'].with_context(active_id=picking01.id, active_model='stock.picking')) wizard = return_form.save() wizard.product_return_moves.write({'quantity': 2.0}) res = wizard.create_returns() return01 = self.env['stock.picking'].browse(res['res_id']) return01.move_lines.quantity_done = 2 return01.button_validate() self.assertEqual(sale_order.order_line.qty_delivered, 0.0, "Delivered components: 0/4") picking02 = picking01.backorder_ids picking02.move_lines.quantity_done = 1 action = picking02.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() self.assertEqual(sale_order.order_line.qty_delivered, 0.0, "Delivered components: 1/4") picking03 = picking02.backorder_ids picking03.move_lines.quantity_done = 1 picking03.button_validate() self.assertEqual(sale_order.order_line.qty_delivered, 0.0, "Delivered components: 2/4") # Create a return of return01 (with 1 component) return_form = Form(self.env['stock.return.picking'].with_context(active_id=return01.id, active_model='stock.picking')) wizard = return_form.save() wizard.product_return_moves.write({'quantity': 1.0}) res = wizard.create_returns() picking04 = self.env['stock.picking'].browse(res['res_id']) picking04.move_lines.quantity_done = 1 picking04.button_validate() self.assertEqual(sale_order.order_line.qty_delivered, 0.0, "Delivered components: 3/4") # Create a second return of return01 (with 1 component, the last one) return_form = Form(self.env['stock.return.picking'].with_context(active_id=return01.id, active_model='stock.picking')) wizard = return_form.save() wizard.product_return_moves.write({'quantity': 1.0}) res = wizard.create_returns() picking04 = self.env['stock.picking'].browse(res['res_id']) picking04.move_lines.quantity_done = 1 picking04.button_validate() self.assertEqual(sale_order.order_line.qty_delivered, 1, "Delivered components: 4/4") def test_cancelled_picking_and_delivered_qty(self): """ The delivered quantity should be zero if all SM are cancelled """ compo, kit = self.env['product.product'].create([{ 'name': n, 'type': 'consu', 'route_ids': [(6, 0, [self.dropship_route.id])], 'seller_ids': [(0, 0, {'name': self.supplier.id})], } for n in ['Compo', 'Kit']]) self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': compo.id, 'product_qty': 1}), ], }) sale_order = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'picking_policy': 'direct', 'order_line': [ (0, 0, {'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 1}), ], }) sale_order.action_confirm() self.env['purchase.order'].search([], order='id desc', limit=1).button_confirm() self.assertEqual(sale_order.order_line.qty_delivered, 0.0) sale_order.picking_ids.action_cancel() self.assertEqual(sale_order.order_line.qty_delivered, 0.0) def test_sale_kit_with_dropshipped_component(self): """ The test checks the delivered quantity of a kit when one of the components is dropshipped """ compo01, compo02, kit = self.env['product.product'].create([{ 'name': n, 'type': 'consu', } for n in ['compo01', 'compo02', 'super kit']]) compo02.write({ 'route_ids': [(6, 0, [self.dropship_route.id])], 'seller_ids': [(0, 0, {'name': self.supplier.id})], }) self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': compo01.id, 'product_qty': 1}), (0, 0, {'product_id': compo02.id, 'product_qty': 1}), ], }) sale_order = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'picking_policy': 'direct', 'order_line': [ (0, 0, {'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 1}), ], }) sale_order.action_confirm() self.env['purchase.order'].search([], order='id desc', limit=1).button_confirm() sale_order.picking_ids.move_lines.quantity_done = 1 sale_order.picking_ids[0].button_validate() sale_order.picking_ids[1].button_validate() self.assertEqual(sale_order.order_line.qty_delivered, 1.0)
43.34471
12,700
16,612
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import Form from odoo.addons.mrp_subcontracting.tests.common import TestMrpSubcontractingCommon class TestSubcontractingDropshippingFlows(TestMrpSubcontractingCommon): def test_mrp_subcontracting_dropshipping_1(self): """ Mark the subcontracted product with the route dropship and add the subcontractor as seller. The component has the routes 'MTO', 'Replenish on order' and 'Buy'. Also another partner is set as vendor on the comp. Create a SO and check that: - Delivery between subcontractor and customer for subcontracted product. - Delivery for the component to the subcontractor for the specified wh. - Po created for the component. """ self.env.ref('stock.route_warehouse0_mto').active = True mto_route = self.env['stock.location.route'].search([('name', '=', 'Replenish on Order (MTO)')]) resupply_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')]) buy_route = self.env['stock.location.route'].search([('name', '=', 'Buy')]) dropship_route = self.env['stock.location.route'].search([('name', '=', 'Dropship')]) self.comp2.write({'route_ids': [(4, buy_route.id), (4, mto_route.id), (4, resupply_route.id)]}) self.finished.write({'route_ids': [(4, dropship_route.id)]}) warehouse = self.env['stock.warehouse'].create({ 'name': 'Warehouse For subcontract', 'code': 'WFS' }) self.env['product.supplierinfo'].create({ 'product_tmpl_id': self.finished.product_tmpl_id.id, 'name': self.subcontractor_partner1.id }) partner = self.env['res.partner'].create({ 'name': 'Toto' }) self.env['product.supplierinfo'].create({ 'product_tmpl_id': self.comp2.product_tmpl_id.id, 'name': partner.id }) # Create a receipt picking from the subcontractor so_form = Form(self.env['sale.order']) so_form.partner_id = partner so_form.warehouse_id = warehouse with so_form.order_line.new() as line: line.product_id = self.finished line.product_uom_qty = 1 so = so_form.save() so.action_confirm() # Pickings should directly be created po = self.env['purchase.order'].search([('origin', 'ilike', so.name)]) self.assertTrue(po) po.button_approve() picking_finished = po.picking_ids self.assertEqual(len(picking_finished), 1.0) self.assertEqual(picking_finished.location_dest_id, partner.property_stock_customer) self.assertEqual(picking_finished.location_id, self.subcontractor_partner1.property_stock_supplier) self.assertEqual(picking_finished.state, 'assigned') picking_delivery = self.env['stock.move'].search([ ('product_id', '=', self.comp2.id), ('location_id', '=', warehouse.lot_stock_id.id), ('location_dest_id', '=', self.subcontractor_partner1.property_stock_subcontractor.id), ]).picking_id self.assertTrue(picking_delivery) self.assertEqual(picking_delivery.state, 'waiting') po = self.env['purchase.order.line'].search([ ('product_id', '=', self.comp2.id), ('partner_id', '=', partner.id), ]).order_id self.assertTrue(po) def test_mrp_subcontracting_purchase_2(self): """Let's consider a subcontracted BOM with 1 component. Tick "Resupply Subcontractor on Order" on the component and set a supplier on it. Purchase 1 BOM to the subcontractor. Confirm the purchase and change the purchased quantity to 2. Check that 2 components are delivered to the subcontractor """ # Tick "resupply subconractor on order on component" self.bom.bom_line_ids = [(5, 0, 0)] self.bom.bom_line_ids = [(0, 0, {'product_id': self.comp1.id, 'product_qty': 1})] resupply_sub_on_order_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')]) (self.comp1).write({'route_ids': [(4, resupply_sub_on_order_route.id, None)]}) # Create a supplier and set it to component vendor = self.env['res.partner'].create({'name': 'AAA', 'email': 'from.test@example.com'}) self.env['product.supplierinfo'].create({ 'name': vendor.id, 'price': 50, }) self.comp1.write({'seller_ids': [(0, 0, {'name': vendor.id, 'product_code': 'COMP1'})]}) # Purchase 1 BOM to the subcontractor po = Form(self.env['purchase.order']) po.partner_id = self.subcontractor_partner1 with po.order_line.new() as po_line: po_line.product_id = self.finished po_line.product_qty = 1 po_line.price_unit = 100 po = po.save() # Confirm the purchase po.button_confirm() # Check one delivery order with the component has been created for the subcontractor mo = self.env['mrp.production'].search([('bom_id', '=', self.bom.id)]) self.assertEqual(mo.state, 'confirmed') # Check that 1 delivery with 1 component for the subcontractor has been created picking_delivery = mo.picking_ids wh = picking_delivery.picking_type_id.warehouse_id origin = picking_delivery.origin self.assertEqual(len(picking_delivery), 1) self.assertEqual(len(picking_delivery.move_ids_without_package), 1) self.assertEqual(picking_delivery.picking_type_id, wh.subcontracting_resupply_type_id) self.assertEqual(picking_delivery.partner_id, self.subcontractor_partner1) # Change the purchased quantity to 2 po.order_line.write({'product_qty': 2}) # Check that two deliveries with 1 component for the subcontractor have been created picking_deliveries = self.env['stock.picking'].search([('origin', '=', origin)]) self.assertEqual(len(picking_deliveries), 2) self.assertEqual(picking_deliveries[0].picking_type_id, wh.subcontracting_resupply_type_id) self.assertEqual(picking_deliveries[0].partner_id, self.subcontractor_partner1) self.assertTrue(picking_deliveries[0].state != 'cancel') move1 = picking_deliveries[0].move_ids_without_package self.assertEqual(picking_deliveries[1].picking_type_id, wh.subcontracting_resupply_type_id) self.assertEqual(picking_deliveries[1].partner_id, self.subcontractor_partner1) self.assertTrue(picking_deliveries[1].state != 'cancel') move2 = picking_deliveries[1].move_ids_without_package self.assertEqual(move1.product_id, self.comp1) self.assertEqual(move1.product_uom_qty, 1) self.assertEqual(move2.product_id, self.comp1) self.assertEqual(move2.product_uom_qty, 1) def test_dropshipped_component_and_sub_location(self): """ Suppose: - a subcontracted product and a component dropshipped to the subcontractor - the location of the subcontractor is a sub-location of the main subcontrating location This test ensures that the PO that brings the component to the subcontractor has a correct destination address """ subcontract_location = self.env.company.subcontracting_location_id sub_location = self.env['stock.location'].create({ 'name': 'Super Location', 'location_id': subcontract_location.id, }) dropship_subcontractor_route = self.env['stock.location.route'].search([('name', '=', 'Dropship Subcontractor on Order')]) dropship_subcontractor_route.rule_ids.filtered(lambda rule: rule.location_id == subcontract_location).copy(default={'location_id': sub_location.id}) dropship_subcontractor_route.rule_ids.filtered(lambda rule: rule.location_src_id == subcontract_location).copy(default={'location_src_id': sub_location.id}) subcontractor, vendor = self.env['res.partner'].create([ {'name': 'SuperSubcontractor', 'property_stock_subcontractor': sub_location.id}, {'name': 'SuperVendor'}, ]) p_finished, p_compo = self.env['product.product'].create([{ 'name': 'Finished Product', 'type': 'product', 'seller_ids': [(0, 0, {'name': subcontractor.id})], }, { 'name': 'Component', 'type': 'consu', 'seller_ids': [(0, 0, {'name': vendor.id})], 'route_ids': [(6, 0, dropship_subcontractor_route.ids)] }]) self.env['mrp.bom'].create({ 'product_tmpl_id': p_finished.product_tmpl_id.id, 'product_qty': 1, 'type': 'subcontract', 'subcontractor_ids': [(6, 0, subcontractor.ids)], 'bom_line_ids': [ (0, 0, {'product_id': p_compo.id, 'product_qty': 1}), ], }) subcontract_po = self.env['purchase.order'].create({ "partner_id": subcontractor.id, "order_line": [(0, 0, { 'product_id': p_finished.id, 'name': p_finished.name, 'product_qty': 1.0, })], }) subcontract_po.button_confirm() dropship_po = self.env['purchase.order'].search([('partner_id', '=', vendor.id)]) self.assertEqual(dropship_po.dest_address_id, subcontractor) def test_po_to_customer(self): """ Create and confirm a PO with a subcontracted move. The picking type of the PO is 'Dropship' and the delivery address a customer. Then, process a return with the stock location as destination and another return with the supplier as destination """ subcontractor, client = self.env['res.partner'].create([ {'name': 'SuperSubcontractor'}, {'name': 'SuperClient'}, ]) p_finished, p_compo = self.env['product.product'].create([{ 'name': 'Finished Product', 'type': 'product', 'seller_ids': [(0, 0, {'name': subcontractor.id})], }, { 'name': 'Component', 'type': 'consu', }]) bom = self.env['mrp.bom'].create({ 'product_tmpl_id': p_finished.product_tmpl_id.id, 'product_qty': 1, 'type': 'subcontract', 'subcontractor_ids': [(6, 0, subcontractor.ids)], 'bom_line_ids': [ (0, 0, {'product_id': p_compo.id, 'product_qty': 1}), ], }) dropship_picking_type = self.env['stock.picking.type'].search([ ('company_id', '=', self.env.company.id), ('default_location_src_id.usage', '=', 'supplier'), ('default_location_dest_id.usage', '=', 'customer'), ], limit=1, order='sequence') po = self.env['purchase.order'].create({ "partner_id": subcontractor.id, "picking_type_id": dropship_picking_type.id, "dest_address_id": client.id, "order_line": [(0, 0, { 'product_id': p_finished.id, 'name': p_finished.name, 'product_qty': 2.0, })], }) po.button_confirm() mo = self.env['mrp.production'].search([('bom_id', '=', bom.id)]) self.assertEqual(mo.picking_type_id, self.warehouse.subcontracting_type_id) delivery = po.picking_ids delivery.move_line_ids.qty_done = 2.0 delivery.button_validate() self.assertEqual(delivery.state, 'done') self.assertEqual(mo.state, 'done') self.assertEqual(po.order_line.qty_received, 2) # return 1 x P_finished to the stock location stock_location = self.warehouse.lot_stock_id stock_location.return_location = True return_form = Form(self.env['stock.return.picking'].with_context(active_ids=delivery.ids, active_id=delivery.id, active_model='stock.picking')) with return_form.product_return_moves.edit(0) as line: line.quantity = 1.0 return_form.location_id = stock_location return_wizard = return_form.save() return_picking_id, _pick_type_id = return_wizard._create_returns() delivery_return01 = self.env['stock.picking'].browse(return_picking_id) delivery_return01.move_line_ids.qty_done = 1.0 delivery_return01.button_validate() self.assertEqual(delivery_return01.state, 'done') self.assertEqual(p_finished.qty_available, 1, 'One product has been returned to the stock location, so it should be available') self.assertEqual(po.order_line.qty_received, 2, 'One product has been returned to the stock location, so we should still consider it as received') # return 1 x P_finished to the supplier location supplier_location = dropship_picking_type.default_location_src_id return_form = Form(self.env['stock.return.picking'].with_context(active_ids=delivery.ids, active_id=delivery.id, active_model='stock.picking')) with return_form.product_return_moves.edit(0) as line: line.quantity = 1.0 return_form.location_id = supplier_location return_wizard = return_form.save() return_picking_id, _pick_type_id = return_wizard._create_returns() delivery_return02 = self.env['stock.picking'].browse(return_picking_id) delivery_return02.move_line_ids.qty_done = 1.0 delivery_return02.button_validate() self.assertEqual(delivery_return02.state, 'done') self.assertEqual(po.order_line.qty_received, 1) def test_po_to_subcontractor(self): """ Create and confirm a PO with a subcontracted move. The bought product is also a component of another subcontracted product. The picking type of the PO is 'Dropship' and the delivery address is the other subcontractor """ subcontractor, super_subcontractor = self.env['res.partner'].create([ {'name': 'Subcontractor'}, {'name': 'SuperSubcontractor'}, ]) super_product, product, component = self.env['product.product'].create([{ 'name': 'Super Product', 'type': 'product', 'seller_ids': [(0, 0, {'name': super_subcontractor.id})], }, { 'name': 'Product', 'type': 'product', 'seller_ids': [(0, 0, {'name': subcontractor.id})], }, { 'name': 'Component', 'type': 'consu', }]) _, bom_product = self.env['mrp.bom'].create([{ 'product_tmpl_id': super_product.product_tmpl_id.id, 'product_qty': 1, 'type': 'subcontract', 'subcontractor_ids': [(6, 0, super_subcontractor.ids)], 'bom_line_ids': [ (0, 0, {'product_id': product.id, 'product_qty': 1}), ], }, { 'product_tmpl_id': product.product_tmpl_id.id, 'product_qty': 1, 'type': 'subcontract', 'subcontractor_ids': [(6, 0, subcontractor.ids)], 'bom_line_ids': [ (0, 0, {'product_id': component.id, 'product_qty': 1}), ], }]) dropship_picking_type = self.env['stock.picking.type'].search([ ('company_id', '=', self.env.company.id), ('default_location_src_id.usage', '=', 'supplier'), ('default_location_dest_id.usage', '=', 'customer'), ], limit=1, order='sequence') po = self.env['purchase.order'].create({ "partner_id": subcontractor.id, "picking_type_id": dropship_picking_type.id, "dest_address_id": super_subcontractor.id, "order_line": [(0, 0, { 'product_id': product.id, 'name': product.name, 'product_qty': 1.0, })], }) po.button_confirm() mo = self.env['mrp.production'].search([('bom_id', '=', bom_product.id)]) self.assertEqual(mo.picking_type_id, self.warehouse.subcontracting_type_id) delivery = po.picking_ids self.assertEqual(delivery.location_dest_id, super_subcontractor.property_stock_subcontractor) self.assertTrue(delivery.is_dropship) delivery.move_line_ids.qty_done = 1.0 delivery.button_validate() self.assertEqual(po.order_line.qty_received, 1.0)
46.272981
16,612
1,831
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ class StockWarehouse(models.Model): _inherit = 'stock.warehouse' subcontracting_dropshipping_to_resupply = fields.Boolean( 'Dropship Subcontractors', default=True, help="Dropship subcontractors with components") subcontracting_dropshipping_pull_id = fields.Many2one( 'stock.rule', 'Subcontracting-Dropshipping MTS Rule' ) def _get_global_route_rules_values(self): rules = super()._get_global_route_rules_values() subcontract_location_id = self._get_subcontracting_location() production_location_id = self._get_production_location() rules.update({ 'subcontracting_dropshipping_pull_id': { 'depends': ['subcontracting_dropshipping_to_resupply'], 'create_values': { 'procure_method': 'make_to_order', 'company_id': self.company_id.id, 'action': 'pull', 'auto': 'manual', 'route_id': self._find_global_route('mrp_subcontracting_dropshipping.route_subcontracting_dropshipping', _('Dropship Subcontractor on Order')).id, 'name': self._format_rulename(subcontract_location_id, production_location_id, False), 'location_id': production_location_id.id, 'location_src_id': subcontract_location_id.id, 'picking_type_id': self.subcontracting_type_id.id }, 'update_values': { 'active': self.subcontracting_dropshipping_to_resupply } }, }) return rules
43.595238
1,831
1,729
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ from odoo.exceptions import UserError class PurchaseOrder(models.Model): _inherit = 'purchase.order' def _get_destination_location(self): self.ensure_one() if not self.dest_address_id: return super()._get_destination_location() mrp_production_ids = self._get_mrp_productions(remove_archived_picking_types=False) if mrp_production_ids: if self.dest_address_id in mrp_production_ids.bom_id.subcontractor_ids: return self.dest_address_id.property_stock_subcontractor.id elif self.sale_order_count: return super()._get_destination_location() in_bom_products = False not_in_bom_products = self.env['purchase.order.line'] for order_line in self.order_line: if any(bom_line.bom_id.type == 'subcontract' and self.dest_address_id in bom_line.bom_id.subcontractor_ids for bom_line in order_line.product_id.bom_line_ids.filtered(lambda line: line.company_id == self.company_id)): in_bom_products = True elif not order_line.display_type: not_in_bom_products |= order_line if in_bom_products and not_in_bom_products: raise UserError( _("It appears some components in this RFQ are not meant for subcontracting. Please create a separate order for these.") + '\n\n' + '\n'.join(not_in_bom_products.mapped('name')) ) elif in_bom_products: return self.dest_address_id.property_stock_subcontractor.id return super()._get_destination_location()
46.72973
1,729
1,037
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class StockMove(models.Model): _inherit = "stock.move" def _is_purchase_return(self): res = super()._is_purchase_return() return res or self._is_dropshipped_returned() def _is_dropshipped(self): res = super()._is_dropshipped() return res or ( self.partner_id.property_stock_subcontractor.parent_path and self.partner_id.property_stock_subcontractor.parent_path in self.location_id.parent_path and self.location_dest_id.usage == 'customer' ) def _is_dropshipped_returned(self): res = super()._is_dropshipped_returned() return res or ( self.location_id.usage == 'customer' and self.partner_id.property_stock_subcontractor.parent_path and self.partner_id.property_stock_subcontractor.parent_path in self.location_dest_id.parent_path )
37.035714
1,037
2,118
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class ResCompany(models.Model): _inherit = 'res.company' def _create_subcontracting_dropshipping_rules(self): route = self.env.ref('mrp_subcontracting_dropshipping.route_subcontracting_dropshipping') supplier_location = self.env.ref('stock.stock_location_suppliers') vals = [] for company in self: subcontracting_location = company.subcontracting_location_id dropship_picking_type = self.env['stock.picking.type'].search([ ('company_id', '=', company.id), ('default_location_src_id.usage', '=', 'supplier'), ('default_location_dest_id.usage', '=', 'customer'), ], limit=1, order='sequence') if dropship_picking_type: vals.append({ 'name': '%s → %s' % (supplier_location.name, subcontracting_location.name), 'action': 'buy', 'location_id': subcontracting_location.id, 'location_src_id': supplier_location.id, 'procure_method': 'make_to_stock', 'route_id': route.id, 'picking_type_id': dropship_picking_type.id, 'company_id': company.id, }) if vals: self.env['stock.rule'].create(vals) @api.model def create_missing_subcontracting_dropshipping_rules(self): route = self.env.ref('mrp_subcontracting_dropshipping.route_subcontracting_dropshipping') company_ids = self.env['res.company'].search([]) company_has_rules = self.env['stock.rule'].search([('route_id', '=', route.id)]).mapped('company_id') company_todo_rules = company_ids - company_has_rules company_todo_rules._create_subcontracting_dropshipping_rules() def _create_per_company_rules(self): res = super()._create_per_company_rules() self.create_missing_subcontracting_dropshipping_rules() return res
46
2,116
3,620
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from odoo.tools import float_compare class StockPicking(models.Model): _inherit = 'stock.picking' def _compute_is_dropship(self): dropship_subcontract_pickings = self.filtered(lambda p: p.location_id.usage == 'supplier' and any(m.location_dest_id == m.partner_id.property_stock_subcontractor or (m.partner_id.property_stock_subcontractor.parent_path and m.location_dest_id.parent_path and m.partner_id.property_stock_subcontractor.parent_path in m.location_dest_id.parent_path) for m in p.move_lines) ) dropship_subcontract_pickings.is_dropship = True super(StockPicking, self - dropship_subcontract_pickings)._compute_is_dropship() def _get_warehouse(self, subcontract_move): if subcontract_move.sale_line_id: return subcontract_move.sale_line_id.order_id.warehouse_id return super(StockPicking, self)._get_warehouse(subcontract_move) def _action_done(self): res = super()._action_done() self.move_lines.move_dest_ids._action_assign() # If needed, create a compensation layer, so we add the MO cost to the dropship one svls = self.env['stock.valuation.layer'] for move in self.move_lines: if not (move.is_subcontract and move._is_dropshipped() and move.state == 'done'): continue dropship_svls = move.stock_valuation_layer_ids if not dropship_svls: continue subcontract_svls = move.move_orig_ids.stock_valuation_layer_ids subcontract_value = sum(subcontract_svls.mapped('value')) dropship_value = abs(sum(dropship_svls.mapped('value'))) diff = subcontract_value - dropship_value if float_compare(diff, 0, precision_rounding=move.company_id.currency_id.rounding) <= 0: continue svl_vals = move._prepare_common_svl_vals() svl_vals.update({ 'remaining_value': 0, 'remaining_qty': 0, 'value': -diff, 'quantity': 0, 'unit_cost': 0, 'stock_valuation_layer_id': dropship_svls[0].id, 'stock_move_id': move.id, }) svls |= self.env['stock.valuation.layer'].create(svl_vals) svls._validate_accounting_entries() return res def _prepare_subcontract_mo_vals(self, subcontract_move, bom): res = super()._prepare_subcontract_mo_vals(subcontract_move, bom) if not res.get('picking_type_id') and ( subcontract_move.location_dest_id.usage == 'customer' or subcontract_move.partner_id.property_stock_subcontractor.parent_path in subcontract_move.location_dest_id.parent_path ): # If the if-condition is respected, it means that `subcontract_move` is not # related to a specific warehouse. This can happen if, for instance, the user # confirms a PO with a subcontracted product that should be delivered to a # customer (dropshipping). In that case, we can use a default warehouse to # get the picking type default_warehouse = self.env['stock.warehouse'].search([('company_id', '=', subcontract_move.company_id.id)], limit=1) res['picking_type_id'] = default_warehouse.subcontracting_type_id.id, return res
47.631579
3,620
534
py
PYTHON
15.0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class StockRule(models.Model): _inherit = 'stock.rule' def _prepare_purchase_order(self, company_id, origins, values): if 'partner_id' not in values[0] and company_id.subcontracting_location_id.parent_path in self.location_id.parent_path: values[0]['partner_id'] = values[0]['group_id'].partner_id.id return super()._prepare_purchase_order(company_id, origins, values)
41.076923
534
551
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Google Maps', 'category': 'Website/Website', 'summary': 'Show your company address on Google Maps', 'version': '1.0', 'description': """ Show your company address/partner address on Google Maps. Configure an API key in the Website settings. """, 'depends': ['base_geolocalize', 'website_partner'], 'data': [ 'views/google_map_templates.xml', ], 'installable': True, 'license': 'LGPL-3', }
32.411765
551
2,438
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http from odoo.http import request from odoo.tools.json import scriptsafe class GoogleMap(http.Controller): ''' This class generates on-the-fly partner maps that can be reused in every website page. To do so, just use an ``<iframe ...>`` whose ``src`` attribute points to ``/google_map`` (this controller generates a complete HTML5 page). URL query parameters: - ``partner_ids``: a comma-separated list of ids (partners to be shown) - ``partner_url``: the base-url to display the partner (eg: if ``partner_url`` is ``/partners/``, when the user will click on a partner on the map, it will be redirected to <myodoo>.com/partners/<id>) In order to resize the map, simply resize the ``iframe`` with CSS directives ``width`` and ``height``. ''' @http.route(['/google_map'], type='http', auth="public", website=True, sitemap=False) def google_map(self, *arg, **post): clean_ids = [] for partner_id in post.get('partner_ids', "").split(","): try: clean_ids.append(int(partner_id)) except ValueError: pass partners = request.env['res.partner'].sudo().search([("id", "in", clean_ids), ('website_published', '=', True), ('is_company', '=', True)]) partner_data = { "counter": len(partners), "partners": [] } for partner in partners.with_context(show_address=True): partner_data["partners"].append({ 'id': partner.id, 'name': partner.name, 'address': '\n'.join(partner.name_get()[0][1].split('\n')[1:]), 'latitude': str(partner.partner_latitude), 'longitude': str(partner.partner_longitude), }) if 'customers' in post.get('partner_url', ''): partner_url = '/customers/' else: partner_url = '/partners/' google_maps_api_key = request.website.google_maps_api_key values = { 'partner_url': partner_url, 'partner_data': scriptsafe.dumps(partner_data), 'google_maps_api_key': google_maps_api_key, } return request.render("website_google_map.google_map", values)
42.034483
2,438
492
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'United States - Accounting', 'version': '1.1', 'category': 'Accounting/Localizations/Account Charts', 'description': """ United States - Chart of accounts. ================================== """, 'depends': ['l10n_generic_coa'], 'data': [ 'data/res_company_data.xml', 'views/res_partner_bank_views.xml' ], 'license': 'LGPL-3', }
27.333333
492
654
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from odoo import fields, models, api, _ from odoo.exceptions import ValidationError class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' aba_routing = fields.Char(string="ABA/Routing", help="American Bankers Association Routing Number") @api.constrains('aba_routing') def _check_aba_routing(self): for bank in self: if bank.aba_routing and not re.match(r'^\d{1,9}$', bank.aba_routing): raise ValidationError(_('ABA/Routing should only contains numbers (maximum 9 digits).'))
36.333333
654
1,054
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Lead Generation', 'summary': 'Generate Leads/Opportunities based on country, industries, size, etc.', 'category': 'Sales/CRM', 'version': '1.2', 'depends': [ 'iap_crm', 'iap_mail', ], 'data': [ 'data/crm.iap.lead.industry.csv', 'data/crm.iap.lead.role.csv', 'data/crm.iap.lead.seniority.csv', 'data/mail_template_data.xml', 'data/ir_sequence_data.xml', 'security/ir.model.access.csv', 'views/crm_lead_views.xml', 'views/crm_iap_lead_mining_request_views.xml', 'views/res_config_settings_views.xml', 'views/mail_templates.xml', 'views/crm_menus.xml', ], 'auto_install': True, 'assets': { 'web.assets_backend': [ 'crm_iap_mine/static/src/js/**/*', ], 'web.assets_qweb': [ 'crm_iap_mine/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
29.277778
1,054
3,762
py
PYTHON
15.0
# -*- coding: utf-8 -*- from contextlib import contextmanager from unittest.mock import patch from odoo import exceptions from odoo.addons.crm.models.crm_lead import Lead from odoo.addons.crm_iap_mine.models.crm_iap_lead_mining_request import CRMLeadMiningRequest from odoo.addons.iap.tests.common import MockIAPEnrich from odoo.addons.iap.tools import iap_tools class MockIAPReveal(MockIAPEnrich): @classmethod def setUpClass(cls): super(MockIAPReveal, cls).setUpClass() cls._new_leads = cls.env['crm.lead'].sudo() cls.mine = False @contextmanager def mock_IAP_mine(self, mine, name_list=None, default_data=None, sim_error=None): self._new_leads = self.env['crm.lead'].sudo() self.mine = mine crm_lead_create_origin = Lead.create def _crm_lead_create(model, *args, **kwargs): res = crm_lead_create_origin(model, *args, **kwargs) self._new_leads += res.sudo() return res def _iap_contact_mining(params, timeout): self.assertMineCallParams(params) self.assertMinePayload(mine, params['data']) if sim_error and sim_error == 'credit': raise iap_tools.InsufficientCreditError('InsufficientCreditError') if sim_error and sim_error == 'jsonrpc_exception': raise exceptions.AccessError( 'The url that this service requested returned an error. Please contact the author of the app. The url it tried to contact was [STRIPPED]' ) if sim_error and sim_error == 'no_result': return {'credit_error': False, 'data': []} response = [] for counter in range(0, mine.lead_number): if name_list: base_name = name_list[counter % len(name_list)] else: base_name = 'heinrich_%d' % counter iap_payload = {} company_data = self._get_iap_company_data(base_name, service='mine') if default_data: company_data.update(default_data) iap_payload['company_data'] = company_data if mine.search_type == 'people': people_data = self._get_iap_contact_data(base_name, service='mine') iap_payload['people_data'] = people_data response.append(iap_payload) return { 'data': response, 'credit_error': False } with patch.object(CRMLeadMiningRequest, '_iap_contact_mining', side_effect=_iap_contact_mining), \ patch.object(Lead, 'create', autospec=True, wraps=Lead, side_effect=_crm_lead_create): yield def _get_iap_company_data(self, base_name, service=None, add_values=None): company_data = super(MockIAPReveal, self)._get_iap_company_data(base_name, service=service, add_values=add_values) if service == 'mine': company_data['phone'] = company_data['phone_numbers'][0] company_data['sector'] = 'Sector Info' return company_data def assertMineCallParams(self, params): self.assertTrue(bool(params['account_token'])) self.assertTrue(bool(params['dbuuid'])) def assertMinePayload(self, mine, payload): if mine.search_type == 'people': self.assertEqual(payload['contact_number'], mine.contact_number) else: self.assertTrue('contact_number' not in payload) self.assertEqual(payload['countries'], mine.mapped('country_ids.code')) self.assertEqual(payload['lead_number'], mine.lead_number) self.assertEqual(payload['search_type'], mine.search_type)
41.340659
3,762
6,394
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import exceptions from odoo.addons.crm.tests.common import TestCrmCommon from odoo.addons.crm_iap_mine.tests.common import MockIAPReveal from odoo.tests.common import users class TestLeadMine(TestCrmCommon, MockIAPReveal): @classmethod def setUpClass(cls): super(TestLeadMine, cls).setUpClass() cls.registry.enter_test_mode(cls.cr) cls.test_crm_tags = cls.env['crm.tag'].create([ {'name': 'TestTag1'}, {'name': 'TestTag2'} ]) cls.test_request = cls.env['crm.iap.lead.mining.request'].create({ 'contact_number': 3, 'error_type': False, 'lead_number': 3, 'lead_type': 'lead', 'name': 'Test Mine', 'search_type': 'people', 'state': 'draft', 'tag_ids': [(6, 0, cls.test_crm_tags.ids)], 'team_id': cls.sales_team_1.id, 'user_id': cls.user_sales_leads.id, }) @classmethod def tearDownClass(cls): cls.registry.leave_test_mode() super().tearDownClass() @users('user_sales_manager') def test_mine_error_credit(self): mine_request = self.env['crm.iap.lead.mining.request'].browse(self.test_request.ids) with self.mock_IAP_mine(mine_request, sim_error='credit'): mine_request.action_submit() self.assertEqual(mine_request.error_type, 'credits') self.assertEqual(mine_request.state, 'error') @users('user_sales_manager') def test_mine_error_jsonrpc_exception(self): mine_request = self.env['crm.iap.lead.mining.request'].browse(self.test_request.ids) with self.assertRaises(exceptions.UserError): with self.mock_IAP_mine(mine_request, sim_error='jsonrpc_exception'): mine_request.action_submit() @users('user_sales_manager') def test_mine_error_no_result(self): mine_request = self.env['crm.iap.lead.mining.request'].browse(self.test_request.ids) with self.mock_IAP_mine(mine_request, sim_error='no_result'): mine_request.action_submit() self.assertEqual(mine_request.error_type, 'no_result') self.assertEqual(mine_request.state, 'draft') @users('user_sales_manager') def test_mine_wpeople(self): country_de = self.base_de state_de = self.de_state_st mine_request = self.env['crm.iap.lead.mining.request'].browse(self.test_request.ids) with self.mock_IAP_mine(mine_request, name_list=['Heinrich', 'Rivil', 'LidGen']): mine_request.action_submit() self.assertFalse(mine_request.error_type) self.assertEqual(mine_request.state, 'done') self.assertEqual(len(self._new_leads), 3, 'Number of leads should match mine request') for base_name in ['Heinrich', 'Rivil', 'LidGen']: lead = self._new_leads.filtered(lambda lead: lead.name == '%s GmbH' % base_name) self.assertTrue(bool(lead)) # mine information self.assertEqual(lead.type, 'lead') self.assertEqual(lead.tag_ids, self.test_crm_tags) self.assertEqual(lead.team_id, self.sales_team_1) self.assertEqual(lead.user_id, self.user_sales_leads) # iap self.assertEqual(lead.reveal_id, '123_ClearbitID_%s' % base_name, 'Ensure reveal_id is set to clearbit ID') # clearbit information self.assertEqual(lead.contact_name, 'Contact %s 0' % base_name) self.assertEqual(lead.city, 'Mönchengladbach') self.assertEqual(lead.country_id, country_de) self.assertEqual(lead.email_from, 'test.contact.0@%s.example.com' % base_name, 'Lead email should be the one from first contact if search_type people is given') self.assertEqual(lead.function, 'Doing stuff') self.assertFalse(lead.partner_id) self.assertEqual(lead.partner_name, '%s GmbH legal_name' % base_name) self.assertEqual(lead.phone, '+4930499193937') self.assertEqual(lead.state_id, state_de) self.assertEqual(lead.street, 'Mennrather Str. 123456') self.assertEqual(lead.website, 'https://www.%s.de' % base_name) self.assertEqual(lead.zip, '41179') @users('user_sales_manager') def test_mine_wcompany(self): country_de = self.base_de state_de = self.de_state_st mine_request = self.env['crm.iap.lead.mining.request'].browse(self.test_request.ids) mine_request.write({'search_type': 'companies'}) with self.mock_IAP_mine(mine_request, name_list=['Heinrich', 'Rivil', 'LidGen']): mine_request.action_submit() self.assertFalse(mine_request.error_type) self.assertEqual(mine_request.state, 'done') self.assertEqual(len(self._new_leads), 3, 'Number of leads should match mine request') for base_name in ['Heinrich', 'Rivil', 'LidGen']: lead = self._new_leads.filtered(lambda lead: lead.name == '%s GmbH' % base_name) self.assertTrue(bool(lead)) # mine information self.assertEqual(lead.type, 'lead') self.assertEqual(lead.tag_ids, self.test_crm_tags) self.assertEqual(lead.team_id, self.sales_team_1) self.assertEqual(lead.user_id, self.user_sales_leads) # iap self.assertEqual(lead.reveal_id, '123_ClearbitID_%s' % base_name, 'Ensure reveal_id is set to clearbit ID') # clearbit information self.assertFalse(lead.contact_name) self.assertEqual(lead.city, 'Mönchengladbach') self.assertEqual(lead.country_id, country_de) self.assertEqual(lead.email_from, 'info@%s.example.com' % base_name) self.assertFalse(lead.function) self.assertFalse(lead.partner_id) self.assertEqual(lead.partner_name, '%s GmbH legal_name' % base_name) self.assertEqual(lead.phone, '+4930499193937') self.assertEqual(lead.state_id, state_de) self.assertEqual(lead.street, 'Mennrather Str. 123456') self.assertEqual(lead.website, 'https://www.%s.de' % base_name) self.assertEqual(lead.zip, '41179')
45.014085
6,392
718
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class CrmIapLeadIndustry(models.Model): """ Industry Tags of Acquisition Rules """ _name = 'crm.iap.lead.industry' _description = 'CRM IAP Lead Industry' _order = 'sequence,id' name = fields.Char(string='Industry', required=True, translate=True) reveal_ids = fields.Char(required=True, help="The list of reveal_ids for this industry, separated with ','") color = fields.Integer(string='Color Index') sequence = fields.Integer('Sequence') _sql_constraints = [ ('name_uniq', 'unique (name)', 'Industry name already exists!'), ]
34.190476
718
1,190
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class PeopleRole(models.Model): """ CRM Reveal People Roles for People """ _name = 'crm.iap.lead.role' _description = 'People Role' name = fields.Char(string='Role Name', required=True, translate=True) reveal_id = fields.Char(required=True) color = fields.Integer(string='Color Index') _sql_constraints = [ ('name_uniq', 'unique (name)', 'Role name already exists!'), ] @api.depends('name') def name_get(self): return [(role.id, role.name.replace('_', ' ').title()) for role in self] class PeopleSeniority(models.Model): """ Seniority for People Rules """ _name = 'crm.iap.lead.seniority' _description = 'People Seniority' name = fields.Char(string='Name', required=True, translate=True) reveal_id = fields.Char(required=True) _sql_constraints = [ ('name_uniq', 'unique (name)', 'Name already exists!'), ] @api.depends('name') def name_get(self): return [(seniority.id, seniority.name.replace('_', ' ').title()) for seniority in self]
30.512821
1,190
15,788
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models, _ from odoo.addons.iap.tools import iap_tools from odoo.exceptions import UserError _logger = logging.getLogger(__name__) DEFAULT_ENDPOINT = 'https://iap-services.odoo.com' MAX_LEAD = 200 MAX_CONTACT = 5 CREDIT_PER_COMPANY = 1 CREDIT_PER_CONTACT = 1 class CRMLeadMiningRequest(models.Model): _name = 'crm.iap.lead.mining.request' _description = 'CRM Lead Mining Request' def _default_lead_type(self): if self.env.user.has_group('crm.group_use_lead'): return 'lead' else: return 'opportunity' def _default_country_ids(self): return self.env.user.company_id.country_id name = fields.Char(string='Request Number', required=True, readonly=True, default=lambda self: _('New'), copy=False) state = fields.Selection([('draft', 'Draft'), ('error', 'Error'), ('done', 'Done')], string='Status', required=True, default='draft') # Request Data lead_number = fields.Integer(string='Number of Leads', required=True, default=3) search_type = fields.Selection([('companies', 'Companies'), ('people', 'Companies and their Contacts')], string='Target', required=True, default='companies') error_type = fields.Selection([ ('credits', 'Insufficient Credits'), ('no_result', 'No Result'), ], string='Error Type', copy=False, readonly=True) # Lead / Opportunity Data lead_type = fields.Selection([('lead', 'Leads'), ('opportunity', 'Opportunities')], string='Type', required=True, default=_default_lead_type) display_lead_label = fields.Char(compute='_compute_display_lead_label') team_id = fields.Many2one( 'crm.team', string='Sales Team', ondelete="set null", domain="[('use_opportunities', '=', True)]", readonly=False, compute='_compute_team_id', store=True) user_id = fields.Many2one('res.users', string='Salesperson', default=lambda self: self.env.user) tag_ids = fields.Many2many('crm.tag', string='Tags') lead_ids = fields.One2many('crm.lead', 'lead_mining_request_id', string='Generated Lead / Opportunity') lead_count = fields.Integer(compute='_compute_lead_count', string='Number of Generated Leads') # Company Criteria Filter filter_on_size = fields.Boolean(string='Filter on Size', default=False) company_size_min = fields.Integer(string='Size', default=1) company_size_max = fields.Integer(default=1000) country_ids = fields.Many2many('res.country', string='Countries', default=_default_country_ids) state_ids = fields.Many2many('res.country.state', string='States') available_state_ids = fields.One2many('res.country.state', compute='_compute_available_state_ids', help="List of available states based on selected countries") industry_ids = fields.Many2many('crm.iap.lead.industry', string='Industries') # Contact Generation Filter contact_number = fields.Integer(string='Number of Contacts', default=10) contact_filter_type = fields.Selection([('role', 'Role'), ('seniority', 'Seniority')], string='Filter on', default='role') preferred_role_id = fields.Many2one('crm.iap.lead.role', string='Preferred Role') role_ids = fields.Many2many('crm.iap.lead.role', string='Other Roles') seniority_id = fields.Many2one('crm.iap.lead.seniority', string='Seniority') # Fields for the blue tooltip lead_credits = fields.Char(compute='_compute_tooltip', readonly=True) lead_contacts_credits = fields.Char(compute='_compute_tooltip', readonly=True) lead_total_credits = fields.Char(compute='_compute_tooltip', readonly=True) @api.depends('lead_type', 'lead_number') def _compute_display_lead_label(self): selection_description_values = { e[0]: e[1] for e in self._fields['lead_type']._description_selection(self.env)} for request in self: lead_type = selection_description_values[request.lead_type] request.display_lead_label = '%s %s' % (request.lead_number, lead_type) @api.onchange('lead_number', 'contact_number') def _compute_tooltip(self): for record in self: company_credits = CREDIT_PER_COMPANY * record.lead_number contact_credits = CREDIT_PER_CONTACT * record.contact_number total_contact_credits = contact_credits * record.lead_number record.lead_contacts_credits = _("Up to %d additional credits will be consumed to identify %d contacts per company.") % (contact_credits*company_credits, record.contact_number) record.lead_credits = _('%d credits will be consumed to find %d companies.') % (company_credits, record.lead_number) record.lead_total_credits = _("This makes a total of %d credits for this request.") % (total_contact_credits + company_credits) @api.depends('lead_ids.lead_mining_request_id') def _compute_lead_count(self): if self.ids: leads_data = self.env['crm.lead'].read_group( [('lead_mining_request_id', 'in', self.ids)], ['lead_mining_request_id'], ['lead_mining_request_id']) else: leads_data = [] mapped_data = dict( (m['lead_mining_request_id'][0], m['lead_mining_request_id_count']) for m in leads_data) for request in self: request.lead_count = mapped_data.get(request.id, 0) @api.depends('user_id', 'lead_type') def _compute_team_id(self): """ When changing the user, also set a team_id or restrict team id to the ones user_id is member of. """ for mining in self: # setting user as void should not trigger a new team computation if not mining.user_id: continue user = mining.user_id if mining.team_id and user in mining.team_id.member_ids | mining.team_id.user_id: continue team_domain = [('use_leads', '=', True)] if mining.lead_type == 'lead' else [('use_opportunities', '=', True)] team = self.env['crm.team']._get_default_team_id(user_id=user.id, domain=team_domain) mining.team_id = team.id @api.depends('country_ids') def _compute_available_state_ids(self): """ States for some specific countries should not be offered as filtering options because they drastically reduce the amount of IAP reveal results. For example, in Belgium, only 11% of companies have a defined state within the reveal service while the rest of them have no state defined at all. Meaning specifying states for that country will yield a lot less results than what you could expect, which is not the desired behavior. Obviously all companies are active within a state, it's just a lack of data in the reveal service side. To help users create meaningful iap searches, we only keep the states filtering for several whitelisted countries (based on their country code). The complete list and reasons for this change can be found on task-2471703. """ for lead_mining_request in self: countries = lead_mining_request.country_ids.filtered(lambda country: country.code in iap_tools._STATES_FILTER_COUNTRIES_WHITELIST) lead_mining_request.available_state_ids = self.env['res.country.state'].search([ ('country_id', 'in', countries.ids) ]) @api.onchange('available_state_ids') def _onchange_available_state_ids(self): self.state_ids -= self.state_ids.filtered( lambda state: (state._origin.id or state.id) not in self.available_state_ids.ids ) @api.onchange('lead_number') def _onchange_lead_number(self): if self.lead_number <= 0: self.lead_number = 1 elif self.lead_number > MAX_LEAD: self.lead_number = MAX_LEAD @api.onchange('contact_number') def _onchange_contact_number(self): if self.contact_number <= 0: self.contact_number = 1 elif self.contact_number > MAX_CONTACT: self.contact_number = MAX_CONTACT @api.onchange('country_ids') def _onchange_country_ids(self): self.state_ids = [] @api.onchange('company_size_min') def _onchange_company_size_min(self): if self.company_size_min <= 0: self.company_size_min = 1 elif self.company_size_min > self.company_size_max: self.company_size_min = self.company_size_max @api.onchange('company_size_max') def _onchange_company_size_max(self): if self.company_size_max < self.company_size_min: self.company_size_max = self.company_size_min @api.model def get_empty_list_help(self, help_string): help_title = _('Create a Lead Mining Request') sub_title = _('Generate new leads based on their country, industry, size, etc.') return '<p class="o_view_nocontent_smiling_face">%s</p><p class="oe_view_nocontent_alias">%s</p>' % (help_title, sub_title) def _prepare_iap_payload(self): """ This will prepare the data to send to the server """ self.ensure_one() payload = {'lead_number': self.lead_number, 'search_type': self.search_type, 'countries': self.country_ids.mapped('code')} if self.state_ids: payload['states'] = self.state_ids.mapped('code') if self.filter_on_size: payload.update({'company_size_min': self.company_size_min, 'company_size_max': self.company_size_max}) if self.industry_ids: # accumulate all reveal_ids (separated by ',') into one list # eg: 3 records with values: "175,176", "177" and "190,191" # will become ['175','176','177','190','191'] all_industry_ids = [ reveal_id.strip() for reveal_ids in self.mapped('industry_ids.reveal_ids') for reveal_id in reveal_ids.split(',') ] payload['industry_ids'] = all_industry_ids if self.search_type == 'people': payload.update({'contact_number': self.contact_number, 'contact_filter_type': self.contact_filter_type}) if self.contact_filter_type == 'role': payload.update({'preferred_role': self.preferred_role_id.reveal_id, 'other_roles': self.role_ids.mapped('reveal_id')}) elif self.contact_filter_type == 'seniority': payload['seniority'] = self.seniority_id.reveal_id return payload def _perform_request(self): """ This will perform the request and create the corresponding leads. The user will be notified if he hasn't enough credits. """ self.error_type = False server_payload = self._prepare_iap_payload() reveal_account = self.env['iap.account'].get('reveal') dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid') params = { 'account_token': reveal_account.account_token, 'dbuuid': dbuuid, 'data': server_payload } try: response = self._iap_contact_mining(params, timeout=300) if not response.get('data'): self.error_type = 'no_result' return False return response['data'] except iap_tools.InsufficientCreditError as e: self.error_type = 'credits' self.state = 'error' return False except Exception as e: raise UserError(_("Your request could not be executed: %s", e)) def _iap_contact_mining(self, params, timeout=300): endpoint = self.env['ir.config_parameter'].sudo().get_param('reveal.endpoint', DEFAULT_ENDPOINT) + '/iap/clearbit/1/lead_mining_request' return iap_tools.iap_jsonrpc(endpoint, params=params, timeout=timeout) def _create_leads_from_response(self, result): """ This method will get the response from the service and create the leads accordingly """ self.ensure_one() lead_vals_list = [] messages_to_post = {} for data in result: lead_vals_list.append(self._lead_vals_from_response(data)) template_values = data['company_data'] template_values.update({ 'flavor_text': _("Opportunity created by Odoo Lead Generation"), 'people_data': data.get('people_data'), }) messages_to_post[data['company_data']['clearbit_id']] = template_values leads = self.env['crm.lead'].create(lead_vals_list) for lead in leads: if messages_to_post.get(lead.reveal_id): lead.message_post_with_view('iap_mail.enrich_company', values=messages_to_post[lead.reveal_id], subtype_id=self.env.ref('mail.mt_note').id) # Methods responsible for format response data into valid odoo lead data @api.model def _lead_vals_from_response(self, data): self.ensure_one() company_data = data.get('company_data') people_data = data.get('people_data') lead_vals = self.env['crm.iap.lead.helpers'].lead_vals_from_response(self.lead_type, self.team_id.id, self.tag_ids.ids, self.user_id.id, company_data, people_data) lead_vals['lead_mining_request_id'] = self.id return lead_vals def action_draft(self): self.ensure_one() self.name = _('New') self.state = 'draft' def action_submit(self): self.ensure_one() if self.name == _('New'): self.name = self.env['ir.sequence'].next_by_code('crm.iap.lead.mining.request') or _('New') results = self._perform_request() if results: self._create_leads_from_response(results) self.state = 'done' if self.lead_type == 'lead': return self.action_get_lead_action() elif self.lead_type == 'opportunity': return self.action_get_opportunity_action() elif self.env.context.get('is_modal'): # when we are inside a modal already, we re-open the same record # that way, the form view is updated and the correct error message appears # (sadly, there is no way to simply 'reload' a form view within a modal) return { 'name': _('Generate Leads'), 'res_model': 'crm.iap.lead.mining.request', 'views': [[False, 'form']], 'target': 'new', 'type': 'ir.actions.act_window', 'res_id': self.id, 'context': dict(self.env.context, edit=True, form_view_initial_mode='edit') } else: # will reload the form view and show the error message on top return False def action_get_lead_action(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_all_leads") action['domain'] = [('id', 'in', self.lead_ids.ids), ('type', '=', 'lead')] return action def action_get_opportunity_action(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_opportunities") action['domain'] = [('id', 'in', self.lead_ids.ids), ('type', '=', 'opportunity')] return action def action_buy_credits(self): return { 'type': 'ir.actions.act_url', 'url': self.env['iap.account'].get_credits_url(service_name='reveal'), }
46.572271
15,788
305
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class Lead(models.Model): _inherit = 'crm.lead' lead_mining_request_id = fields.Many2one('crm.iap.lead.mining.request', string='Lead Mining Request', index=True)
30.5
305
3,242
py
PYTHON
15.0
from math import floor, log10 from odoo import api, models class CRMHelpers(models.Model): _name = 'crm.iap.lead.helpers' _description = 'Helper methods for crm_iap_mine modules' @api.model def notify_no_more_credit(self, service_name, model_name, notification_parameter): """ Notify about the number of credit. In order to avoid to spam people each hour, an ir.config_parameter is set """ already_notified = self.env['ir.config_parameter'].sudo().get_param(notification_parameter, False) if already_notified: return mail_template = self.env.ref('crm_iap_mine.lead_generation_no_credits') iap_account = self.env['iap.account'].search([('service_name', '=', service_name)], limit=1) # Get the email address of the creators of the records res = self.env[model_name].search_read([], ['create_uid']) uids = set(r['create_uid'][0] for r in res if r.get('create_uid')) res = self.env['res.users'].search_read([('id', 'in', list(uids))], ['email']) emails = set(r['email'] for r in res if r.get('email')) email_values = { 'email_to': ','.join(emails) } mail_template.send_mail(iap_account.id, force_send=True, email_values=email_values) self.env['ir.config_parameter'].sudo().set_param(notification_parameter, True) @api.model def lead_vals_from_response(self, lead_type, team_id, tag_ids, user_id, company_data, people_data): country_id = self.env['res.country'].search([('code', '=', company_data['country_code'])]).id website_url = 'https://www.%s' % company_data['domain'] if company_data['domain'] else False lead_vals = { # Lead vals from record itself 'type': lead_type, 'team_id': team_id, 'tag_ids': [(6, 0, tag_ids)], 'user_id': user_id, 'reveal_id': company_data['clearbit_id'], # Lead vals from data 'name': company_data['name'] or company_data['domain'], 'partner_name': company_data['legal_name'] or company_data['name'], 'email_from': next(iter(company_data.get('email', [])), ''), 'phone': company_data['phone'] or (company_data['phone_numbers'] and company_data['phone_numbers'][0]) or '', 'website': website_url, 'street': company_data['location'], 'city': company_data['city'], 'zip': company_data['postal_code'], 'country_id': country_id, 'state_id': self._find_state_id(company_data['state_code'], country_id), } # If type is people then add first contact in lead data if people_data: lead_vals.update({ 'contact_name': people_data[0]['full_name'], 'email_from': people_data[0]['email'], 'function': people_data[0]['title'], }) return lead_vals @api.model def _find_state_id(self, state_code, country_id): state_id = self.env['res.country.state'].search([('code', '=', state_code), ('country_id', '=', country_id)]) if state_id: return state_id.id return False
46.314286
3,242
645
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class PeopleSeniority(models.Model): """ Seniority for People Rules """ _name = 'crm.iap.lead.seniority' _description = 'People Seniority' name = fields.Char(string='Name', required=True, translate=True) reveal_id = fields.Char(required=True) _sql_constraints = [ ('name_uniq', 'unique (name)', 'Name already exists!'), ] @api.depends('name') def name_get(self): return [(seniority.id, seniority.name.replace('_', ' ').title()) for seniority in self]
30.714286
645
995
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Belgium - E-Invoicing (UBL 2.0, e-fff)', 'icon': '/l10n_be/static/description/icon.png', 'version': '0.1', 'category': 'Accounting/Localizations/EDI', 'summary': 'E-Invoicing, Universal Business Language (UBL 2.0), e-fff protocol', 'description': """ Universal Business Language (UBL <http://ubl.xml.org/>`_) is a library of standard electronic XML business documents such as invoices. The UBL standard became the `ISO/IEC 19845 <http://www.iso.org/iso/catalogue_detail.htm?csnumber=66370>`_ standard in January 2016 (cf the `official announce <http://www.prweb.com/releases/2016/01/prweb13186919.htm>`_). Belgian e-invoicing uses the UBL 2.0 using the e-fff protocol. """, 'depends': ['l10n_be', 'account_edi_ubl'], 'data': [ 'data/account_edi_data.xml', 'data/ubl_templates.xml', ], 'installable': True, 'auto_install': True, 'post_init_hook': '_post_init_hook', 'license': 'LGPL-3', }
41.458333
995
8,203
py
PYTHON
15.0
# -*- coding: utf-8 -*- import base64 import io from PyPDF2 import PdfFileWriter, PdfFileReader from odoo.addons.account_edi.tests.common import AccountEdiTestCommon from odoo.tests import tagged @tagged('post_install_l10n', 'post_install', '-at_install') class TestUBLBE(AccountEdiTestCommon): @classmethod def setUpClass(cls, chart_template_ref='l10n_be.l10nbe_chart_template', edi_format_ref='l10n_be_edi.edi_efff_1'): super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) if cls.env['ir.module.module'].search( [('name', '=', 'account_edi_ubl_cii'), ('state', '=', 'installed')], limit=1, ): cls.skipTest(cls, "L10n_be_edi Tests skipped because account_edi_ubl_cii is installed.") cls.partner_a.write({ 'street': "Chaussée de Namur 40", 'zip': "1367", 'city': "Ramillies", 'vat': 'BE0202239951', 'country_id': cls.env.ref('base.be').id, }) cls.env.company.write({ 'street': "Rue des Bourlottes 9", 'zip': "1367", 'city': "Ramillies", 'vat': 'BE0477472701', 'country_id': cls.env.ref('base.be').id, }) cls.tax_21 = cls.env['account.tax'].create({ 'name': 'tax_21', 'amount_type': 'percent', 'amount': 21, 'type_tax_use': 'sale', }) def test_out_invoice_efff(self): invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'ref': 'test invoice ref', 'narration': 'test narration', 'invoice_line_ids': [(0, 0, { 'price_unit': 1000.0, 'product_id': self.product_a.id, 'tax_ids': [(6, 0, self.tax_21.ids)], })], }) invoice.action_post() # Print the invoice to append AdditionalDocumentReference. pdf_buffer = io.BytesIO() pdf_writer = PdfFileWriter() pdf_writer.addBlankPage(42, 42) pdf_writer.write(pdf_buffer) self.env.ref('account.account_invoices_without_payment')._postprocess_pdf_report(invoice, pdf_buffer) pdf_buffer.close() attachment = invoice._get_edi_attachment(self.edi_format) self.assertTrue(attachment) xml_content = base64.b64decode(attachment.datas) current_etree = self.get_xml_tree_from_string(xml_content) expected_etree = self.get_xml_tree_from_string(f''' <Invoice> <UBLVersionID>2.0</UBLVersionID> <ID>{invoice.name}</ID> <IssueDate>2017-01-01</IssueDate> <InvoiceTypeCode>380</InvoiceTypeCode> <Note>test narration</Note> <DocumentCurrencyCode>EUR</DocumentCurrencyCode> <OrderReference> <ID>test invoice ref</ID> </OrderReference> <AdditionalDocumentReference> <ID>efff_BE0477472701_INV201700001.pdf</ID> <Attachment> <EmbeddedDocumentBinaryObject mimeCode="application/pdf" filename="efff_BE0477472701_INV201700001.pdf">___ignore___</EmbeddedDocumentBinaryObject> </Attachment> </AdditionalDocumentReference> <AccountingSupplierParty> <Party> <PartyName> <Name>company_1_data</Name> </PartyName> <Language> <LocaleCode>en_US</LocaleCode> </Language> <PostalAddress> <StreetName>Rue des Bourlottes 9</StreetName> <CityName>Ramillies</CityName> <PostalZone>1367</PostalZone> <Country> <IdentificationCode>BE</IdentificationCode> <Name>Belgium</Name> </Country> </PostalAddress> <PartyTaxScheme> <RegistrationName>company_1_data</RegistrationName> <CompanyID>BE0477472701</CompanyID> <TaxScheme> <ID schemeID="UN/ECE 5153" schemeAgencyID="6">VAT</ID> </TaxScheme> </PartyTaxScheme> <Contact> <Name>company_1_data</Name> </Contact> </Party> </AccountingSupplierParty> <AccountingCustomerParty> <Party> <PartyName> <Name>partner_a</Name> </PartyName> <Language> <LocaleCode>en_US</LocaleCode> </Language> <PostalAddress> <StreetName>Chaussée de Namur 40</StreetName> <CityName>Ramillies</CityName> <PostalZone>1367</PostalZone> <Country> <IdentificationCode>BE</IdentificationCode> <Name>Belgium</Name> </Country> </PostalAddress> <PartyTaxScheme> <RegistrationName>partner_a</RegistrationName> <CompanyID>BE0202239951</CompanyID> <TaxScheme> <ID schemeID="UN/ECE 5153" schemeAgencyID="6">VAT</ID> </TaxScheme> </PartyTaxScheme> <Contact> <Name>partner_a</Name> </Contact> </Party> </AccountingCustomerParty> <PaymentMeans> <PaymentMeansCode listID="UN/ECE 4461">31</PaymentMeansCode> <PaymentDueDate>2017-02-28</PaymentDueDate> <InstructionID>{invoice.name}</InstructionID> </PaymentMeans> <PaymentTerms> <Note>30% Advance End of Following Month</Note> </PaymentTerms> <TaxTotal> <TaxAmount currencyID="EUR">210.00</TaxAmount> </TaxTotal> <LegalMonetaryTotal> <LineExtensionAmount currencyID="EUR">1000.00</LineExtensionAmount> <TaxExclusiveAmount currencyID="EUR">1000.00</TaxExclusiveAmount> <TaxInclusiveAmount currencyID="EUR">1210.00</TaxInclusiveAmount> <PrepaidAmount currencyID="EUR">0.00</PrepaidAmount> <PayableAmount currencyID="EUR">1210.00</PayableAmount> </LegalMonetaryTotal> <InvoiceLine> <ID>___ignore___</ID> <InvoicedQuantity>1.0</InvoicedQuantity> <LineExtensionAmount currencyID="EUR">1000.00</LineExtensionAmount> <TaxTotal> <TaxAmount currencyID="EUR">210.00</TaxAmount> </TaxTotal> <Item> <Description>product_a</Description> <Name>product_a</Name> </Item> <Price> <PriceAmount currencyID="EUR">1000.00</PriceAmount> </Price> </InvoiceLine> </Invoice> ''') self.assertXmlTreeEqual(current_etree, expected_etree)
43.62234
8,201
8,898
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account_edi.tests.common import AccountEdiTestCommon from odoo.tests import tagged from odoo import Command @tagged('post_install_l10n', 'post_install', '-at_install') class TestL10nBeEdi(AccountEdiTestCommon): @classmethod def setUpClass(cls, chart_template_ref='l10n_be.l10nbe_chart_template', edi_format_ref='l10n_be_edi.edi_efff_1'): super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) if cls.env['ir.module.module'].search( [('name', '=', 'account_edi_ubl_cii'), ('state', '=', 'installed')], limit=1, ): cls.skipTest(cls, "L10n_be_edi Tests skipped because account_edi_ubl_cii is installed.") # ==== Init ==== cls.tax_10_include = cls.env['account.tax'].create({ 'name': 'tax_10_include', 'amount_type': 'percent', 'amount': 10, 'type_tax_use': 'sale', 'price_include': True, 'include_base_amount': True, 'sequence': 10, }) cls.tax_20 = cls.env['account.tax'].create({ 'name': 'tax_20', 'amount_type': 'percent', 'amount': 20, 'invoice_repartition_line_ids': [ (0, 0, {'factor_percent': 100.0, 'repartition_type': 'base'}), (0, 0, {'factor_percent': 40.0, 'repartition_type': 'tax'}), (0, 0, {'factor_percent': 60.0, 'repartition_type': 'tax'}), ], 'refund_repartition_line_ids': [ (0, 0, {'factor_percent': 100.0, 'repartition_type': 'base'}), (0, 0, {'factor_percent': 40.0, 'repartition_type': 'tax'}), (0, 0, {'factor_percent': 60.0, 'repartition_type': 'tax'}), ], 'type_tax_use': 'sale', 'sequence': 20, }) cls.tax_group = cls.env['account.tax'].create({ 'name': 'tax_group', 'amount_type': 'group', 'amount': 0.0, 'type_tax_use': 'sale', 'children_tax_ids': [(6, 0, (cls.tax_10_include + cls.tax_20).ids)], }) cls.partner_a.vat = 'BE0477472701' # ==== Invoice ==== cls.invoice = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': cls.journal.id, 'partner_id': cls.partner_b.id, 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, { 'product_id': cls.product_a.id, 'product_uom_id': cls.env.ref('uom.product_uom_dozen').id, 'price_unit': 275.0, 'quantity': 5, 'discount': 20.0, 'tax_ids': [(6, 0, cls.tax_20.ids)], })], }) cls.expected_invoice_efff_values = ''' <Invoice> <UBLVersionID>2.0</UBLVersionID> <ID>INV/2017/00001</ID> <IssueDate>2017-01-01</IssueDate> <InvoiceTypeCode>380</InvoiceTypeCode> <DocumentCurrencyCode>Gol</DocumentCurrencyCode> <AccountingSupplierParty> <Party> <PartyName> <Name>company_1_data</Name> </PartyName> <Language> <LocaleCode>en_US</LocaleCode> </Language> <PostalAddress/> <Contact> <Name>company_1_data</Name> </Contact> </Party> </AccountingSupplierParty> <AccountingCustomerParty> <Party> <PartyName> <Name>partner_b</Name> </PartyName> <Language> <LocaleCode>en_US</LocaleCode> </Language> <PostalAddress/> <Contact> <Name>partner_b</Name> </Contact> </Party> </AccountingCustomerParty> <PaymentMeans> <PaymentMeansCode listID="UN/ECE 4461">31</PaymentMeansCode> <PaymentDueDate>2017-01-01</PaymentDueDate> <InstructionID>INV/2017/00001</InstructionID> </PaymentMeans> <TaxTotal> <TaxAmount currencyID="Gol">220.000</TaxAmount> </TaxTotal> <LegalMonetaryTotal> <LineExtensionAmount currencyID="Gol">1100.000</LineExtensionAmount> <TaxExclusiveAmount currencyID="Gol">1100.000</TaxExclusiveAmount> <TaxInclusiveAmount currencyID="Gol">1320.000</TaxInclusiveAmount> <PrepaidAmount currencyID="Gol">0.000</PrepaidAmount> <PayableAmount currencyID="Gol">1320.000</PayableAmount> </LegalMonetaryTotal> <InvoiceLine> <ID>___ignore___</ID> <Note>Discount (20.0 %)</Note> <InvoicedQuantity>5.0</InvoicedQuantity> <LineExtensionAmount currencyID="Gol">1100.000</LineExtensionAmount> <TaxTotal> <TaxAmount currencyID="Gol">220.000</TaxAmount> </TaxTotal> <Item> <Description>product_a</Description> <Name>product_a</Name> </Item> <Price> <PriceAmount currencyID="Gol">275.000</PriceAmount> </Price> </InvoiceLine> </Invoice> ''' #################################################### # Test export #################################################### def test_efff_simple_case(self): ''' Test the generated Facturx Edi attachment without any modification of the invoice. ''' self.assert_generated_file_equal(self.invoice, self.expected_invoice_efff_values) def test_efff_group_of_taxes(self): self.invoice.write({ 'invoice_line_ids': [(1, self.invoice.invoice_line_ids.id, {'tax_ids': [Command.set(self.tax_group.ids)]})], }) applied_xpath = ''' <xpath expr="//TaxTotal/TaxAmount" position="replace"> <TaxAmount currencyID="Gol">320.000</TaxAmount> </xpath> <xpath expr="//LegalMonetaryTotal/LineExtensionAmount" position="replace"> <LineExtensionAmount currencyID="Gol">1000.000</LineExtensionAmount> </xpath> <xpath expr="//LegalMonetaryTotal/TaxExclusiveAmount" position="replace"> <TaxExclusiveAmount currencyID="Gol">1000.000</TaxExclusiveAmount> </xpath> <xpath expr="//InvoiceLine/LineExtensionAmount" position="replace"> <LineExtensionAmount currencyID="Gol">1000.000</LineExtensionAmount> </xpath> <xpath expr="//InvoiceLine/TaxTotal" position="replace"> <TaxTotal> <TaxAmount currencyID="Gol">100.000</TaxAmount> </TaxTotal> <TaxTotal> <TaxAmount currencyID="Gol">220.000</TaxAmount> </TaxTotal> </xpath> ''' self.assert_generated_file_equal(self.invoice, self.expected_invoice_efff_values, applied_xpath) #################################################### # Test import #################################################### def test_invoice_edi_xml_update(self): invoice = self._create_empty_vendor_bill() invoice_count = len(self.env['account.move'].search([])) self.update_invoice_from_file('l10n_be_edi', 'test_xml_file', 'efff_test.xml', invoice) self.assertEqual(len(self.env['account.move'].search([])), invoice_count) self.assertEqual(invoice.amount_total, 666.50) self.assertEqual(invoice.amount_tax, 115.67) self.assertEqual(invoice.partner_id, self.partner_a) def test_invoice_edi_xml_create(self): invoice_count = len(self.env['account.move'].search([])) invoice = self.create_invoice_from_file('l10n_be_edi', 'test_xml_file', 'efff_test.xml') self.assertEqual(len(self.env['account.move'].search([])), invoice_count + 1) self.assertEqual(invoice.amount_total, 666.50) self.assertEqual(invoice.amount_tax, 115.67) self.assertEqual(invoice.partner_id, self.partner_a)
43.194175
8,898
375
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models import re class AccountMove(models.Model): _inherit = 'account.move' def _get_efff_name(self): self.ensure_one() vat = self.company_id.partner_id.commercial_partner_id.vat return 'efff_%s%s%s' % (vat or '', '_' if vat else '', re.sub(r'[\W_]', '', self.name)) # official naming convention
26.785714
375
2,500
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models import base64 import markupsafe class AccountEdiFormat(models.Model): _inherit = 'account.edi.format' #################################################### # Export #################################################### def _get_efff_values(self, invoice): return { **self._get_ubl_values(invoice), 'ubl_version': 2.0, } def _export_efff(self, invoice): self.ensure_one() # Create file content. xml_content = markupsafe.Markup("<?xml version='1.0' encoding='UTF-8'?>") xml_content += self.env.ref('l10n_be_edi.export_efff_invoice')._render(self._get_efff_values(invoice)) xml_name = '%s.xml' % invoice._get_efff_name() return self.env['ir.attachment'].create({ 'name': xml_name, 'raw': xml_content.encode(), 'mimetype': 'application/xml', }) #################################################### # Account.edi.format override #################################################### def _create_invoice_from_xml_tree(self, filename, tree, journal=None): self.ensure_one() if self.code == 'efff_1' and self._is_ubl(filename, tree) and not self._is_account_edi_ubl_cii_available(): return self._create_invoice_from_ubl(tree) return super()._create_invoice_from_xml_tree(filename, tree, journal=journal) def _update_invoice_from_xml_tree(self, filename, tree, invoice): self.ensure_one() if self.code == 'efff_1' and self._is_ubl(filename, tree) and not self._is_account_edi_ubl_cii_available(): return self._update_invoice_from_ubl(tree, invoice) return super()._update_invoice_from_xml_tree(filename, tree, invoice) def _is_compatible_with_journal(self, journal): self.ensure_one() if self.code != 'efff_1' or self._is_account_edi_ubl_cii_available(): return super()._is_compatible_with_journal(journal) return journal.type == 'sale' and journal.country_code == 'BE' def _post_invoice_edi(self, invoices): self.ensure_one() if self.code != 'efff_1' or self._is_account_edi_ubl_cii_available(): return super()._post_invoice_edi(invoices) res = {} for invoice in invoices: attachment = self._export_efff(invoice) res[invoice] = {'success': True, 'attachment': attachment} return res
39.0625
2,500
2,648
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from lxml import etree import base64 from xml.sax.saxutils import escape, quoteattr class IrActionsReport(models.Model): _inherit = 'ir.actions.report' def _postprocess_pdf_report(self, record, buffer): '''Add the pdf report in the e-fff XML as base64 string. ''' result = super()._postprocess_pdf_report(record, buffer) if record._name == 'account.move': edi_attachment = record.edi_document_ids.filtered(lambda d: d.edi_format_id.code == 'efff_1').attachment_id if edi_attachment: old_xml = base64.b64decode(edi_attachment.with_context(bin_size=False).datas, validate=True) tree = etree.fromstring(old_xml) anchor_elements = tree.xpath("//*[local-name()='AccountingSupplierParty']") additional_document_elements = tree.xpath("//*[local-name()='AdditionalDocumentReference']") if anchor_elements and not additional_document_elements: pdf = base64.b64encode(buffer.getvalue()).decode() pdf_name = '%s.pdf' % record._get_efff_name() to_inject = ''' <cac:AdditionalDocumentReference xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"> <cbc:ID>%s</cbc:ID> <cac:Attachment> <cbc:EmbeddedDocumentBinaryObject mimeCode="application/pdf" filename=%s> %s </cbc:EmbeddedDocumentBinaryObject> </cac:Attachment> </cac:AdditionalDocumentReference> ''' % (escape(pdf_name), quoteattr(pdf_name), pdf) anchor_index = tree.index(anchor_elements[0]) tree.insert(anchor_index, etree.fromstring(to_inject)) new_xml = etree.tostring(tree, pretty_print=True) edi_attachment.write({ 'res_model': 'account.move', 'res_id': record.id, 'datas': base64.b64encode(new_xml), 'mimetype': 'application/xml', }) return result
49.962264
2,648
621
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Pad on tasks', 'category': 'Services/Project', 'description': """ This module adds a PAD in all project form views. ================================================= """, 'depends': [ 'project', 'pad' ], 'data': [ 'views/res_config_settings_views.xml', 'views/project_views.xml', ], 'auto_install': True, 'assets': { 'web.assets_frontend': [ 'pad_project/static/**/*', ], }, 'license': 'LGPL-3', }
23.884615
621
2,079
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ProjectTask(models.Model): _name = "project.task" _inherit = ["project.task", 'pad.common'] _description = 'Task' description_pad = fields.Char('Pad URL', pad_content_field='description', copy=False) use_pad = fields.Boolean(related="project_id.use_pads", string="Use collaborative pad", readonly=True) @api.onchange('use_pad') def _onchange_use_pads(self): """ Copy the content in the pad when the user change the project of the task to the one with no pads enabled. This case is when the use_pad becomes False and we have already generated the url pad, that is the description_pad field contains the url of the pad. """ if not self.use_pad and self.description_pad: vals = {'description_pad': self.description_pad} self._set_pad_to_field(vals) self.description = vals['description'] @api.model def create(self, vals): # When using quick create, the project_id is in the context, not in the vals project_id = vals.get('project_id', False) or self.default_get(['project_id']).get('project_id', False) if not self.env['project.project'].browse(project_id).use_pads: self = self.with_context(pad_no_create=True) return super(ProjectTask, self).create(vals) def _get_pad_content(self): """ Gets the content of the pad used to edit the task description and returns it. """ self.ensure_one() return self.pad_get_content(self.description_pad) class ProjectProject(models.Model): _name = "project.project" _inherit = ["project.project", 'pad.common'] _description = 'Project' description_pad = fields.Char('Pad URL', pad_content_field='description', copy=False) use_pads = fields.Boolean("Use collaborative pads", default=True, help="Use collaborative pad for the tasks on this project.")
40.764706
2,079
511
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Sale - SMS", 'summary': "Ease SMS integration with sales capabilities", 'description': "Ease SMS integration with sales capabilities", 'category': 'Hidden', 'version': '1.0', 'depends': ['sale', 'sms'], 'data': [ 'security/ir.model.access.csv', 'security/security.xml', ], 'application': False, 'auto_install': True, 'license': 'LGPL-3', }
28.388889
511
1,326
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Purchase Stock', 'version': '1.2', 'category': 'Inventory/Purchase', 'sequence': 60, 'summary': 'Purchase Orders, Receipts, Vendor Bills for Stock', 'description': "", 'depends': ['stock_account', 'purchase'], 'data': [ 'security/ir.model.access.csv', 'data/purchase_stock_data.xml', 'data/mail_templates.xml', 'report/vendor_delay_report.xml', 'views/purchase_views.xml', 'views/stock_views.xml', 'views/stock_rule_views.xml', 'views/res_config_settings_views.xml', 'views/res_partner_views.xml', 'views/stock_production_lot_views.xml', 'views/product_category_views.xml', 'report/purchase_report_views.xml', 'report/purchase_report_templates.xml', 'report/report_stock_forecasted.xml', 'report/report_stock_rule.xml', 'wizard/stock_replenishment_info.xml' ], 'demo': [ 'data/purchase_stock_demo.xml', ], 'installable': True, 'auto_install': True, 'post_init_hook': '_create_buy_rules', 'assets': { 'web.assets_backend': [ 'purchase_stock/static/**/*', ], }, 'license': 'LGPL-3', }
31.571429
1,326
1,175
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import models from odoo.tools import populate, groupby _logger = logging.getLogger(__name__) class PurchaseOrder(models.Model): _inherit = "purchase.order" _populate_dependencies = ["res.partner", "stock.picking.type"] def _populate_factories(self): res = super()._populate_factories() picking_types = self.env['stock.picking.type'].search([('code', '=', 'incoming')]) picking_types_by_company = dict(groupby(picking_types, key=lambda par: par.company_id.id)) picking_types_inter_company = self.env['stock.picking.type'].concat(*picking_types_by_company.get(False, [])) picking_types_by_company = {com: self.env['stock.picking.type'].concat(*pt) | picking_types_inter_company for com, pt in picking_types_by_company.items() if com} def get_picking_type_id(values=None, random=None, **kwargs): return random.choice(picking_types_by_company[values["company_id"]]).id return res + [ ("picking_type_id", populate.compute(get_picking_type_id)) ]
39.166667
1,175
20,378
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, timedelta, time from unittest.mock import patch from odoo import fields from .common import PurchaseTestCommon from odoo.tests.common import Form class TestPurchaseLeadTime(PurchaseTestCommon): def test_00_product_company_level_delays(self): """ To check dates, set product's Delivery Lead Time and company's Purchase Lead Time.""" company = self.env.ref('base.main_company') # Update company with Purchase Lead Time company.write({'po_lead': 3.00}) # Make procurement request from product_1's form view, create procurement and check it's state date_planned = fields.datetime.now() + timedelta(days=10) self._create_make_procurement(self.product_1, 15.00, date_planned=date_planned) purchase = self.env['purchase.order.line'].search([('product_id', '=', self.product_1.id)], limit=1).order_id # Confirm purchase order purchase.button_confirm() # Check order date of purchase order order_date = fields.Datetime.from_string(date_planned) - timedelta(days=self.product_1.seller_ids.delay) self.assertEqual(purchase.date_order, order_date, 'Order date should be equal to: Date of the procurement order - Purchase Lead Time - Delivery Lead Time.') # Check scheduled date of purchase order schedule_date = order_date + timedelta(days=self.product_1.seller_ids.delay) self.assertEqual(purchase.order_line.date_planned, schedule_date, 'Schedule date should be equal to: Order date of Purchase order + Delivery Lead Time.') # check the picking created or not self.assertTrue(purchase.picking_ids, "Picking should be created.") # Check scheduled and deadline date of In Type shipment self.assertEqual(purchase.picking_ids.scheduled_date, schedule_date, 'Schedule date of In type shipment should be equal to: schedule date of purchase order.') self.assertEqual(purchase.picking_ids.date_deadline, schedule_date, 'Deadline date of should be equal to: schedule date of purchase order.') def test_01_product_level_delay(self): """ To check schedule dates of multiple purchase order line of the same purchase order, we create two procurements for the two different product with same vendor and different Delivery Lead Time.""" company = self.env.ref('base.main_company') company.write({'po_lead': 0.00}) # Make procurement request from product_1's form view, create procurement and check it's state date_planned1 = fields.datetime.now() + timedelta(days=10) self._create_make_procurement(self.product_1, 10.00, date_planned=date_planned1) purchase1 = self.env['purchase.order.line'].search([('product_id', '=', self.product_1.id)], limit=1).order_id # Make procurement request from product_2's form view, create procurement and check it's state date_planned2 = fields.datetime.now() + timedelta(days=10) self._create_make_procurement(self.product_2, 5.00, date_planned=date_planned2) purchase2 = self.env['purchase.order.line'].search([('product_id', '=', self.product_2.id)], limit=1).order_id # Check purchase order is same or not self.assertEqual(purchase1, purchase2, 'Purchase orders should be same for the two different product with same vendor.') # Confirm purchase order purchase1.button_confirm() # Check order date of purchase order order_line_pro_1 = purchase2.order_line.filtered(lambda r: r.product_id == self.product_1) order_line_pro_2 = purchase2.order_line.filtered(lambda r: r.product_id == self.product_2) order_date = date_planned1 - timedelta(days=self.product_1.seller_ids.delay) self.assertEqual(purchase2.date_order, order_date, 'Order date should be equal to: Date of the procurement order - Delivery Lead Time.') # Check scheduled date of purchase order line for product_1 self.assertEqual(order_line_pro_1.date_planned, date_planned1, 'Schedule date of purchase order line for product_1 should be equal to: Order date of purchase order + Delivery Lead Time of product_1.') # Check scheduled date of purchase order line for product_2 self.assertEqual(order_line_pro_2.date_planned, date_planned2, 'Schedule date of purchase order line for product_2 should be equal to: Order date of purchase order + Delivery Lead Time of product_2.') # Check the picking created or not self.assertTrue(purchase2.picking_ids, "Picking should be created.") # Check scheduled date of In Type shipment picking_schedule_date = min(date_planned1, date_planned2) self.assertEqual(purchase2.picking_ids.scheduled_date, picking_schedule_date, 'Schedule date of In type shipment should be same as schedule date of purchase order.') # Check deadline of pickings self.assertEqual(fields.Date.to_date(purchase2.picking_ids.date_deadline), fields.Date.to_date(purchase1.date_planned), "Deadline of pickings should be equals to the receipt date of purchase") purchase_form = Form(purchase2) purchase_form.date_planned = purchase2.date_planned + timedelta(days=2) purchase_form.save() self.assertEqual(purchase2.picking_ids.date_deadline, purchase2.date_planned, "Deadline of pickings should be propagate") def test_02_product_route_level_delays(self): """ In order to check dates, set product's Delivery Lead Time and warehouse route's delay.""" company = self.env.ref('base.main_company') company.write({'po_lead': 1.00}) # Update warehouse_1 with Incoming Shipments 3 steps self.warehouse_1.write({'reception_steps': 'three_steps'}) # Set delay on push rule for push_rule in self.warehouse_1.reception_route_id.rule_ids: push_rule.write({'delay': 2}) rule_delay = sum(self.warehouse_1.reception_route_id.rule_ids.mapped('delay')) date_planned = fields.Datetime.to_string(fields.datetime.now() + timedelta(days=10)) # Create procurement order of product_1 self.env['procurement.group'].run([self.env['procurement.group'].Procurement( self.product_1, 5.000, self.uom_unit, self.warehouse_1.lot_stock_id, 'Test scheduler for RFQ', '/', self.env.company, { 'warehouse_id': self.warehouse_1, 'date_planned': date_planned, # 10 days added to current date of procurement to get future schedule date and order date of purchase order. 'date_deadline': date_planned, # 10 days added to current date of procurement to get future schedule date and order date of purchase order. 'rule_id': self.warehouse_1.buy_pull_id, 'group_id': False, 'route_ids': [], } )]) # Confirm purchase order purchase = self.env['purchase.order.line'].search([('product_id', '=', self.product_1.id)], limit=1).order_id purchase.button_confirm() # Check order date of purchase order order_date = fields.Datetime.from_string(date_planned) - timedelta(days=self.product_1.seller_ids.delay + rule_delay) self.assertEqual(purchase.date_order, order_date, 'Order date should be equal to: Date of the procurement order - Delivery Lead Time(supplier and pull rules).') # Check scheduled date of purchase order schedule_date = order_date + timedelta(days=self.product_1.seller_ids.delay + rule_delay) self.assertEqual(date_planned, str(schedule_date), 'Schedule date should be equal to: Order date of Purchase order + Delivery Lead Time(supplier and pull rules).') # Check the picking crated or not self.assertTrue(purchase.picking_ids, "Picking should be created.") # Check scheduled date of Internal Type shipment incoming_shipment1 = self.env['stock.picking'].search([('move_lines.product_id', 'in', (self.product_1.id, self.product_2.id)), ('picking_type_id', '=', self.warehouse_1.int_type_id.id), ('location_id', '=', self.warehouse_1.wh_input_stock_loc_id.id), ('location_dest_id', '=', self.warehouse_1.wh_qc_stock_loc_id.id)]) incoming_shipment1_date = order_date + timedelta(days=self.product_1.seller_ids.delay) self.assertEqual(incoming_shipment1.scheduled_date, incoming_shipment1_date, 'Schedule date of Internal Type shipment for input stock location should be equal to: schedule date of purchase order + push rule delay.') self.assertEqual(incoming_shipment1.date_deadline, incoming_shipment1_date) old_deadline1 = incoming_shipment1.date_deadline incoming_shipment2 = self.env['stock.picking'].search([('picking_type_id', '=', self.warehouse_1.int_type_id.id), ('location_id', '=', self.warehouse_1.wh_qc_stock_loc_id.id), ('location_dest_id', '=', self.warehouse_1.lot_stock_id.id)]) incoming_shipment2_date = schedule_date - timedelta(days=incoming_shipment2.move_lines[0].rule_id.delay) self.assertEqual(incoming_shipment2.scheduled_date, incoming_shipment2_date, 'Schedule date of Internal Type shipment for quality control stock location should be equal to: schedule date of Internal type shipment for input stock location + push rule delay..') self.assertEqual(incoming_shipment2.date_deadline, incoming_shipment2_date) old_deadline2 = incoming_shipment2.date_deadline # Modify the date_planned of the purchase -> propagate the deadline purchase_form = Form(purchase) purchase_form.date_planned = purchase.date_planned + timedelta(days=1) purchase_form.save() self.assertEqual(incoming_shipment2.date_deadline, old_deadline2 + timedelta(days=1), 'Deadline should be propagate') self.assertEqual(incoming_shipment1.date_deadline, old_deadline1 + timedelta(days=1), 'Deadline should be propagate') def test_merge_po_line(self): """Change that merging po line for same procurement is done.""" # create a product with manufacture route product_1 = self.env['product.product'].create({ 'name': 'AAA', 'route_ids': [(4, self.route_buy)], 'seller_ids': [(0, 0, {'name': self.partner_1.id, 'delay': 5})] }) # create a move for product_1 from stock to output and reserve to trigger the # rule move_1 = self.env['stock.move'].create({ 'name': 'move_1', 'product_id': product_1.id, 'product_uom': self.ref('uom.product_uom_unit'), 'location_id': self.ref('stock.stock_location_stock'), 'location_dest_id': self.ref('stock.stock_location_output'), 'product_uom_qty': 10, 'procure_method': 'make_to_order' }) move_1._action_confirm() po_line = self.env['purchase.order.line'].search([ ('product_id', '=', product_1.id), ]) self.assertEqual(len(po_line), 1, 'the purchase order line is not created') self.assertEqual(po_line.product_qty, 10, 'the purchase order line has a wrong quantity') move_2 = self.env['stock.move'].create({ 'name': 'move_2', 'product_id': product_1.id, 'product_uom': self.ref('uom.product_uom_unit'), 'location_id': self.ref('stock.stock_location_stock'), 'location_dest_id': self.ref('stock.stock_location_output'), 'product_uom_qty': 5, 'procure_method': 'make_to_order' }) move_2._action_confirm() po_line = self.env['purchase.order.line'].search([ ('product_id', '=', product_1.id), ]) self.assertEqual(len(po_line), 1, 'the purchase order lines should be merged') self.assertEqual(po_line.product_qty, 15, 'the purchase order line has a wrong quantity') def test_merge_po_line_3(self): """Change merging po line if same procurement is done depending on custom values.""" company = self.env.ref('base.main_company') company.write({'po_lead': 0.00}) # The seller has a specific product name and code which must be kept in the PO line self.t_shirt.seller_ids.write({ 'product_name': 'Vendor Name', 'product_code': 'Vendor Code', }) partner = self.t_shirt.seller_ids[:1].name t_shirt = self.t_shirt.with_context( lang=partner.lang, partner_id=partner.id, ) # Create procurement order of product_1 ProcurementGroup = self.env['procurement.group'] procurement_values = { 'warehouse_id': self.warehouse_1, 'rule_id': self.warehouse_1.buy_pull_id, 'date_planned': fields.datetime.now() + timedelta(days=10), 'group_id': False, 'route_ids': [], } procurement_values['product_description_variants'] = 'Color (Red)' order_1_values = procurement_values ProcurementGroup.run([self.env['procurement.group'].Procurement( self.t_shirt, 5, self.uom_unit, self.warehouse_1.lot_stock_id, self.t_shirt.name, '/', self.env.company, order_1_values) ]) purchase_order = self.env['purchase.order.line'].search([('product_id', '=', self.t_shirt.id)], limit=1).order_id order_line_description = purchase_order.order_line.product_id.description_pickingin or '' self.assertEqual(len(purchase_order.order_line), 1, 'wrong number of order line is created') self.assertEqual(purchase_order.order_line.name, t_shirt.display_name + "\n" + "Color (Red)", 'wrong description in po lines') procurement_values['product_description_variants'] = 'Color (Red)' order_2_values = procurement_values ProcurementGroup.run([self.env['procurement.group'].Procurement( self.t_shirt, 10, self.uom_unit, self.warehouse_1.lot_stock_id, self.t_shirt.name, '/', self.env.company, order_2_values) ]) self.env['procurement.group'].run_scheduler() self.assertEqual(len(purchase_order.order_line), 1, 'line with same custom value should be merged') self.assertEqual(purchase_order.order_line[0].product_qty, 15, 'line with same custom value should be merged and qty should be update') procurement_values['product_description_variants'] = 'Color (Green)' order_3_values = procurement_values ProcurementGroup.run([self.env['procurement.group'].Procurement( self.t_shirt, 10, self.uom_unit, self.warehouse_1.lot_stock_id, self.t_shirt.name, '/', self.env.company, order_3_values) ]) self.assertEqual(len(purchase_order.order_line), 2, 'line with different custom value should not be merged') self.assertEqual(purchase_order.order_line.filtered(lambda x: x.product_qty == 15).name, t_shirt.display_name + "\n" + "Color (Red)", 'wrong description in po lines') self.assertEqual(purchase_order.order_line.filtered(lambda x: x.product_qty == 10).name, t_shirt.display_name + "\n" + "Color (Green)", 'wrong description in po lines') purchase_order.button_confirm() self.assertEqual(purchase_order.picking_ids[0].move_ids_without_package.filtered(lambda x: x.product_uom_qty == 15).description_picking, t_shirt.display_name + "\n" + order_line_description + "Color (Red)", 'wrong description in picking') self.assertEqual(purchase_order.picking_ids[0].move_ids_without_package.filtered(lambda x: x.product_uom_qty == 10).description_picking, t_shirt.display_name + "\n" + order_line_description + "Color (Green)", 'wrong description in picking') def test_reordering_days_to_purchase(self): company = self.env.ref('base.main_company') company2 = self.env['res.company'].create({ 'name': 'Second Company', }) company.write({'po_lead': 0.00}) self.patcher = patch('odoo.addons.stock.models.stock_orderpoint.fields.Date', wraps=fields.Date) self.mock_date = self.patcher.start() vendor = self.env['res.partner'].create({ 'name': 'Colruyt' }) vendor2 = self.env['res.partner'].create({ 'name': 'Delhaize' }) self.env.company.days_to_purchase = 2.0 product = self.env['product.product'].create({ 'name': 'Chicory', 'type': 'product', 'seller_ids': [ (0, 0, {'name': vendor2.id, 'delay': 15.0, 'company_id': company2.id}), (0, 0, {'name': vendor.id, 'delay': 1.0, 'company_id': company.id}) ] }) orderpoint_form = Form(self.env['stock.warehouse.orderpoint']) orderpoint_form.product_id = product orderpoint_form.product_min_qty = 0.0 orderpoint = orderpoint_form.save() orderpoint_form = Form(self.env['stock.warehouse.orderpoint'].with_company(company2)) orderpoint_form.product_id = product orderpoint_form.product_min_qty = 0.0 orderpoint = orderpoint_form.save() warehouse = self.env['stock.warehouse'].search([], limit=1) delivery_moves = self.env['stock.move'] for i in range(0, 6): delivery_moves |= self.env['stock.move'].create({ 'name': 'Delivery', 'date': datetime.today() + timedelta(days=i), 'product_id': product.id, 'product_uom': product.uom_id.id, 'product_uom_qty': 5.0, 'location_id': warehouse.lot_stock_id.id, 'location_dest_id': self.ref('stock.stock_location_customers'), }) delivery_moves._action_confirm() self.env['procurement.group'].run_scheduler() po_line = self.env['purchase.order.line'].search([('product_id', '=', product.id)]) expected_date_order = fields.Date.today() + timedelta(days=2) self.assertEqual(fields.Date.to_date(po_line.order_id.date_order), expected_date_order) self.assertEqual(len(po_line), 1) self.assertEqual(po_line.product_uom_qty, 20.0) self.assertEqual(len(po_line.order_id), 1) orderpoint_form = Form(orderpoint) orderpoint_form.save() self.mock_date.today.return_value = fields.Date.today() + timedelta(days=1) orderpoint._compute_qty() self.env['procurement.group'].run_scheduler() po_line02 = self.env['purchase.order.line'].search([('product_id', '=', product.id)]) self.assertEqual(po_line02, po_line, 'The orderpoint execution should not create a new POL') self.assertEqual(fields.Date.to_date(po_line.order_id.date_order), expected_date_order, 'The Order Deadline should not change') self.assertEqual(po_line.product_uom_qty, 25.0, 'The existing POL should be updated with the quantity of the last execution') self.patcher.stop() def test_supplier_lead_time(self): """ Basic stock configuration and a supplier with a minimum qty and a lead time """ self.env['stock.warehouse.orderpoint'].search([]).unlink() orderpoint_form = Form(self.env['stock.warehouse.orderpoint']) orderpoint_form.product_id = self.product_1 orderpoint_form.product_min_qty = 10 orderpoint_form.product_max_qty = 50 orderpoint = orderpoint_form.save() self.env['product.supplierinfo'].search([('product_tmpl_id', '=', self.product_1.product_tmpl_id.id)]).unlink() self.env['product.supplierinfo'].create({ 'name': self.partner_1.id, 'min_qty': 1, 'price': 1, 'delay': 7, 'product_tmpl_id': self.product_1.product_tmpl_id.id, }) self.env['procurement.group'].run_scheduler() purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.partner_1.id)]) today = fields.Datetime.start_of(fields.Datetime.now(), 'day') self.assertEqual(purchase_order.date_order, today) self.assertEqual(fields.Datetime.start_of(purchase_order.date_planned, 'day'), today + timedelta(days=7))
56.448753
20,378
15,369
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import Form from odoo.addons.mail.tests.common import mail_new_test_user from odoo.addons.stock.tests.test_report import TestReportsCommon class TestPurchaseStockReports(TestReportsCommon): def test_report_forecast_1_purchase_order_multi_receipt(self): """ Create a PO for 5 product, receive them then increase the quantity to 10. """ po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 5 po = po_form.save() # Checks the report. report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids) draft_picking_qty_in = docs['draft_picking_qty']['in'] draft_purchase_qty = docs['draft_purchase_qty'] pending_qty_in = docs['qty']['in'] self.assertEqual(len(lines), 0, "Must have 0 line for now.") self.assertEqual(draft_picking_qty_in, 0) self.assertEqual(draft_purchase_qty, 5) self.assertEqual(pending_qty_in, 5) # Confirms the PO and checks the report again. po.button_confirm() report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids) draft_picking_qty_in = docs['draft_picking_qty']['in'] draft_purchase_qty = docs['draft_purchase_qty'] pending_qty_in = docs['qty']['in'] self.assertEqual(len(lines), 1) self.assertEqual(lines[0]['document_in'].id, po.id) self.assertEqual(lines[0]['quantity'], 5) self.assertEqual(lines[0]['document_out'], False) self.assertEqual(draft_picking_qty_in, 0) self.assertEqual(draft_purchase_qty, 0) self.assertEqual(pending_qty_in, 0) # Receives 5 products. receipt = po.picking_ids res_dict = receipt.button_validate() wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save() wizard.process() report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids) draft_picking_qty_in = docs['draft_picking_qty']['in'] draft_purchase_qty = docs['draft_purchase_qty'] pending_qty_in = docs['qty']['in'] self.assertEqual(len(lines), 0) self.assertEqual(draft_picking_qty_in, 0) self.assertEqual(draft_purchase_qty, 0) self.assertEqual(pending_qty_in, 0) # Increase the PO quantity to 10, so must create a second receipt. po_form = Form(po) with po_form.order_line.edit(0) as line: line.product_qty = 10 po = po_form.save() # Checks the report. report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids) draft_picking_qty_in = docs['draft_picking_qty']['in'] draft_purchase_qty = docs['draft_purchase_qty'] pending_qty_in = docs['qty']['in'] self.assertEqual(len(lines), 1, "Must have 1 line for now.") self.assertEqual(lines[0]['document_in'].id, po.id) self.assertEqual(lines[0]['quantity'], 5) self.assertEqual(draft_picking_qty_in, 0) self.assertEqual(draft_purchase_qty, 0) self.assertEqual(pending_qty_in, 0) def test_report_forecast_2_purchase_order_three_step_receipt(self): """ Create a PO for 4 product, receive them then increase the quantity to 10, but use three steps receipt. """ grp_multi_loc = self.env.ref('stock.group_stock_multi_locations') grp_multi_routes = self.env.ref('stock.group_adv_location') self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]}) self.env.user.write({'groups_id': [(4, grp_multi_routes.id)]}) # Configure warehouse. warehouse = self.env.ref('stock.warehouse0') warehouse.reception_steps = 'three_steps' po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 4 po = po_form.save() # Checks the report -> Must be empty for now, just display some pending qty. report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids) draft_picking_qty_in = docs['draft_picking_qty']['in'] draft_purchase_qty = docs['draft_purchase_qty'] pending_qty_in = docs['qty']['in'] self.assertEqual(len(lines), 0, "Must have 0 line for now.") self.assertEqual(draft_picking_qty_in, 0) self.assertEqual(draft_purchase_qty, 4) self.assertEqual(pending_qty_in, 4) # Confirms the PO and checks the report again. po.button_confirm() report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids) draft_picking_qty_in = docs['draft_picking_qty']['in'] draft_purchase_qty = docs['draft_purchase_qty'] pending_qty_in = docs['qty']['in'] self.assertEqual(len(lines), 1) self.assertEqual(lines[0]['document_in'].id, po.id) self.assertEqual(lines[0]['quantity'], 4) self.assertEqual(lines[0]['document_out'], False) self.assertEqual(draft_picking_qty_in, 0) self.assertEqual(draft_purchase_qty, 0) self.assertEqual(pending_qty_in, 0) # Get back the different transfers. receipt = po.picking_ids # Receives 4 products. res_dict = receipt.button_validate() wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save() wizard.process() report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids) draft_picking_qty_in = docs['draft_picking_qty']['in'] draft_purchase_qty = docs['draft_purchase_qty'] pending_qty_in = docs['qty']['in'] self.assertEqual(len(lines), 0) self.assertEqual(draft_picking_qty_in, 0) self.assertEqual(draft_purchase_qty, 0) self.assertEqual(pending_qty_in, 0) # Increase the PO quantity to 10, so must create a second receipt. po_form = Form(po) with po_form.order_line.edit(0) as line: line.product_qty = 10 po = po_form.save() # Checks the report. report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids) draft_picking_qty_in = docs['draft_picking_qty']['in'] draft_purchase_qty = docs['draft_purchase_qty'] pending_qty_in = docs['qty']['in'] self.assertEqual(len(lines), 1) self.assertEqual(lines[0]['document_in'].id, po.id) self.assertEqual(lines[0]['quantity'], 6) self.assertEqual(draft_picking_qty_in, 0) self.assertEqual(draft_purchase_qty, 0) self.assertEqual(pending_qty_in, 0) def test_report_forecast_3_report_line_corresponding_to_po_line_highlighted(self): """ When accessing the report from a PO line, checks if the correct PO line is highlighted in the report """ # We create 2 identical PO po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 5 po1 = po_form.save() po1.button_confirm() po2 = po1.copy() po2.button_confirm() # Check for both PO if the highlight (is_matched) corresponds to the correct PO for po in [po1, po2]: context = po.order_line[0].action_product_forecast_report()['context'] _, _, lines = self.get_report_forecast(product_template_ids=self.product_template.ids, context=context) for line in lines: if line['document_in'] == po: self.assertTrue(line['is_matched'], "The corresponding PO line should be matched in the forecast report.") else: self.assertFalse(line['is_matched'], "A line of the forecast report not linked to the PO shoud not be matched.") def test_approval_and_forecasted_qty(self): """ When a PO is waiting for an approval, its quantities should be included in the draft quantity count """ self.env.company.po_double_validation = 'two_step' self.env.company.po_double_validation_amount = 0 basic_purchase_user = mail_new_test_user( self.env, login='basic_purchase_user', groups='base.group_user,purchase.group_purchase_user', ) po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 50 po_form.save() po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 100 po = po_form.save() po.with_user(basic_purchase_user).button_confirm() docs = self.get_report_forecast(product_template_ids=self.product_template.ids)[1] self.assertEqual(docs['draft_purchase_qty'], 150) def test_vendor_delay_report_with_uom(self): """ PO 12 units x P Receive 1 dozen x P -> 100% received """ uom_12 = self.env.ref('uom.product_uom_dozen') po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 12 po = po_form.save() po.button_confirm() receipt = po.picking_ids receipt_move = receipt.move_lines receipt_move.move_line_ids.unlink() receipt_move.move_line_ids = [(0, 0, { 'location_id': receipt_move.location_id.id, 'location_dest_id': receipt_move.location_dest_id.id, 'product_id': self.product.id, 'product_uom_id': uom_12.id, 'qty_done': 1, 'picking_id': receipt.id, })] receipt.button_validate() data = self.env['vendor.delay.report'].read_group( [('partner_id', '=', self.partner.id)], ['product_id', 'on_time_rate', 'qty_on_time', 'qty_total'], ['product_id'], )[0] self.assertEqual(data['qty_on_time'], 12) self.assertEqual(data['qty_total'], 12) self.assertEqual(data['on_time_rate'], 100) def test_vendor_delay_report_with_multi_location(self): """ PO 10 units x P Receive - 6 x P in Child Location 01 - 4 x P in Child Location 02 -> 100% received """ child_loc_01, child_loc_02 = self.stock_location.child_ids po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 10 po = po_form.save() po.button_confirm() receipt = po.picking_ids receipt_move = receipt.move_lines receipt_move.move_line_ids.unlink() receipt_move.move_line_ids = [(0, 0, { 'location_id': receipt_move.location_id.id, 'location_dest_id': child_loc_01.id, 'product_id': self.product.id, 'product_uom_id': self.product.uom_id.id, 'qty_done': 6, 'picking_id': receipt.id, }), (0, 0, { 'location_id': receipt_move.location_id.id, 'location_dest_id': child_loc_02.id, 'product_id': self.product.id, 'product_uom_id': self.product.uom_id.id, 'qty_done': 4, 'picking_id': receipt.id, })] receipt.button_validate() data = self.env['vendor.delay.report'].read_group( [('partner_id', '=', self.partner.id)], ['product_id', 'on_time_rate', 'qty_on_time', 'qty_total'], ['product_id'], )[0] self.assertEqual(data['qty_on_time'], 10) self.assertEqual(data['qty_total'], 10) self.assertEqual(data['on_time_rate'], 100) def test_vendor_delay_report_with_backorder(self): """ PO 10 units x P Receive 6 x P with backorder -> 60% received Process the backorder -> 100% received """ po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 10 po = po_form.save() po.button_confirm() receipt01 = po.picking_ids receipt01_move = receipt01.move_lines receipt01_move.quantity_done = 6 action = receipt01.button_validate() Form(self.env[action['res_model']].with_context(action['context'])).save().process() data = self.env['vendor.delay.report'].read_group( [('partner_id', '=', self.partner.id)], ['product_id', 'on_time_rate', 'qty_on_time', 'qty_total'], ['product_id'], )[0] self.assertEqual(data['qty_on_time'], 6) self.assertEqual(data['qty_total'], 10) self.assertEqual(data['on_time_rate'], 60) receipt02 = receipt01.backorder_ids receipt02.move_lines.quantity_done = 4 receipt02.button_validate() data = self.env['vendor.delay.report'].read_group( [('partner_id', '=', self.partner.id)], ['product_id', 'on_time_rate', 'qty_on_time', 'qty_total'], ['product_id'], )[0] self.assertEqual(data['qty_on_time'], 10) self.assertEqual(data['qty_total'], 10) self.assertEqual(data['on_time_rate'], 100) def test_vendor_delay_report_without_backorder(self): """ PO 10 units x P Receive 6 x P without backorder -> 60% received """ po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner with po_form.order_line.new() as line: line.product_id = self.product line.product_qty = 10 po = po_form.save() po.button_confirm() receipt01 = po.picking_ids receipt01_move = receipt01.move_lines receipt01_move.quantity_done = 6 action = receipt01.button_validate() Form(self.env[action['res_model']].with_context(action['context'])).save().process_cancel_backorder() data = self.env['vendor.delay.report'].read_group( [('partner_id', '=', self.partner.id)], ['product_id', 'on_time_rate', 'qty_on_time', 'qty_total'], ['product_id'], )[0] self.assertEqual(data['qty_on_time'], 6) self.assertEqual(data['qty_total'], 10) self.assertEqual(data['on_time_rate'], 60)
42.455801
15,369
44,598
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime as dt from datetime import timedelta as td from freezegun import freeze_time from odoo import SUPERUSER_ID from odoo.tests import Form, tagged from odoo.tests.common import TransactionCase from odoo.exceptions import UserError @tagged('post_install', '-at_install') @freeze_time("2021-01-14 09:12:15") class TestReorderingRule(TransactionCase): @classmethod def setUpClass(cls): super(TestReorderingRule, cls).setUpClass() cls.partner = cls.env['res.partner'].create({ 'name': 'Smith' }) # create product and set the vendor product_form = Form(cls.env['product.product']) product_form.name = 'Product A' product_form.detailed_type = 'product' product_form.description = 'Internal Notes' with product_form.seller_ids.new() as seller: seller.name = cls.partner product_form.route_ids.add(cls.env.ref('purchase_stock.route_warehouse0_buy')) cls.product_01 = product_form.save() def test_reordering_rule_1(self): """ - Receive products in 2 steps - The product has a reordering rule - On the po generated, the source document should be the name of the reordering rule - Increase the quantity on the RFQ, the extra quantity should follow the push rules - Increase the quantity on the PO, the extra quantity should follow the push rules - There should be one move supplier -> input and two moves input -> stock """ warehouse_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1) warehouse_1.write({'reception_steps': 'two_steps'}) warehouse_2 = self.env['stock.warehouse'].create({'name': 'WH 2', 'code': 'WH2', 'company_id': self.env.company.id, 'partner_id': self.env.company.partner_id.id, 'reception_steps': 'one_step'}) # create reordering rule orderpoint_form = Form(self.env['stock.warehouse.orderpoint']) orderpoint_form.warehouse_id = warehouse_1 orderpoint_form.location_id = warehouse_1.lot_stock_id orderpoint_form.product_id = self.product_01 orderpoint_form.product_min_qty = 0.000 orderpoint_form.product_max_qty = 0.000 order_point = orderpoint_form.save() # Create Delivery Order of 10 product picking_form = Form(self.env['stock.picking']) picking_form.partner_id = self.partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = self.product_01 move.product_uom_qty = 10.0 customer_picking = picking_form.save() # picking confirm customer_picking.action_confirm() # Run scheduler self.env['procurement.group'].run_scheduler() # Check purchase order created or not purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.partner.id)]) self.assertTrue(purchase_order, 'No purchase order created.') # Check the picking type on the purchase order purchase_order.picking_type_id = warehouse_2.in_type_id with self.assertRaises(UserError): purchase_order.button_confirm() purchase_order.picking_type_id = warehouse_1.in_type_id # On the po generated, the source document should be the name of the reordering rule self.assertEqual(order_point.name, purchase_order.origin, 'Source document on purchase order should be the name of the reordering rule.') self.assertEqual(purchase_order.order_line.product_qty, 10) self.assertEqual(purchase_order.order_line.name, 'Product A') # Increase the quantity on the RFQ before confirming it purchase_order.order_line.product_qty = 12 purchase_order.button_confirm() self.assertEqual(purchase_order.picking_ids.move_lines.filtered(lambda m: m.product_id == self.product_01).product_qty, 12) next_picking = purchase_order.picking_ids.move_lines.move_dest_ids.picking_id self.assertEqual(len(next_picking), 2) self.assertEqual(next_picking[0].move_lines.filtered(lambda m: m.product_id == self.product_01).product_qty, 10) self.assertEqual(next_picking[1].move_lines.filtered(lambda m: m.product_id == self.product_01).product_qty, 2) # Increase the quantity on the PO purchase_order.order_line.product_qty = 15 self.assertEqual(purchase_order.picking_ids.move_lines.product_qty, 15) self.assertEqual(next_picking[0].move_lines.filtered(lambda m: m.product_id == self.product_01).product_qty, 10) self.assertEqual(next_picking[1].move_lines.filtered(lambda m: m.product_id == self.product_01).product_qty, 5) def test_reordering_rule_2(self): """ - Receive products in 1 steps - The product has two reordering rules, each one applying in a sublocation - Processing the purchase order should fulfill the two sublocations - Increase the quantity on the RFQ for one of the POL, the extra quantity will go to the original subloc since we don't know where to push it (no move dest) - Increase the quantity on the PO, the extra quantity should follow the push rules and thus go to stock """ warehouse_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1) subloc_1 = self.env['stock.location'].create({'name': 'subloc_1', 'location_id': warehouse_1.lot_stock_id.id}) subloc_2 = self.env['stock.location'].create({'name': 'subloc_2', 'location_id': warehouse_1.lot_stock_id.id}) # create reordering rules orderpoint_form = Form(self.env['stock.warehouse.orderpoint']) orderpoint_form.warehouse_id = warehouse_1 orderpoint_form.location_id = subloc_1 orderpoint_form.product_id = self.product_01 orderpoint_form.product_min_qty = 0.000 orderpoint_form.product_max_qty = 0.000 order_point_1 = orderpoint_form.save() orderpoint_form = Form(self.env['stock.warehouse.orderpoint']) orderpoint_form.warehouse_id = warehouse_1 orderpoint_form.location_id = subloc_2 orderpoint_form.product_id = self.product_01 orderpoint_form.product_min_qty = 0.000 orderpoint_form.product_max_qty = 0.000 order_point_2 = orderpoint_form.save() # Create Delivery Order of 10 product picking_form = Form(self.env['stock.picking']) picking_form.partner_id = self.partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = self.product_01 move.product_uom_qty = 10.0 with picking_form.move_ids_without_package.new() as move: move.product_id = self.product_01 move.product_uom_qty = 10.0 customer_picking = picking_form.save() customer_picking.move_lines[0].location_id = subloc_1.id customer_picking.move_lines[1].location_id = subloc_2.id # picking confirm customer_picking.action_confirm() self.assertEqual(self.product_01.with_context(location=subloc_1.id).virtual_available, -10) self.assertEqual(self.product_01.with_context(location=subloc_2.id).virtual_available, -10) # Run scheduler self.env['procurement.group'].run_scheduler() # Check purchase order created or not purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.partner.id)]) self.assertTrue(purchase_order, 'No purchase order created.') self.assertEqual(len(purchase_order.order_line), 2, 'Not enough purchase order lines created.') # increment the qty of the first po line purchase_order.order_line.filtered(lambda pol: pol.orderpoint_id == order_point_1).product_qty = 15 purchase_order.button_confirm() self.assertEqual(self.product_01.with_context(location=subloc_1.id).virtual_available, 5) self.assertEqual(self.product_01.with_context(location=subloc_2.id).virtual_available, 0) # increment the qty of the second po line purchase_order.order_line.filtered(lambda pol: pol.orderpoint_id == order_point_2).with_context(debug=True).product_qty = 15 self.assertEqual(self.product_01.with_context(location=subloc_1.id).virtual_available, 5) self.assertEqual(self.product_01.with_context(location=subloc_2.id).virtual_available, 0) self.assertEqual(self.product_01.with_context(location=warehouse_1.lot_stock_id.id).virtual_available, 10) # 5 on the main loc, 5 on subloc_1 self.assertEqual(purchase_order.picking_ids.move_lines[-1].product_qty, 5) self.assertEqual(purchase_order.picking_ids.move_lines[-1].location_dest_id, warehouse_1.lot_stock_id) def test_reordering_rule_3(self): """ trigger a reordering rule with a route to a location without warehouse """ warehouse_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1) outside_loc = self.env['stock.location'].create({ 'name': 'outside', 'usage': 'internal', 'location_id': self.env.ref('stock.stock_location_locations').id, }) route = self.env['stock.location.route'].create({ 'name': 'resupply outside', 'rule_ids': [ (0, False, { 'name': 'Buy', 'location_id': warehouse_1.lot_stock_id.id, 'company_id': self.env.company.id, 'action': 'buy', 'sequence': 2, 'procure_method': 'make_to_stock', 'picking_type_id': self.env.ref('stock.picking_type_in').id, }), (0, False, { 'name': 'ressuply from stock', 'location_src_id': warehouse_1.lot_stock_id.id, 'location_id': outside_loc.id, 'company_id': self.env.company.id, 'action': 'pull', 'procure_method': 'mts_else_mto', 'sequence': 1, 'picking_type_id': self.env.ref('stock.picking_type_out').id, }), ], }) vendor1 = self.env['res.partner'].create({'name': 'AAA', 'email': 'from.test@example.com'}) supplier_info1 = self.env['product.supplierinfo'].create({ 'name': vendor1.id, 'price': 50, }) product = self.env['product.product'].create({ 'name': 'product_rr_3', 'type': 'product', 'route_ids': [(4, route.id)], 'seller_ids': [(6, 0, [supplier_info1.id])], }) # create reordering rules orderpoint_form = Form(self.env['stock.warehouse.orderpoint'].with_user(2)) orderpoint_form.warehouse_id = warehouse_1 orderpoint_form.location_id = outside_loc orderpoint_form.product_id = product orderpoint_form.product_min_qty = 0.000 orderpoint_form.product_max_qty = 0.000 order_point_1 = orderpoint_form.save() order_point_1.route_id = route order_point_1.trigger = 'manual' # Create move out of 10 product move = self.env['stock.move'].create({ 'name': 'move out', 'product_id': product.id, 'product_uom': product.uom_id.id, 'product_uom_qty': 10, 'location_id': outside_loc.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'picking_type_id': self.env.ref('stock.picking_type_out').id, }) move._action_confirm() # Forecast on the order point should be -10 self.assertEqual(order_point_1.qty_forecast, -10) order_point_1.action_replenish() # Check purchase order created or not purchase_order = self.env['purchase.order.line'].search([('product_id', '=', product.id)]).order_id self.assertTrue(purchase_order, 'No purchase order created.') self.assertEqual(len(purchase_order.order_line), 1, 'Not enough purchase order lines created.') purchase_order.button_confirm() def test_replenish_report_1(self): """Tests the auto generation of manual orderpoints. Opening multiple times the report should not duplicate the generated orderpoints. MTO products should not trigger the creation of generated orderpoints """ partner = self.env['res.partner'].create({ 'name': 'Tintin' }) route_buy = self.env.ref('purchase_stock.route_warehouse0_buy') route_mto = self.env.ref('stock.route_warehouse0_mto') product_form = Form(self.env['product.product']) product_form.name = 'Simple Product' product_form.detailed_type = 'product' with product_form.seller_ids.new() as s: s.name = partner product = product_form.save() product_form = Form(self.env['product.product']) product_form.name = 'Product BUY + MTO' product_form.detailed_type = 'product' product_form.route_ids.add(route_buy) product_form.route_ids.add(route_mto) with product_form.seller_ids.new() as s: s.name = partner product_buy_mto = product_form.save() # Create Delivery Order of 20 product and 10 buy + MTO picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = product move.product_uom_qty = 10.0 with picking_form.move_ids_without_package.new() as move: move.product_id = product move.product_uom_qty = 10.0 with picking_form.move_ids_without_package.new() as move: move.product_id = product_buy_mto move.product_uom_qty = 10.0 customer_picking = picking_form.save() customer_picking.move_lines.filtered(lambda m: m.product_id == product_buy_mto).procure_method = 'make_to_order' customer_picking.action_confirm() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product.id)]) orderpoint_product_mto_buy = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product_buy_mto.id)]) self.assertFalse(orderpoint_product_mto_buy) self.assertEqual(len(orderpoint_product), 1.0) self.assertEqual(orderpoint_product.qty_to_order, 20.0) self.assertEqual(orderpoint_product.trigger, 'manual') self.assertEqual(orderpoint_product.create_uid.id, SUPERUSER_ID) orderpoint_product.action_replenish() po = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) self.assertTrue(po) self.assertEqual(len(po.order_line), 2.0) po_line_product_mto = po.order_line.filtered(lambda l: l.product_id == product_buy_mto) po_line_product = po.order_line.filtered(lambda l: l.product_id == product) self.assertEqual(po_line_product_mto.product_uom_qty, 10.0) self.assertEqual(po_line_product.product_uom_qty, 20.0) self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product.id)]) orderpoint_product_mto_buy = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product_buy_mto.id)]) self.assertFalse(orderpoint_product) self.assertFalse(orderpoint_product_mto_buy) # Create Delivery Order of 10 product and 10 buy + MTO picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = product move.product_uom_qty = 10.0 with picking_form.move_ids_without_package.new() as move: move.product_id = product_buy_mto move.product_uom_qty = 10.0 customer_picking = picking_form.save() customer_picking.move_lines.filtered(lambda m: m.product_id == product_buy_mto).procure_method = 'make_to_order' customer_picking.action_confirm() self.env['stock.warehouse.orderpoint'].flush() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product.id)]) orderpoint_product_mto_buy = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product_buy_mto.id)]) self.assertFalse(orderpoint_product_mto_buy) self.assertEqual(len(orderpoint_product), 1.0) self.assertEqual(orderpoint_product.qty_to_order, 10.0) self.assertEqual(orderpoint_product.trigger, 'manual') self.assertEqual(orderpoint_product.create_uid.id, SUPERUSER_ID) def test_replenish_report_2(self): """Same then `test_replenish_report_1` but with two steps receipt enabled""" partner = self.env['res.partner'].create({ 'name': 'Tintin' }) for wh in self.env['stock.warehouse'].search([]): wh.write({'reception_steps': 'two_steps'}) route_buy = self.env.ref('purchase_stock.route_warehouse0_buy') route_mto = self.env.ref('stock.route_warehouse0_mto') product_form = Form(self.env['product.product']) product_form.name = 'Simple Product' product_form.detailed_type = 'product' with product_form.seller_ids.new() as s: s.name = partner product = product_form.save() product_form = Form(self.env['product.product']) product_form.name = 'Product BUY + MTO' product_form.detailed_type = 'product' product_form.route_ids.add(route_buy) product_form.route_ids.add(route_mto) with product_form.seller_ids.new() as s: s.name = partner product_buy_mto = product_form.save() # Create Delivery Order of 20 product and 10 buy + MTO picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = product move.product_uom_qty = 10.0 with picking_form.move_ids_without_package.new() as move: move.product_id = product move.product_uom_qty = 10.0 with picking_form.move_ids_without_package.new() as move: move.product_id = product_buy_mto move.product_uom_qty = 10.0 customer_picking = picking_form.save() customer_picking.move_lines.filtered(lambda m: m.product_id == product_buy_mto).procure_method = 'make_to_order' customer_picking.action_confirm() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product.id)]) orderpoint_product_mto_buy = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product_buy_mto.id)]) self.assertFalse(orderpoint_product_mto_buy) self.assertEqual(len(orderpoint_product), 1.0) self.assertEqual(orderpoint_product.qty_to_order, 20.0) self.assertEqual(orderpoint_product.trigger, 'manual') self.assertEqual(orderpoint_product.create_uid.id, SUPERUSER_ID) orderpoint_product.action_replenish() po = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) self.assertTrue(po) self.assertEqual(len(po.order_line), 2.0) po_line_product_mto = po.order_line.filtered(lambda l: l.product_id == product_buy_mto) po_line_product = po.order_line.filtered(lambda l: l.product_id == product) self.assertEqual(po_line_product_mto.product_uom_qty, 10.0) self.assertEqual(po_line_product.product_uom_qty, 20.0) self.env['stock.warehouse.orderpoint'].flush() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product.id)]) orderpoint_product_mto_buy = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product_buy_mto.id)]) self.assertFalse(orderpoint_product) self.assertFalse(orderpoint_product_mto_buy) # Create Delivery Order of 10 product and 10 buy + MTO picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = product move.product_uom_qty = 10.0 with picking_form.move_ids_without_package.new() as move: move.product_id = product_buy_mto move.product_uom_qty = 10.0 customer_picking = picking_form.save() customer_picking.move_lines.filtered(lambda m: m.product_id == product_buy_mto).procure_method = 'make_to_order' customer_picking.action_confirm() self.env['stock.warehouse.orderpoint'].flush() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product.id)]) orderpoint_product_mto_buy = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product_buy_mto.id)]) self.assertFalse(orderpoint_product_mto_buy) self.assertEqual(len(orderpoint_product), 1.0) self.assertEqual(orderpoint_product.qty_to_order, 10.0) self.assertEqual(orderpoint_product.trigger, 'manual') self.assertEqual(orderpoint_product.create_uid.id, SUPERUSER_ID) def test_procure_not_default_partner(self): """Define a product with 2 vendors. First run a "standard" procurement, default vendor should be used. Then, call a procurement with `partner_id` specified in values, the specified vendor should be used.""" purchase_route = self.env.ref("purchase_stock.route_warehouse0_buy") uom_unit = self.env.ref("uom.product_uom_unit") warehouse = self.env['stock.warehouse'].search( [('company_id', '=', self.env.company.id)], limit=1) product = self.env["product.product"].create({ "name": "product TEST", "standard_price": 100.0, "type": "product", "uom_id": uom_unit.id, "default_code": "A", "route_ids": [(6, 0, purchase_route.ids)], }) default_vendor = self.env["res.partner"].create({ "name": "Supplier A", }) secondary_vendor = self.env["res.partner"].create({ "name": "Supplier B", }) self.env["product.supplierinfo"].create({ "name": default_vendor.id, "product_tmpl_id": product.product_tmpl_id.id, "delay": 7, }) self.env["product.supplierinfo"].create({ "name": secondary_vendor.id, "product_tmpl_id": product.product_tmpl_id.id, "delay": 10, }) # Test standard procurement. po_line = self.env["purchase.order.line"].search( [("product_id", "=", product.id)]) self.assertFalse(po_line) self.env["procurement.group"].run( [self.env["procurement.group"].Procurement( product, 100, uom_unit, warehouse.lot_stock_id, "Test default vendor", "/", self.env.company, { "warehouse_id": warehouse, "date_planned": dt.today() + td(days=15), "rule_id": warehouse.buy_pull_id, "group_id": False, "route_ids": [], } )]) po_line = self.env["purchase.order.line"].search( [("product_id", "=", product.id)]) self.assertTrue(po_line) self.assertEqual(po_line.partner_id, default_vendor) po_line.order_id.button_cancel() po_line.order_id.unlink() # now force the vendor: po_line = self.env["purchase.order.line"].search( [("product_id", "=", product.id)]) self.assertFalse(po_line) self.env["procurement.group"].run( [self.env["procurement.group"].Procurement( product, 100, uom_unit, warehouse.lot_stock_id, "Test default vendor", "/", self.env.company, { "warehouse_id": warehouse, "date_planned": dt.today() + td(days=15), "rule_id": warehouse.buy_pull_id, "group_id": False, "route_ids": [], "supplierinfo_name": secondary_vendor, } )]) po_line = self.env["purchase.order.line"].search( [("product_id", "=", product.id)]) self.assertTrue(po_line) self.assertEqual(po_line.partner_id, secondary_vendor) def test_procure_multi_lingual(self): """ Define a product with description in English and French. Run a procurement specifying a group_id with a partner (customer) set up with French as language. Verify that the PO is generated using the default (English) language. """ purchase_route = self.env.ref("purchase_stock.route_warehouse0_buy") # create a new warehouse to make sure it gets the mts/mto rule warehouse = self.env['stock.warehouse'].create({ "name": "test warehouse", "active": True, 'reception_steps': 'one_step', 'delivery_steps': 'ship_only', 'code': 'TEST' }) customer_loc, _ = warehouse._get_partner_locations() mto_rule = self.env['stock.rule'].search( [('warehouse_id', '=', warehouse.id), ('procure_method', '=', 'mts_else_mto'), ('location_id', '=', customer_loc.id) ] ) route_mto = self.env["stock.location.route"].create({ "name": "MTO", "active": True, "sequence": 3, "product_selectable": True, "rule_ids": [(6, 0, [ mto_rule.id ])] }) uom_unit = self.env.ref("uom.product_uom_unit") product = self.env["product.product"].create({ "name": "product TEST", "standard_price": 100.0, "type": "product", "uom_id": uom_unit.id, "default_code": "A", "route_ids": [(6, 0, [ route_mto.id, purchase_route.id, ])], }) self.env['res.lang']._activate_lang('fr_FR') self.env['ir.translation']._set_ids('product.template,name', 'model', 'fr_FR', product.product_tmpl_id.ids, 'produit en français') self.env['ir.translation']._set_ids('product.product,name', 'model', 'fr_FR', product.ids, 'produit en français') default_vendor = self.env["res.partner"].create({ "name": "Supplier A", }) self.env["product.supplierinfo"].create({ "name": default_vendor.id, "product_tmpl_id": product.product_tmpl_id.id, "delay": 7, }) customer = self.env["res.partner"].create({ "name": "Customer", "lang": "fr_FR" }) proc_group = self.env["procurement.group"].create({ "partner_id": customer.id }) procurement = self.env["procurement.group"].Procurement( product, 100, uom_unit, customer.property_stock_customer, "Test default vendor", "/", self.env.company, { "warehouse_id": warehouse, "date_planned": dt.today() + td(days=15), "group_id": proc_group, "route_ids": [], } ) self.env.cache.invalidate() self.env["procurement.group"].run([procurement]) po_line = self.env["purchase.order.line"].search( [("product_id", "=", product.id)]) self.assertTrue(po_line) self.assertEqual("[A] product TEST", po_line.name) def test_multi_locations_and_reordering_rule(self): """ Suppose two orderpoints for the same product, each one to a different location If the user triggers each orderpoint separately, it should still produce two different purchase order lines (one for each orderpoint) """ warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1) stock_location = warehouse.lot_stock_id sub_location = self.env['stock.location'].create({'name': 'subloc_1', 'location_id': stock_location.id}) orderpoint_form = Form(self.env['stock.warehouse.orderpoint']) orderpoint_form.warehouse_id = warehouse orderpoint_form.location_id = stock_location orderpoint_form.product_id = self.product_01 orderpoint_form.product_min_qty = 1 orderpoint_form.product_max_qty = 1 stock_op = orderpoint_form.save() orderpoint_form = Form(self.env['stock.warehouse.orderpoint']) orderpoint_form.warehouse_id = warehouse orderpoint_form.location_id = sub_location orderpoint_form.product_id = self.product_01 orderpoint_form.product_min_qty = 2 orderpoint_form.product_max_qty = 2 sub_op = orderpoint_form.save() stock_op.action_replenish() sub_op.action_replenish() po = self.env['purchase.order'].search([('partner_id', '=', self.partner.id)]) self.assertRecordValues(po.order_line, [ {'product_id': self.product_01.id, 'product_qty': 1.0, 'orderpoint_id': stock_op.id}, {'product_id': self.product_01.id, 'product_qty': 2.0, 'orderpoint_id': sub_op.id}, ]) po.button_confirm() picking = po.picking_ids action = picking.button_validate() wizard = Form(self.env[(action.get('res_model'))].with_context(action['context'])).save() wizard.process() self.assertRecordValues(picking.move_line_ids, [ {'product_id': self.product_01.id, 'qty_done': 1.0, 'state': 'done', 'location_dest_id': stock_location.id}, {'product_id': self.product_01.id, 'qty_done': 2.0, 'state': 'done', 'location_dest_id': sub_location.id}, ]) def test_change_of_scheduled_date(self): """ A user creates a delivery, an orderpoint is created. Its forecast quantity becomes -1 and the quantity to order is 1. Then the user postpones the scheduled date of the delivery. The quantities of the orderpoint should be reset to zero. """ delivery_form = Form(self.env['stock.picking']) delivery_form.partner_id = self.partner delivery_form.picking_type_id = self.env.ref('stock.picking_type_out') with delivery_form.move_ids_without_package.new() as move: move.product_id = self.product_01 move.product_uom_qty = 1 delivery = delivery_form.save() delivery.action_confirm() self.env['report.stock.quantity'].flush() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint = self.env['stock.warehouse.orderpoint'].search([('product_id', '=', self.product_01.id)]) self.assertRecordValues(orderpoint, [ {'qty_forecast': -1, 'qty_to_order': 1}, ]) delivery.scheduled_date += td(days=7) orderpoint.invalidate_cache(fnames=['qty_forecast', 'qty_to_order'], ids=orderpoint.ids) orderpoint.product_id.invalidate_cache(fnames=['virtual_available'], ids=orderpoint.product_id.ids) self.assertRecordValues(orderpoint, [ {'qty_forecast': 0, 'qty_to_order': 0}, ]) def test_decrease_qty_multi_step_receipt(self): """ Two-steps receipt. An orderpoint generates a move from Input to Stock with 5 x Product01 and a purchase order to fulfill the need of that SM. Then, the user decreases the qty on the PO and confirms it. The existing SM should be updated and another one should be created (from Vendors to Input, for the PO) """ warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1) warehouse.reception_steps = 'two_steps' input_location_id = warehouse.wh_input_stock_loc_id.id stock_location_id = warehouse.lot_stock_id.id customer_location_id = self.ref('stock.stock_location_customers') supplier_location_id = self.ref('stock.stock_location_suppliers') self.product_01.description = 'Super Note' op = self.env['stock.warehouse.orderpoint'].create({ 'name': self.product_01.name, 'location_id': stock_location_id, 'product_id': self.product_01.id, 'product_min_qty': 0, 'product_max_qty': 0, 'trigger': 'manual', }) out_move = self.env['stock.move'].create({ 'name': self.product_01.name, 'product_id': self.product_01.id, 'product_uom': self.product_01.uom_id.id, 'product_uom_qty': 5, 'location_id': stock_location_id, 'location_dest_id': customer_location_id, }) out_move._action_confirm() op.action_replenish() moves = self.env['stock.move'].search([('id', '!=', out_move.id), ('product_id', '=', self.product_01.id)]) self.assertRecordValues(moves, [ {'location_id': input_location_id, 'location_dest_id': stock_location_id, 'product_uom_qty': 5} ]) purchase = self.env['purchase.order'].search([('partner_id', '=', self.partner.id)], order="id desc", limit=1) with Form(purchase) as form: with form.order_line.edit(0) as line: line.product_qty = 4 purchase.button_confirm() moves = self.env['stock.move'].search([('id', '!=', out_move.id), ('product_id', '=', self.product_01.id)], order='id desc') self.assertRecordValues(moves, [ {'location_id': supplier_location_id, 'location_dest_id': input_location_id, 'product_qty': 4}, {'location_id': input_location_id, 'location_dest_id': stock_location_id, 'product_qty': 4}, ]) def test_decrease_qty_multi_step_receipt02(self): """ Two-steps receipt. An orderpoint generates a move from Input to Stock with 4 x Product01 and a purchase order to fulfill the need of that SM. Then, the user increases and decreases the qty on the PO. The existing SMs should be updated. """ warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1) warehouse.reception_steps = 'two_steps' input_location_id = warehouse.wh_input_stock_loc_id.id stock_location_id = warehouse.lot_stock_id.id supplier_location_id = self.ref('stock.stock_location_suppliers') self.product_01.description = False op = self.env['stock.warehouse.orderpoint'].create({ 'name': self.product_01.name, 'location_id': stock_location_id, 'product_id': self.product_01.id, 'product_min_qty': 4, 'product_max_qty': 4, 'trigger': 'manual', }) op.action_replenish() purchase = self.env['purchase.order'].search([('partner_id', '=', self.partner.id)], order="id desc", limit=1) with Form(purchase) as form: with form.order_line.edit(0) as line: line.product_qty = 10 purchase.button_confirm() moves = self.env['stock.move'].search([('product_id', '=', self.product_01.id)], order='id desc') self.assertRecordValues(moves, [ {'location_id': input_location_id, 'location_dest_id': stock_location_id, 'product_qty': 6}, {'location_id': supplier_location_id, 'location_dest_id': input_location_id, 'product_qty': 10}, {'location_id': input_location_id, 'location_dest_id': stock_location_id, 'product_qty': 4}, ]) with Form(purchase) as form: with form.order_line.edit(0) as line: line.product_qty = 1 moves = self.env['stock.move'].search([('product_id', '=', self.product_01.id)], order='id desc') self.assertRecordValues(moves, [ {'location_id': supplier_location_id, 'location_dest_id': input_location_id, 'product_qty': 1}, {'location_id': input_location_id, 'location_dest_id': stock_location_id, 'product_qty': 1}, ]) def test_add_line_to_existing_draft_po(self): """ Days to purchase = 10 Two products P1, P2 from the same supplier Several use cases, each time we run the RR one by one. Then, according to the dates and the configuration, it should use the existing PO or not """ warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1) self.env.company.days_to_purchase = 10 expected_order_date = dt.combine(dt.today() + td(days=10), dt.min.time()) expected_delivery_date = expected_order_date + td(days=1.0) # expected_delivery_date = expected_delivery_date.replace(hour=12, minute=0, second=0) product_02 = self.env['product.product'].create({ 'name': 'Super Product', 'type': 'product', 'seller_ids': [(0, 0, {'name': self.partner.id})], }) op_01, op_02 = self.env['stock.warehouse.orderpoint'].create([{ 'warehouse_id': warehouse.id, 'location_id': warehouse.lot_stock_id.id, 'product_id': p.id, 'product_min_qty': 1, 'product_max_qty': 0, } for p in [self.product_01, product_02]]) op_01.action_replenish() po01 = self.env['purchase.order'].search([], order='id desc', limit=1) self.assertEqual(po01.date_order, expected_order_date) op_02.action_replenish() self.assertEqual(po01.date_order, expected_order_date) self.assertRecordValues(po01.order_line, [ {'product_id': self.product_01.id, 'date_planned': expected_delivery_date}, {'product_id': product_02.id, 'date_planned': expected_delivery_date}, ]) # Reset and try another flow po01.button_cancel() op_01.action_replenish() po02 = self.env['purchase.order'].search([], order='id desc', limit=1) self.assertNotEqual(po02, po01) with freeze_time(dt.today() + td(days=1)): op_02.invalidate_cache(fnames=['lead_days_date'], ids=op_02.ids) op_02.action_replenish() self.assertEqual(po02.date_order, expected_order_date) self.assertRecordValues(po02.order_line, [ {'product_id': self.product_01.id, 'date_planned': expected_delivery_date}, {'product_id': product_02.id, 'date_planned': expected_delivery_date + td(days=1)}, ]) # Restrict the merge with POs that have their order deadline in [today - 2 days, today + 2 days] self.env['ir.config_parameter'].set_param('purchase_stock.delta_days_merge', '2') # Reset and try with a second RR executed in the dates range (-> should still use the existing PO) po02.button_cancel() op_01.action_replenish() po03 = self.env['purchase.order'].search([], order='id desc', limit=1) self.assertNotEqual(po03, po02) with freeze_time(dt.today() + td(days=2)): op_02.invalidate_cache(fnames=['lead_days_date'], ids=op_02.ids) op_02.action_replenish() self.assertEqual(po03.date_order, expected_order_date) self.assertRecordValues(po03.order_line, [ {'product_id': self.product_01.id, 'date_planned': expected_delivery_date}, {'product_id': product_02.id, 'date_planned': expected_delivery_date + td(days=2)}, ]) # Reset and try with a second RR executed after the dates range (-> should not use the existing PO) po03.button_cancel() op_01.action_replenish() po04 = self.env['purchase.order'].search([], order='id desc', limit=1) self.assertNotEqual(po04, po03) with freeze_time(dt.today() + td(days=3)): op_02.invalidate_cache(fnames=['lead_days_date'], ids=op_02.ids) op_02.action_replenish() self.assertEqual(po04.order_line.product_id, self.product_01, 'There should be only a line for product 01') po05 = self.env['purchase.order'].search([], order='id desc', limit=1) self.assertNotEqual(po05, po04, 'A new PO should be generated') self.assertEqual(po05.order_line.product_id, product_02) def test_update_po_line_without_purchase_access_right(self): """ Test that a user without purchase access right can update a PO line from picking.""" # create a user with only inventory access right user = self.env['res.users'].create({ 'name': 'Inventory Manager', 'login': 'inv_manager', 'groups_id': [(6, 0, [self.env.ref('stock.group_stock_user').id])] }) product = self.env['product.product'].create({ 'name': 'Storable Product', 'type': 'product', 'seller_ids': [(0, 0, {'name': self.partner.id})], }) warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1) self.env['stock.warehouse.orderpoint'].create({ 'warehouse_id': warehouse.id, 'location_id': warehouse.lot_stock_id.id, 'product_id': product.id, 'product_min_qty': 5, 'product_max_qty': 0, }) # run the scheduler self.env['procurement.group'].run_scheduler() # check that the PO line is created po_line = self.env['purchase.order.line'].search([('product_id', '=', product.id)]) self.assertEqual(len(po_line), 1, 'There should be only one PO line') self.assertEqual(po_line.product_qty, 5, 'The PO line quantity should be 5') # Update the po line from the picking picking = self.env['stock.picking'].with_user(user).create({ 'location_id': warehouse.lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'picking_type_id': warehouse.out_type_id.id, 'move_lines': [(0, 0, { 'name': product.name, 'product_id': product.id, 'product_uom': product.uom_id.id, 'product_uom_qty': 1, 'location_id': warehouse.lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, })] }) picking.with_user(user).action_assign() # check that the PO line quantity has been updated self.assertEqual(po_line.product_qty, 6, 'The PO line quantity should be 6')
48.264069
44,596
17,744
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon from odoo.tests import tagged, Form import time @tagged('-at_install', 'post_install') class TestFifoPrice(ValuationReconciliationTestCommon): def test_00_test_fifo(self): """ Test product cost price with fifo removal strategy.""" res_partner_3 = self.env['res.partner'].create({ 'name': 'Gemini Partner', }) # Set a product as using fifo price product_cable_management_box = self.env['product.product'].create({ 'default_code': 'FIFO', 'name': 'FIFO Ice Cream', 'type': 'product', 'categ_id': self.stock_account_product_categ.id, 'list_price': 100.0, 'standard_price': 70.0, 'uom_id': self.env.ref('uom.product_uom_kgm').id, 'uom_po_id': self.env.ref('uom.product_uom_kgm').id, 'supplier_taxes_id': [], 'description': 'FIFO Ice Cream', }) # I create a draft Purchase Order for first in move for 10 kg at 50 euro purchase_order_1 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': 'FIFO Ice Cream', 'product_id': product_cable_management_box.id, 'product_qty': 10.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 50.0, 'date_planned': time.strftime('%Y-%m-%d')})], }) # Confirm the first purchase order purchase_order_1.button_confirm() # Check the "Purchase" status of purchase order 1 self.assertEqual(purchase_order_1.state, 'purchase') # Process the reception of purchase order 1 and set date picking = purchase_order_1.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check the standard price of the product (fifo icecream), that should have changed # because the unit cost of the purchase order is 50 self.assertAlmostEqual(product_cable_management_box.standard_price, 50.0) self.assertEqual(product_cable_management_box.value_svl, 500.0, 'Wrong stock value') # I create a draft Purchase Order for second shipment for 30 kg at 80 euro purchase_order_2 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': 'FIFO Ice Cream', 'product_id': product_cable_management_box.id, 'product_qty': 30.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 80.0, 'date_planned': time.strftime('%Y-%m-%d')})], }) # Confirm the second purchase order purchase_order_2.button_confirm() # Process the reception of purchase order 2 picking = purchase_order_2.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check the standard price of the product, that should have not changed because we # still have icecream in stock self.assertEqual(product_cable_management_box.standard_price, 50.0, 'Standard price as fifo price of second reception incorrect!') self.assertEqual(product_cable_management_box.value_svl, 2900.0, 'Stock valuation should be 2900') # Let us send some goods outgoing_shipment = self.env['stock.picking'].create({ 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'move_lines': [(0, 0, { 'name': product_cable_management_box.name, 'product_id': product_cable_management_box.id, 'product_uom_qty': 20.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id})] }) # I assign this outgoing shipment outgoing_shipment.action_assign() # Process the delivery of the outgoing shipment res = outgoing_shipment.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check stock value became 1600 . self.assertEqual(product_cable_management_box.value_svl, 1600.0, 'Stock valuation should be 1600') # Do a delivery of an extra 500 g (delivery order) outgoing_shipment_uom = self.env['stock.picking'].create({ 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'move_lines': [(0, 0, { 'name': product_cable_management_box.name, 'product_id': product_cable_management_box.id, 'product_uom_qty': 500.0, 'product_uom': self.env.ref('uom.product_uom_gram').id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id})] }) # I assign this outgoing shipment outgoing_shipment_uom.action_assign() # Process the delivery of the outgoing shipment res = outgoing_shipment_uom.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check stock valuation and qty in stock self.assertEqual(product_cable_management_box.value_svl, 1560.0, 'Stock valuation should be 1560') self.assertEqual(product_cable_management_box.qty_available, 19.5, 'Should still have 19.5 in stock') # We will temporarily change the currency rate on the sixth of June to have the same results all year NewUSD = self.env['res.currency'].create({ 'name': 'new_usd', 'symbol': '$²', 'rate_ids': [(0, 0, {'rate': 1.2834, 'name': time.strftime('%Y-%m-%d')})], }) # Create PO for 30000 g at 0.150$/g and 10 kg at 150$/kg purchase_order_usd = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'currency_id': NewUSD.id, 'order_line': [(0, 0, { 'name': 'FIFO Ice Cream', 'product_id': product_cable_management_box.id, 'product_qty': 30, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 0.150, 'date_planned': time.strftime('%Y-%m-%d')}), (0, 0, { 'name': product_cable_management_box.name, 'product_id': product_cable_management_box.id, 'product_qty': 10.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 150.0, 'date_planned': time.strftime('%Y-%m-%d')})] }) # Confirm the purchase order in USD purchase_order_usd.button_confirm() # Process the reception of purchase order with USD picking = purchase_order_usd.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Create delivery order of 49.5 kg outgoing_shipment_cur = self.env['stock.picking'].create({ 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'move_lines': [(0, 0, { 'name': product_cable_management_box.name, 'product_id': product_cable_management_box.id, 'product_uom_qty': 49.5, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id})] }) # I assign this outgoing shipment outgoing_shipment_cur.action_assign() # Process the delivery of the outgoing shipment res = outgoing_shipment_cur.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Do a delivery of an extra 10 kg outgoing_shipment_ret = self.env['stock.picking'].create({ 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'move_lines': [(0, 0, { 'name': product_cable_management_box.name, 'product_id': product_cable_management_box.id, 'product_uom_qty': 10, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id})] }) # I assign this outgoing shipment outgoing_shipment_ret.action_assign() res = outgoing_shipment_ret.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check rounded price is 150.0 / 1.2834 self.assertEqual(round(product_cable_management_box.qty_available), 0.0, 'Wrong quantity in stock after first reception.') # Let us create some outs to get negative stock for a new product using the same config product_fifo_negative = self.env['product.product'].create({ 'default_code': 'NEG', 'name': 'FIFO Negative', 'type': 'product', 'categ_id': self.stock_account_product_categ.id, 'list_price': 100.0, 'standard_price': 70.0, 'uom_id': self.env.ref('uom.product_uom_kgm').id, 'uom_po_id': self.env.ref('uom.product_uom_kgm').id, 'supplier_taxes_id': [], 'description': 'FIFO Ice Cream', }) # Create outpicking.create delivery order of 100 kg. outgoing_shipment_neg = self.env['stock.picking'].create({ 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'move_lines': [(0, 0, { 'name': product_fifo_negative.name, 'product_id': product_fifo_negative.id, 'product_uom_qty': 100, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id})] }) # Process the delivery of the first outgoing shipment outgoing_shipment_neg.action_confirm() outgoing_shipment_neg.move_lines[0].quantity_done = 100.0 outgoing_shipment_neg._action_done() # Check qty available = -100 self.assertEqual(product_fifo_negative.qty_available, -100, 'Stock qty should be -100') # The behavior of fifo/lifo is not garantee if the quants are created at the same second, so just wait one second time.sleep(1) # Let create another out shipment of 400 kg outgoing_shipment_neg2 = self.env['stock.picking'].create({ 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'move_lines': [(0, 0, { 'name': product_fifo_negative.name, 'product_id': product_fifo_negative.id, 'product_uom_qty': 400, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id})] }) # Process the delivery of the outgoing shipments outgoing_shipment_neg2.action_confirm() outgoing_shipment_neg2.move_lines[0].quantity_done = 400.0 outgoing_shipment_neg2._action_done() # Check qty available = -500 self.assertEqual(product_fifo_negative.qty_available, -500, 'Stock qty should be -500') # Receive purchase order with 50 kg Ice Cream at 50€/kg purchase_order_neg = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': 'FIFO Ice Cream', 'product_id': product_fifo_negative.id, 'product_qty': 50.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 50.0, 'date_planned': time.strftime('%Y-%m-%d')})], }) # I confirm the first purchase order purchase_order_neg.button_confirm() # Process the reception of purchase order neg picking = purchase_order_neg.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Receive purchase order with 600 kg FIFO Ice Cream at 80 euro/kg purchase_order_neg2 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': product_cable_management_box.name, 'product_id': product_fifo_negative.id, 'product_qty': 600.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 80.0, 'date_planned': time.strftime('%Y-%m-%d')})], }) # I confirm the second negative purchase order purchase_order_neg2.button_confirm() # Process the reception of purchase order neg2 picking = purchase_order_neg2.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() original_out_move = outgoing_shipment_neg.move_lines[0] self.assertEqual(original_out_move.product_id.value_svl, 12000.0, 'Value of the move should be 12000') self.assertEqual(original_out_move.product_id.qty_available, 150.0, 'Qty available should be 150') def test_01_test_fifo(self): """" This test ensures that unit price keeps its decimal precision """ unit_price_precision = self.env.ref('product.decimal_price') unit_price_precision.digits = 3 tax = self.env["account.tax"].create({ "name": "Dummy Tax", "amount": "0.00", "type_tax_use": "purchase", }) super_product = self.env['product.product'].create({ 'name': 'Super Product', 'type': 'product', 'categ_id': self.stock_account_product_categ.id, 'standard_price': 0.035, }) self.assertEqual(super_product.cost_method, 'fifo') self.assertEqual(super_product.valuation, 'real_time') purchase_order = self.env['purchase.order'].create({ 'partner_id': self.env.ref('base.res_partner_3').id, 'order_line': [(0, 0, { 'name': super_product.name, 'product_id': super_product.id, 'product_qty': 1000, 'product_uom': super_product.uom_id.id, 'price_unit': super_product.standard_price, 'date_planned': time.strftime('%Y-%m-%d'), 'taxes_id': [(4, tax.id)], })], }) purchase_order.button_confirm() self.assertEqual(purchase_order.state, 'purchase') picking = purchase_order.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() self.assertEqual(super_product.standard_price, 0.035) self.assertEqual(super_product.value_svl, 35.0) self.assertEqual(picking.move_lines.price_unit, 0.035)
48.472678
17,741
29,757
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, datetime, timedelta from odoo.addons.mail.tests.common import mail_new_test_user from odoo.addons.product.tests import common from odoo.tests import Form from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT class TestCreatePicking(common.TestProductCommon): def setUp(self): super(TestCreatePicking, self).setUp() self.partner_id = self.env['res.partner'].create({'name': 'Wood Corner Partner'}) self.product_id_1 = self.env['product.product'].create({'name': 'Large Desk'}) self.product_id_2 = self.env['product.product'].create({'name': 'Conference Chair'}) self.user_purchase_user = mail_new_test_user( self.env, name='Pauline Poivraisselle', login='pauline', email='pur@example.com', notification_type='inbox', groups='purchase.group_purchase_user', ) self.po_vals = { 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product_id_1.name, 'product_id': self.product_id_1.id, 'product_qty': 5.0, 'product_uom': self.product_id_1.uom_po_id.id, 'price_unit': 500.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), })], } def test_00_create_picking(self): # Draft purchase order created self.po = self.env['purchase.order'].create(self.po_vals) self.assertTrue(self.po, 'Purchase: no purchase order created') # Purchase order confirm self.po.button_confirm() self.assertEqual(self.po.state, 'purchase', 'Purchase: PO state should be "Purchase') self.assertEqual(self.po.incoming_picking_count, 1, 'Purchase: one picking should be created') self.assertEqual(len(self.po.order_line.move_ids), 1, 'One move should be created') # Change purchase order line product quantity self.po.order_line.write({'product_qty': 7.0}) self.assertEqual(len(self.po.order_line.move_ids), 1, 'The two moves should be merged in one') # Validate first shipment self.picking = self.po.picking_ids[0] for ml in self.picking.move_line_ids: ml.qty_done = ml.product_uom_qty self.picking._action_done() self.assertEqual(self.po.order_line.mapped('qty_received'), [7.0], 'Purchase: all products should be received') # create new order line self.po.write({'order_line': [ (0, 0, { 'name': self.product_id_2.name, 'product_id': self.product_id_2.id, 'product_qty': 5.0, 'product_uom': self.product_id_2.uom_po_id.id, 'price_unit': 250.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), })]}) self.assertEqual(self.po.incoming_picking_count, 2, 'New picking should be created') moves = self.po.order_line.mapped('move_ids').filtered(lambda x: x.state not in ('done', 'cancel')) self.assertEqual(len(moves), 1, 'One moves should have been created') def test_01_check_double_validation(self): # make double validation two step self.env.company.write({'po_double_validation': 'two_step','po_double_validation_amount':2000.00}) # Draft purchase order created self.po = self.env['purchase.order'].with_user(self.user_purchase_user).create(self.po_vals) self.assertTrue(self.po, 'Purchase: no purchase order created') # Purchase order confirm self.po.button_confirm() self.assertEqual(self.po.state, 'to approve', 'Purchase: PO state should be "to approve".') # PO approved by manager self.po.env.user.groups_id += self.env.ref("purchase.group_purchase_manager") self.po.button_approve() self.assertEqual(self.po.state, 'purchase', 'PO state should be "Purchase".') def test_02_check_mto_chain(self): """ Simulate a mto chain with a purchase order. Cancel the purchase order should also change the procure_method of the following move to MTS in order to be able to link it to a manually created purchase order. """ stock_location = self.env.ref('stock.stock_location_stock') customer_location = self.env.ref('stock.stock_location_customers') picking_type_out = self.env.ref('stock.picking_type_out') # route buy should be there by default partner = self.env['res.partner'].create({ 'name': 'Jhon' }) vendor = self.env['res.partner'].create({ 'name': 'Roger' }) seller = self.env['product.supplierinfo'].create({ 'name': partner.id, 'price': 12.0, }) product = self.env['product.product'].create({ 'name': 'product', 'type': 'product', 'route_ids': [(4, self.ref('stock.route_warehouse0_mto')), (4, self.ref('purchase_stock.route_warehouse0_buy'))], 'seller_ids': [(6, 0, [seller.id])], 'categ_id': self.env.ref('product.product_category_all').id, 'supplier_taxes_id': [(6, 0, [])], }) customer_move = self.env['stock.move'].create({ 'name': 'move out', 'location_id': stock_location.id, 'location_dest_id': customer_location.id, 'product_id': product.id, 'product_uom': product.uom_id.id, 'product_uom_qty': 100.0, 'procure_method': 'make_to_order', 'picking_type_id': picking_type_out.id, }) customer_move._action_confirm() purchase_order = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) self.assertTrue(purchase_order, 'No purchase order created.') # Check purchase order line data. purchase_order_line = purchase_order.order_line self.assertEqual(purchase_order_line.product_id, product, 'The product on the purchase order line is not correct.') self.assertEqual(purchase_order_line.price_unit, seller.price, 'The purchase order line price should be the same as the seller.') self.assertEqual(purchase_order_line.product_qty, customer_move.product_uom_qty, 'The purchase order line qty should be the same as the move.') self.assertEqual(purchase_order_line.price_subtotal, 1200.0, 'The purchase order line subtotal should be equal to the move qty * seller price.') purchase_order.button_cancel() self.assertEqual(purchase_order.state, 'cancel', 'Purchase order should be cancelled.') self.assertEqual(customer_move.procure_method, 'make_to_stock', 'Customer move should be passed to mts.') purchase = purchase_order.create({ 'partner_id': vendor.id, 'order_line': [ (0, 0, { 'name': product.name, 'product_id': product.id, 'product_qty': 100.0, 'product_uom': product.uom_po_id.id, 'price_unit': 11.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), })], }) self.assertTrue(purchase, 'RFQ should be created') purchase.button_confirm() picking = purchase.picking_ids self.assertTrue(picking, 'Picking should be created') # Process pickings picking.action_confirm() picking.move_lines.quantity_done = 100.0 picking.button_validate() # mts move will be automatically assigned self.assertEqual(customer_move.state, 'assigned', 'Automatically assigned due to the incoming move makes it available.') self.assertEqual(self.env['stock.quant']._get_available_quantity(product, stock_location), 0.0, 'Wrong quantity in stock.') def test_03_uom(self): """ Buy a dozen of products stocked in units. Check that the quantities on the purchase order lines as well as the received quantities are handled in dozen while the moves themselves are handled in units. Edit the ordered quantities, check that the quantites are correctly updated on the moves. Edit the ir.config_parameter to propagate the uom of the purchase order lines to the moves and edit a last time the ordered quantities. Receive, check the quantities. """ uom_unit = self.env.ref('uom.product_uom_unit') uom_dozen = self.env.ref('uom.product_uom_dozen') self.assertEqual(self.product_id_1.uom_po_id.id, uom_unit.id) # buy a dozen po = self.env['purchase.order'].create(self.po_vals) po.order_line.product_qty = 1 po.order_line.product_uom = uom_dozen.id po.button_confirm() # the move should be 12 units # note: move.product_qty = computed field, always in the uom of the quant # move.product_uom_qty = stored field representing the initial demand in move.product_uom move1 = po.picking_ids.move_lines.sorted()[0] self.assertEqual(move1.product_uom_qty, 12) self.assertEqual(move1.product_uom.id, uom_unit.id) self.assertEqual(move1.product_qty, 12) # edit the so line, sell 2 dozen, the move should now be 24 units po.order_line.product_qty = 2 move1 = po.picking_ids.move_lines.sorted()[0] self.assertEqual(move1.product_uom_qty, 24) self.assertEqual(move1.product_uom.id, uom_unit.id) self.assertEqual(move1.product_qty, 24) # force the propagation of the uom, sell 3 dozen self.env['ir.config_parameter'].sudo().set_param('stock.propagate_uom', '1') po.order_line.product_qty = 3 move2 = po.picking_ids.move_lines.filtered(lambda m: m.product_uom.id == uom_dozen.id) self.assertEqual(move2.product_uom_qty, 1) self.assertEqual(move2.product_uom.id, uom_dozen.id) self.assertEqual(move2.product_qty, 12) # deliver everything move1.quantity_done = 24 move2.quantity_done = 1 po.picking_ids.button_validate() # check the delivered quantity self.assertEqual(po.order_line.qty_received, 3.0) def test_04_mto_multiple_po(self): """ Simulate a mto chain with 2 purchase order. Create a move with qty 1, confirm the RFQ then create a new move that will not be merged in the first one(simulate an increase order quantity on a SO). It should generate a new RFQ, validate and receipt the picking then try to reserve the delivery picking. """ stock_location = self.env.ref('stock.stock_location_stock') customer_location = self.env.ref('stock.stock_location_customers') picking_type_out = self.env.ref('stock.picking_type_out') # route buy should be there by default partner = self.env['res.partner'].create({ 'name': 'Jhon' }) seller = self.env['product.supplierinfo'].create({ 'name': partner.id, 'price': 12.0, }) product = self.env['product.product'].create({ 'name': 'product', 'type': 'product', 'route_ids': [(4, self.ref('stock.route_warehouse0_mto')), (4, self.ref('purchase_stock.route_warehouse0_buy'))], 'seller_ids': [(6, 0, [seller.id])], 'categ_id': self.env.ref('product.product_category_all').id, }) # A picking is require since only moves inside the same picking are merged. customer_picking = self.env['stock.picking'].create({ 'location_id': stock_location.id, 'location_dest_id': customer_location.id, 'partner_id': partner.id, 'picking_type_id': picking_type_out.id, }) customer_move = self.env['stock.move'].create({ 'name': 'move out', 'location_id': stock_location.id, 'location_dest_id': customer_location.id, 'product_id': product.id, 'product_uom': product.uom_id.id, 'product_uom_qty': 80.0, 'procure_method': 'make_to_order', 'picking_id': customer_picking.id, }) customer_move._action_confirm() purchase_order = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) self.assertTrue(purchase_order, 'No purchase order created.') # Check purchase order line data. purchase_order_line = purchase_order.order_line self.assertEqual(purchase_order_line.product_id, product, 'The product on the purchase order line is not correct.') self.assertEqual(purchase_order_line.price_unit, seller.price, 'The purchase order line price should be the same as the seller.') self.assertEqual(purchase_order_line.product_qty, customer_move.product_uom_qty, 'The purchase order line qty should be the same as the move.') purchase_order.button_confirm() customer_move_2 = self.env['stock.move'].create({ 'name': 'move out', 'location_id': stock_location.id, 'location_dest_id': customer_location.id, 'product_id': product.id, 'product_uom': product.uom_id.id, 'product_uom_qty': 20.0, 'procure_method': 'make_to_order', 'picking_id': customer_picking.id, }) customer_move_2._action_confirm() self.assertTrue(customer_move_2.exists(), 'The second customer move should not be merged in the first.') self.assertEqual(sum(customer_picking.move_lines.mapped('product_uom_qty')), 100.0) purchase_order_2 = self.env['purchase.order'].search([('partner_id', '=', partner.id), ('state', '=', 'draft')]) self.assertTrue(purchase_order_2, 'No purchase order created.') purchase_order_2.button_confirm() purchase_order.picking_ids.move_lines.quantity_done = 80.0 purchase_order.picking_ids.button_validate() purchase_order_2.picking_ids.move_lines.quantity_done = 20.0 purchase_order_2.picking_ids.button_validate() self.assertEqual(sum(customer_picking.move_lines.mapped('reserved_availability')), 100.0, 'The total quantity for the customer move should be available and reserved.') def test_04_rounding(self): """ We set the Unit(s) rounding to 1.0 and ensure buying 1.2 units in a PO is rounded to 1.0 at reception. """ uom_unit = self.env.ref('uom.product_uom_unit') uom_unit.rounding = 1.0 # buy a dozen po = self.env['purchase.order'].create(self.po_vals) po.order_line.product_qty = 1.2 po.button_confirm() # the move should be 1.0 units move1 = po.picking_ids.move_lines[0] self.assertEqual(move1.product_uom_qty, 1.0) self.assertEqual(move1.product_uom.id, uom_unit.id) self.assertEqual(move1.product_qty, 1.0) # edit the so line, buy 2.4 units, the move should now be 2.0 units po.order_line.product_qty = 2.0 self.assertEqual(move1.product_uom_qty, 2.0) self.assertEqual(move1.product_uom.id, uom_unit.id) self.assertEqual(move1.product_qty, 2.0) # deliver everything move1.quantity_done = 2.0 po.picking_ids.button_validate() # check the delivered quantity self.assertEqual(po.order_line.qty_received, 2.0) def test_05_uom_rounding(self): """ We set the Unit(s) and Dozen(s) rounding to 1.0 and ensure buying 1.3 dozens in a PO is rounded to 1.0 at reception. """ uom_unit = self.env.ref('uom.product_uom_unit') uom_dozen = self.env.ref('uom.product_uom_dozen') uom_unit.rounding = 1.0 uom_dozen.rounding = 1.0 # buy 1.3 dozen po = self.env['purchase.order'].create(self.po_vals) po.order_line.product_qty = 1.3 po.order_line.product_uom = uom_dozen.id po.button_confirm() # the move should be 16.0 units move1 = po.picking_ids.move_lines[0] self.assertEqual(move1.product_uom_qty, 16.0) self.assertEqual(move1.product_uom.id, uom_unit.id) self.assertEqual(move1.product_qty, 16.0) # force the propagation of the uom, buy 2.6 dozens, the move 2 should have 2 dozens self.env['ir.config_parameter'].sudo().set_param('stock.propagate_uom', '1') po.order_line.product_qty = 2.6 move2 = po.picking_ids.move_lines.filtered(lambda m: m.product_uom.id == uom_dozen.id) self.assertEqual(move2.product_uom_qty, 2) self.assertEqual(move2.product_uom.id, uom_dozen.id) self.assertEqual(move2.product_qty, 24) def create_delivery_order(self): stock_location = self.env.ref('stock.stock_location_stock') customer_location = self.env.ref('stock.stock_location_customers') unit = self.ref("uom.product_uom_unit") picking_type_out = self.env.ref('stock.picking_type_out') partner = self.env['res.partner'].create({'name': 'AAA', 'email': 'from.test@example.com'}) supplier_info1 = self.env['product.supplierinfo'].create({ 'name': partner.id, 'price': 50, }) warehouse1 = self.env.ref('stock.warehouse0') route_buy = warehouse1.buy_pull_id.route_id route_mto = warehouse1.mto_pull_id.route_id product = self.env['product.product'].create({ 'name': 'Usb Keyboard', 'type': 'product', 'uom_id': unit, 'uom_po_id': unit, 'seller_ids': [(6, 0, [supplier_info1.id])], 'route_ids': [(6, 0, [route_buy.id, route_mto.id])] }) delivery_order = self.env['stock.picking'].create({ 'location_id': stock_location.id, 'location_dest_id': customer_location.id, 'partner_id': partner.id, 'picking_type_id': picking_type_out.id, }) customer_move = self.env['stock.move'].create({ 'name': 'move out', 'location_id': stock_location.id, 'location_dest_id': customer_location.id, 'product_id': product.id, 'product_uom': product.uom_id.id, 'product_uom_qty': 10.0, 'procure_method': 'make_to_order', 'picking_id': delivery_order.id, }) customer_move._action_confirm() # find created po the product purchase_order = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) return delivery_order, purchase_order def test_05_propagate_deadline(self): """ In order to check deadline date of the delivery order is changed and the planned date not.""" # Create Delivery Order and with propagate date and minimum delta delivery_order, purchase_order = self.create_delivery_order() # check po is created or not self.assertTrue(purchase_order, 'No purchase order created.') purchase_order_line = purchase_order.order_line # change scheduled date of po line. purchase_order_line.write({'date_planned': purchase_order_line.date_planned + timedelta(days=5)}) # Now check scheduled date and deadline of delivery order. self.assertNotEqual( purchase_order_line.date_planned, delivery_order.scheduled_date, 'Scheduled delivery order date should not changed.') self.assertEqual( purchase_order_line.date_planned, delivery_order.date_deadline, 'Delivery deadline date should be changed.') def test_07_differed_schedule_date(self): warehouse = self.env['stock.warehouse'].search([], limit=1) with Form(warehouse) as w: w.reception_steps = 'three_steps' po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner_id with po_form.order_line.new() as line: line.product_id = self.product_id_1 line.date_planned = datetime.today() line.product_qty = 1.0 with po_form.order_line.new() as line: line.product_id = self.product_id_1 line.date_planned = datetime.today() + timedelta(days=7) line.product_qty = 1.0 po = po_form.save() po.button_approve() po.picking_ids.move_line_ids.write({ 'qty_done': 1.0 }) po.picking_ids.button_validate() pickings = self.env['stock.picking'].search([('group_id', '=', po.group_id.id)]) for picking in pickings: self.assertEqual(picking.scheduled_date.date(), date.today()) def test_update_quantity_and_return(self): po = self.env['purchase.order'].create(self.po_vals) po.order_line.product_qty = 10 po.button_confirm() first_picking = po.picking_ids first_picking.move_lines.quantity_done = 5 # create the backorder backorder_wizard_dict = first_picking.button_validate() backorder_wizard = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context'])).save() backorder_wizard.process() self.assertEqual(len(po.picking_ids), 2) # Create a partial return stock_return_picking_form = Form( self.env['stock.return.picking'].with_context( active_ids=first_picking.ids, active_id=first_picking.ids[0], active_model='stock.picking' ) ) stock_return_picking = stock_return_picking_form.save() stock_return_picking.product_return_moves.quantity = 2.0 stock_return_picking_action = stock_return_picking.create_returns() return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id']) return_pick.action_assign() return_pick.move_lines.quantity_done = 2 return_pick._action_done() self.assertEqual(po.order_line.qty_received, 3) po.order_line.product_qty += 2 backorder = po.picking_ids.filtered(lambda picking: picking.state == 'assigned') self.assertEqual(backorder.move_lines.product_uom_qty, 9) def test_08_check_update_qty_mto_chain(self): """ Simulate a mto chain with a purchase order. Updating the initial demand should also impact the initial move and the purchase order if it wasn't yet confirmed. """ def create_run_procurement(product, product_qty, values=None): if not values: values = { 'warehouse_id': picking_type_out.warehouse_id, 'action': 'pull_push', 'group_id': procurement_group, } return self.env['procurement.group'].run([self.env['procurement.group'].Procurement( product, product_qty, self.uom_unit, vendor.property_stock_customer, product.name, '/', self.env.company, values) ]) # Prepare procurement that replicates a sale order. picking_type_out = self.env.ref('stock.picking_type_out') partner = self.env['res.partner'].create({ 'name': 'Jhon' }) seller = self.env['product.supplierinfo'].create({ 'name': partner.id, 'price': 12.0, }) vendor = self.env['res.partner'].create({ 'name': 'Roger' }) # This needs to be tried with MTO route activated self.env['stock.location.route'].browse(self.ref('stock.route_warehouse0_mto')).action_unarchive() product = self.env['product.product'].create({ 'name': 'product', 'type': 'product', 'route_ids': [(4, self.ref('stock.route_warehouse0_mto')), (4, self.ref('purchase_stock.route_warehouse0_buy'))], 'seller_ids': [(6, 0, [seller.id])], 'categ_id': self.env.ref('product.product_category_all').id, 'supplier_taxes_id': [(6, 0, [])], }) procurement_group = self.env['procurement.group'].create({ 'move_type': 'direct', 'partner_id': vendor.id }) # Create initial procurement that will generate the initial move and its picking. create_run_procurement(product, 50, { 'group_id': procurement_group, 'warehouse_id': picking_type_out.warehouse_id, 'partner_id': vendor }) customer_move = self.env['stock.move'].search([('group_id', '=', procurement_group.id)]) purchase_order = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) self.assertTrue(purchase_order, 'No purchase order created.') # Check purchase order line data. purchase_order_line = purchase_order.order_line self.assertEqual(purchase_order_line.product_id, product, 'The product on the purchase order line is not correct.') self.assertEqual(purchase_order_line.product_qty, 50, 'The purchase order line qty should be the same as the move.') # Create procurement to decrease quantity in the initial move and the related RFQ. create_run_procurement(product, -10.00) self.assertEqual(customer_move.product_uom_qty, 40, 'The demand on the initial move should have been decreased when merged with the procurement.') self.assertEqual(purchase_order_line.product_qty, 40, 'The demand on the Purchase Order should have been decreased since it is still a RFQ.') # Create procurement to increase quantity on the initial move and the related RFQ. create_run_procurement(product, 5.00) self.assertEqual(customer_move.product_uom_qty, 45, 'The demand on the initial move should have been increased when merged with the procurement.') self.assertEqual(purchase_order_line.product_qty, 45, 'The demand on the Purchase Order should have been increased since it is still a RFQ.') purchase_order.button_confirm() # Create procurement to decrease quantity in the initial move but not the confirmed PO. create_run_procurement(product, -10.00) self.assertEqual(customer_move.product_uom_qty, 35, 'The demand on the initial move should have been decreased when merged with the procurement.') self.assertEqual(purchase_order_line.product_qty, 45, 'The demand on the Purchase Order should not have been decreased since it is has been confirmed.') purchase_orders = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) self.assertEqual(len(purchase_orders), 1, 'No RFQ should have been created for a negative demand') # Create procurement to increase quantity on the initial move that will create a new move and a new RFQ for missing demand. create_run_procurement(product, 5.00) self.assertEqual(customer_move.product_uom_qty, 35, 'The demand on the initial move should not have been increased since it should be a new move.') self.assertEqual(purchase_order_line.product_qty, 45, 'The demand on the Purchase Order should not have been increased since it is has been confirmed.') purchase_orders = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) self.assertEqual(len(purchase_orders), 2, 'A new RFQ should have been created for missing demand.') def test_update_qty_purchased(self): """ Test that the price unit in the purchase order line and the move is updated according to the price defined in the PO line when the PO is confirmed, and that the "stock.moves" are merged correctly when changing the qty purchased. """ # add vendor to the product self.product_id_1.seller_ids = [(0, 0, { 'name': self.partner_id.id, 'min_qty': 10, 'price': 15, })] # Create PO po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner_id with po_form.order_line.new() as po_line: po_line.product_id = self.product_id_1 po_line.product_qty = 10 purchase_order = po_form.save() # Confirm Purchase order purchase_order.button_confirm() # Check purchase order state, it should be "purchase". self.assertEqual(purchase_order.state, 'purchase', 'Purchase order should be in purchase state.') # Make sure that picking has been created self.assertEqual(len(purchase_order.picking_ids), 1) # check that the price list has been applied self.assertEqual(purchase_order.order_line.price_unit, 15) self.assertEqual(purchase_order.picking_ids.move_lines.price_unit, 15) # update the product qty purchased with po_form.order_line.edit(0) as po_line: po_line.product_qty = 9 po_line.price_unit = 10 purchase_order = po_form.save() # verify that the move for the decreased qty has been merged with the initial move self.assertEqual(len(purchase_order.picking_ids), 1) self.assertEqual(len(purchase_order.picking_ids.move_lines), 1) # check that the price has been updated in the purchase order line and in the stock.move self.assertEqual(purchase_order.order_line.price_unit, 10) self.assertEqual(purchase_order.picking_ids.move_lines.price_unit, 10)
46.278383
29,757
6,607
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import fields, Command from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged, Form from odoo.exceptions import UserError @tagged('post_install', '-at_install') class TestAccruedPurchaseStock(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) uom_unit = cls.env.ref('uom.product_uom_unit') product = cls.env['product.product'].create({ 'name': "Product", 'list_price': 30.0, 'type': 'consu', 'uom_id': uom_unit.id, 'uom_po_id': uom_unit.id, }) cls.purchase_order = cls.env['purchase.order'].with_context(tracking_disable=True).create({ 'partner_id': cls.partner_a.id, 'order_line': [ Command.create({ 'name': product.name, 'product_id': product.id, 'product_qty': 10.0, 'product_uom': product.uom_id.id, 'price_unit': product.list_price, 'taxes_id': False, }), ] }) cls.purchase_order.button_confirm() cls.account_expense = cls.company_data['default_account_expense'] cls.account_revenue = cls.company_data['default_account_revenue'] def test_purchase_stock_accruals(self): # receive 2 on 2020-01-02 pick = self.purchase_order.picking_ids pick.move_lines.write({'quantity_done': 2}) pick.button_validate() wiz_act = pick.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() pick.move_lines.write({'date': fields.Date.to_date('2020-01-02')}) # receive 3 on 2020-01-06 pick = pick.copy() pick.move_lines.write({'quantity_done': 3}) wiz_act = pick.button_validate() pick.move_lines.write({'date': fields.Date.to_date('2020-01-06')}) wizard = self.env['account.accrued.orders.wizard'].with_context({ 'active_model': 'purchase.order', 'active_ids': self.purchase_order.ids, }).create({ 'account_id': self.account_expense.id, 'date': '2020-01-01', }) # nothing to invoice on 2020-01-01 with self.assertRaises(UserError): wizard.create_entries() # 2 to invoice on 2020-01-04 wizard.date = fields.Date.to_date('2020-01-04') self.assertRecordValues(self.env['account.move'].search(wizard.create_entries()['domain']).line_ids, [ # reverse move lines {'account_id': self.account_expense.id, 'debit': 0, 'credit': 60}, {'account_id': wizard.account_id.id, 'debit': 60, 'credit': 0}, # move lines {'account_id': self.account_expense.id, 'debit': 60, 'credit': 0}, {'account_id': wizard.account_id.id, 'debit': 0, 'credit': 60}, ]) # 5 to invoice on 2020-01-07 wizard.date = fields.Date.to_date('2020-01-07') self.assertRecordValues(self.env['account.move'].search(wizard.create_entries()['domain']).line_ids, [ # reverse move lines {'account_id': self.account_expense.id, 'debit': 0, 'credit': 150}, {'account_id': wizard.account_id.id, 'debit': 150, 'credit': 0}, # move lines {'account_id': self.account_expense.id, 'debit': 150, 'credit': 0}, {'account_id': wizard.account_id.id, 'debit': 0, 'credit': 150}, ]) def test_purchase_stock_invoiced_accrued_entries(self): # deliver 2 on 2020-01-02 pick = self.purchase_order.picking_ids pick.move_lines.write({'quantity_done': 2}) pick.button_validate() wiz_act = pick.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() pick.move_lines.write({'date': fields.Date.to_date('2020-01-02')}) # invoice on 2020-01-04 move = self.env['account.move'].browse(self.purchase_order.action_create_invoice()['res_id']) move.invoice_date = fields.Date.to_date('2020-01-04') move.action_post() # deliver 3 on 2020-01-06 pick = pick.copy() pick.move_lines.write({'quantity_done': 3}) wiz_act = pick.button_validate() pick.move_lines.write({'date': fields.Date.to_date('2020-01-06')}) # invoice on 2020-01-08 move = self.env['account.move'].browse(self.purchase_order.action_create_invoice()['res_id']) move.invoice_date = fields.Date.to_date('2020-01-08') move.action_post() wizard = self.env['account.accrued.orders.wizard'].with_context({ 'active_model': 'purchase.order', 'active_ids': self.purchase_order.ids, }).create({ 'account_id': self.company_data['default_account_expense'].id, 'date': '2020-01-02', }) # 2 to invoice on 2020-01-07 self.assertRecordValues(self.env['account.move'].search(wizard.create_entries()['domain']).line_ids, [ # reverse move lines {'account_id': self.account_expense.id, 'debit': 0, 'credit': 60}, {'account_id': wizard.account_id.id, 'debit': 60, 'credit': 0}, # move lines {'account_id': self.account_expense.id, 'debit': 60, 'credit': 0}, {'account_id': wizard.account_id.id, 'debit': 0, 'credit': 60}, ]) # nothing to invoice on 2020-01-05 wizard.date = fields.Date.to_date('2020-01-05') with self.assertRaises(UserError): wizard.create_entries() # 3 to invoice on 2020-01-07 wizard.date = fields.Date.to_date('2020-01-07') self.assertRecordValues(self.env['account.move'].search(wizard.create_entries()['domain']).line_ids, [ # reverse move lines {'account_id': self.account_expense.id, 'debit': 0, 'credit': 90}, {'account_id': wizard.account_id.id, 'debit': 90, 'credit': 0}, # move lines {'account_id': self.account_expense.id, 'debit': 90, 'credit': 0}, {'account_id': wizard.account_id.id, 'debit': 0, 'credit': 90}, ]) # nothing to invoice on 2020-01-09 wizard.date = fields.Date.to_date('2020-01-09') with self.assertRaises(UserError): wizard.create_entries()
43.183007
6,607
1,751
py
PYTHON
15.0
from odoo.tests.common import TransactionCase, Form class TestRoutes(TransactionCase): def test_allow_rule_creation_for_route_without_company(self): self.env['res.config.settings'].write({ 'group_stock_adv_location': True, 'group_stock_multi_locations': True, }) warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1) location_1 = self.env['stock.location'].create({ 'name': 'loc1', 'location_id': warehouse.id }) location_2 = self.env['stock.location'].create({ 'name': 'loc2', 'location_id': warehouse.id }) receipt_1 = self.env['stock.picking.type'].create({ 'name': 'Receipts from loc1', 'sequence_code': 'IN1', 'code': 'incoming', 'warehouse_id': warehouse.id, 'default_location_dest_id': location_1.id, }) receipt_2 = self.env['stock.picking.type'].create({ 'name': 'Receipts from loc2', 'sequence_code': 'IN2', 'code': 'incoming', 'warehouse_id': warehouse.id, 'default_location_dest_id': location_2.id, }) route = self.env['stock.location.route'].create({ 'name': 'Buy', 'company_id': False }) with Form(route) as r: with r.rule_ids.new() as line: line.name = 'first rule' line.action = 'buy' line.picking_type_id = receipt_1 with r.rule_ids.new() as line: line.name = 'second rule' line.action = 'buy' line.picking_type_id = receipt_2
33.037736
1,751
1,709
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import UserError from .common import PurchaseTestCommon class TestDeleteOrder(PurchaseTestCommon): def test_00_delete_order(self): ''' Testcase for deleting purchase order with purchase user group''' # In order to test delete process on purchase order,tried to delete a confirmed order and check Error Message. partner = self.env['res.partner'].create({'name': 'My Partner'}) purchase_order = self.env['purchase.order'].create({ 'partner_id': partner.id, 'state': 'purchase', }) purchase_order_1 = purchase_order.with_user(self.res_users_purchase_user) with self.assertRaises(UserError): purchase_order_1.unlink() # Delete 'cancelled' purchase order with user group purchase_order = self.env['purchase.order'].create({ 'partner_id': partner.id, 'state': 'purchase', }) purchase_order_2 = purchase_order.with_user(self.res_users_purchase_user) purchase_order_2.button_cancel() self.assertEqual(purchase_order_2.state, 'cancel', 'PO is cancelled!') purchase_order_2.unlink() # Delete 'draft' purchase order with user group purchase_order = self.env['purchase.order'].create({ 'partner_id': partner.id, 'state': 'draft', }) purchase_order_3 = purchase_order.with_user(self.res_users_purchase_user) purchase_order_3.button_cancel() self.assertEqual(purchase_order_3.state, 'cancel', 'PO is cancelled!') purchase_order_3.unlink()
40.690476
1,709
2,135
py
PYTHON
15.0
from .common import PurchaseTestCommon class TestPurchaseOrderProcess(PurchaseTestCommon): def test_00_cancel_purchase_order_flow(self): """ Test cancel purchase order with group user.""" # In order to test the cancel flow,start it from canceling confirmed purchase order. purchase_order = self.env['purchase.order'].create({ 'partner_id': self.env['res.partner'].create({'name': 'My Partner'}).id, 'state': 'draft', }) po_edit_with_user = purchase_order.with_user(self.res_users_purchase_user) # Confirm the purchase order. po_edit_with_user.button_confirm() # Check the "Approved" status after confirmed RFQ. self.assertEqual(po_edit_with_user.state, 'purchase', 'Purchase: PO state should be "Purchase') # First cancel receptions related to this order if order shipped. po_edit_with_user.picking_ids.action_cancel() # Able to cancel purchase order. po_edit_with_user.button_cancel() # Check that order is cancelled. self.assertEqual(po_edit_with_user.state, 'cancel', 'Purchase: PO state should be "Cancel') def test_01_packaging_propagation(self): """Create a PO with lines using packaging, check the packaging propagate to its move. """ product = self.env['product.product'].create({ 'name': 'Product with packaging', 'type': 'product', }) packaging = self.env['product.packaging'].create({ 'name': 'box', 'product_id': product.id, }) po = self.env['purchase.order'].create({ 'partner_id': self.env['res.partner'].create({'name': 'My Partner'}).id, 'order_line': [ (0, 0, { 'product_id': product.id, 'product_qty': 1.0, 'product_uom': product.uom_id.id, 'product_packaging_id': packaging.id, })], }) po.button_confirm() self.assertEqual(po.order_line.move_ids.product_packaging_id, packaging)
38.125
2,135
20,609
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon from odoo.tests.common import Form, tagged from odoo import fields from freezegun import freeze_time @tagged('post_install', '-at_install') class TestValuationReconciliation(ValuationReconciliationTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.stock_account_product_categ.property_account_creditor_price_difference_categ = cls.company_data['default_account_stock_price_diff'] @classmethod def setup_company_data(cls, company_name, chart_template=None, **kwargs): company_data = super().setup_company_data(company_name, chart_template=chart_template, **kwargs) # Create stock config. company_data.update({ 'default_account_stock_price_diff': cls.env['account.account'].create({ 'name': 'default_account_stock_price_diff', 'code': 'STOCKDIFF', 'reconcile': True, 'user_type_id': cls.env.ref('account.data_account_type_current_assets').id, 'company_id': company_data['company'].id, }), }) return company_data def _create_purchase(self, product, date, quantity=1.0, set_tax=False, price_unit=66.0): rslt = self.env['purchase.order'].create({ 'partner_id': self.partner_a.id, 'currency_id': self.currency_data['currency'].id, 'order_line': [ (0, 0, { 'name': product.name, 'product_id': product.id, 'product_qty': quantity, 'product_uom': product.uom_po_id.id, 'price_unit': price_unit, 'date_planned': date, 'taxes_id': [(6, 0, product.supplier_taxes_id.ids)] if set_tax else False, })], 'date_order': date, }) rslt.button_confirm() return rslt def _create_invoice_for_po(self, purchase_order, date): move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice', default_date=date)) move_form.invoice_date = date move_form.partner_id = self.partner_a move_form.currency_id = self.currency_data['currency'] move_form.purchase_id = purchase_order return move_form.save() def test_shipment_invoice(self): """ Tests the case into which we receive the goods first, and then make the invoice. """ test_product = self.test_product_delivery date_po_and_delivery = '2018-01-01' purchase_order = self._create_purchase(test_product, date_po_and_delivery) self._process_pickings(purchase_order.picking_ids, date=date_po_and_delivery) invoice = self._create_invoice_for_po(purchase_order, '2018-02-02') invoice.action_post() picking = self.env['stock.picking'].search([('purchase_id','=',purchase_order.id)]) self.check_reconciliation(invoice, picking) # cancel the invoice invoice.button_cancel() def test_invoice_shipment(self): """ Tests the case into which we make the invoice first, and then receive the goods. """ # Create a PO and an invoice for it test_product = self.test_product_order purchase_order = self._create_purchase(test_product, '2017-12-01') invoice = self._create_invoice_for_po(purchase_order, '2017-12-23') move_form = Form(invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.quantity = 1 invoice = move_form.save() # Validate the invoice and refund the goods invoice.action_post() self._process_pickings(purchase_order.picking_ids, date='2017-12-24') picking = self.env['stock.picking'].search([('purchase_id', '=', purchase_order.id)]) self.check_reconciliation(invoice, picking) # Return the goods and refund the invoice stock_return_picking_form = Form(self.env['stock.return.picking'] .with_context(active_ids=picking.ids, active_id=picking.ids[0], active_model='stock.picking')) stock_return_picking = stock_return_picking_form.save() stock_return_picking.product_return_moves.quantity = 1.0 stock_return_picking_action = stock_return_picking.create_returns() return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id']) return_pick.action_assign() return_pick.move_lines.quantity_done = 1 return_pick._action_done() self._change_pickings_date(return_pick, '2018-01-13') # Refund the invoice refund_invoice_wiz = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=[invoice.id]).create({ 'reason': 'test_invoice_shipment_refund', 'refund_method': 'cancel', 'date': '2018-03-15', 'journal_id': invoice.journal_id.id, }) refund_invoice = self.env['account.move'].browse(refund_invoice_wiz.reverse_moves()['res_id']) # Check the result self.assertEqual(invoice.payment_state, 'reversed', "Invoice should be in 'reversed' state") self.assertEqual(refund_invoice.payment_state, 'paid', "Refund should be in 'paid' state") self.check_reconciliation(refund_invoice, return_pick) def test_multiple_shipments_invoices(self): """ Tests the case into which we receive part of the goods first, then 2 invoices at different rates, and finally the remaining quantities """ test_product = self.test_product_delivery date_po_and_delivery0 = '2017-01-01' purchase_order = self._create_purchase(test_product, date_po_and_delivery0, quantity=5.0) self._process_pickings(purchase_order.picking_ids, quantity=2.0, date=date_po_and_delivery0) picking = self.env['stock.picking'].search([('purchase_id', '=', purchase_order.id)], order="id asc", limit=1) invoice = self._create_invoice_for_po(purchase_order, '2017-01-15') move_form = Form(invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.quantity = 3.0 invoice = move_form.save() invoice.action_post() self.check_reconciliation(invoice, picking, full_reconcile=False) invoice2 = self._create_invoice_for_po(purchase_order, '2017-02-15') move_form = Form(invoice2) with move_form.invoice_line_ids.edit(0) as line_form: line_form.quantity = 2.0 invoice2 = move_form.save() invoice2.action_post() self.check_reconciliation(invoice2, picking, full_reconcile=False) # We don't need to make the date of processing explicit since the very last rate # will be taken self._process_pickings(purchase_order.picking_ids.filtered(lambda x: x.state != 'done'), quantity=3.0) picking = self.env['stock.picking'].search([('purchase_id', '=', purchase_order.id)], order='id desc', limit=1) self.check_reconciliation(invoice2, picking) def test_rounding_discount(self): self.env.ref("product.decimal_discount").digits = 5 tax_exclude_id = self.env["account.tax"].create( { "name": "Exclude tax", "amount": "0.00", "type_tax_use": "purchase", } ) test_product = self.test_product_delivery test_product.supplier_taxes_id = [(6, 0, tax_exclude_id.ids)] date_po_and_delivery = '2018-01-01' purchase_order = self._create_purchase(test_product, date_po_and_delivery, quantity=10000, set_tax=True) self._process_pickings(purchase_order.picking_ids, date=date_po_and_delivery) invoice = self._create_invoice_for_po(purchase_order, '2018-01-01') # Set a discount move_form = Form(invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.discount = 0.92431 move_form.save() invoice.action_post() # Check the price difference amount. price_diff_line = invoice.line_ids.filtered(lambda l: l.account_id == self.stock_account_product_categ.property_account_creditor_price_difference_categ) self.assertTrue(len(price_diff_line) == 1, "A price difference line should be created") self.assertAlmostEqual(price_diff_line.price_total, -6100.446) picking = self.env['stock.picking'].search([('purchase_id','=',purchase_order.id)]) self.check_reconciliation(invoice, picking) def test_rounding_price_unit(self): self.env.ref("product.decimal_price").digits = 6 test_product = self.test_product_delivery date_po_and_delivery = '2018-01-01' purchase_order = self._create_purchase(test_product, date_po_and_delivery, quantity=1000000, price_unit=0.0005) self._process_pickings(purchase_order.picking_ids, date=date_po_and_delivery) invoice = self._create_invoice_for_po(purchase_order, '2018-01-01') # Set a discount move_form = Form(invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 0.0006 move_form.save() invoice.action_post() # Check the price difference amount. It's expected that price_unit * qty != price_total. price_diff_line = invoice.line_ids.filtered(lambda l: l.account_id == self.stock_account_product_categ.property_account_creditor_price_difference_categ) self.assertTrue(len(price_diff_line) == 1, "A price difference line should be created") self.assertAlmostEqual(price_diff_line.price_unit, 0.0001) self.assertAlmostEqual(price_diff_line.price_total, 100.0) picking = self.env['stock.picking'].search([('purchase_id','=',purchase_order.id)]) self.check_reconciliation(invoice, picking) @freeze_time('2021-01-01') def test_rounding_price_unit_exchange_difference(self): test_product = self.test_product_delivery date_po_and_delivery = '2021-01-01' rate_po = 28.0 date_bill = '2020-01-01' rate_bill = 26.0 foreign_currency = self.currency_data['currency'] company_currency = self.env.company.currency_id self.env['res.currency.rate'].create([ { 'name': date_po_and_delivery, 'rate': rate_po, 'currency_id': foreign_currency.id, 'company_id': self.env.company.id, }, { 'name': date_bill, 'rate': rate_bill, 'currency_id': foreign_currency.id, 'company_id': self.env.company.id, }, { 'name': date_po_and_delivery, 'rate': 1.0, 'currency_id': company_currency.id, 'company_id': self.env.company.id, }, { 'name': date_bill, 'rate': 1.0, 'currency_id': company_currency.id, 'company_id': self.env.company.id, }]) purchase_order = self._create_purchase(test_product, date_po_and_delivery, quantity=100, price_unit=6000) self._process_pickings(purchase_order.picking_ids, date=date_po_and_delivery) invoice = self._create_invoice_for_po(purchase_order, date_bill) invoice.action_post() price_diff_line = invoice.line_ids.filtered(lambda l: l.account_id == self.stock_account_product_categ.property_account_creditor_price_difference_categ) self.assertFalse(price_diff_line, "No price difference line should be created") picking = self.env['stock.picking'].search([('purchase_id', '=', purchase_order.id)]) self.check_reconciliation(invoice, picking) @freeze_time('2021-01-03') def test_price_difference_exchange_difference_accounting_date(self): test_product = self.test_product_delivery test_product.categ_id.write({"property_cost_method": "standard"}) test_product.write({'standard_price': 100.0}) date_po_receipt = '2021-01-02' rate_po_receipt = 25.0 date_bill = '2021-01-01' rate_bill = 30.0 date_accounting = '2021-01-03' rate_accounting = 26.0 foreign_currency = self.currency_data['currency'] company_currency = self.env.company.currency_id self.env['res.currency.rate'].create([ { 'name': date_po_receipt, 'rate': rate_po_receipt, 'currency_id': foreign_currency.id, 'company_id': self.env.company.id, }, { 'name': date_bill, 'rate': rate_bill, 'currency_id': foreign_currency.id, 'company_id': self.env.company.id, }, { 'name': date_accounting, 'rate': rate_accounting, 'currency_id': foreign_currency.id, 'company_id': self.env.company.id, }, { 'name': date_po_receipt, 'rate': 1.0, 'currency_id': company_currency.id, 'company_id': self.env.company.id, }, { 'name': date_accounting, 'rate': 1.0, 'currency_id': company_currency.id, 'company_id': self.env.company.id, }, { 'name': date_bill, 'rate': 1.0, 'currency_id': company_currency.id, 'company_id': self.env.company.id, }]) #purchase order created in foreign currency purchase_order = self._create_purchase(test_product, date_po_receipt, quantity=10, price_unit=3000) with freeze_time(date_po_receipt): self._process_pickings(purchase_order.picking_ids) invoice = self._create_invoice_for_po(purchase_order, date_bill) with Form(invoice) as move_form: move_form.invoice_date = fields.Date.from_string(date_bill) move_form.date = fields.Date.from_string(date_accounting) invoice.action_post() price_diff_line = invoice.line_ids.filtered(lambda l: l.account_id == self.stock_account_product_categ.property_account_creditor_price_difference_categ) self.assertTrue(len(price_diff_line) == 1, "A price difference line should be created") self.assertAlmostEqual(price_diff_line.balance, 192.31) self.assertAlmostEqual(price_diff_line.price_total, 5000.0) picking = self.env['stock.picking'].search([('purchase_id', '=', purchase_order.id)]) self.check_reconciliation(invoice, picking) interim_account_id = self.company_data['default_account_stock_in'].id valuation_line = picking.move_lines.mapped('account_move_ids.line_ids').filtered(lambda x: x.account_id.id == interim_account_id) self.assertTrue(valuation_line.full_reconcile_id, "The reconciliation should be total at that point.") exchange_move = valuation_line.full_reconcile_id.exchange_move_id self.assertTrue(exchange_move, "An exchange move should exists.") exchange_difference = exchange_move.line_ids.filtered(lambda l: l.account_id.id == interim_account_id).balance self.assertAlmostEqual(exchange_difference, 38.46, "Exchange amount is incorrect") def test_reconcile_cash_basis_bill(self): ''' Test the generation of the CABA move after bill payment ''' self.env.company.tax_exigibility = True cash_basis_base_account = self.env['account.account'].create({ 'code': 'cash_basis_base_account', 'name': 'cash_basis_base_account', 'user_type_id': self.env.ref('account.data_account_type_revenue').id, 'company_id': self.company_data['company'].id, }) self.company_data['company'].account_cash_basis_base_account_id = cash_basis_base_account cash_basis_transfer_account = self.env['account.account'].create({ 'code': 'cash_basis_transfer_account', 'name': 'cash_basis_transfer_account', 'user_type_id': self.env.ref('account.data_account_type_revenue').id, 'company_id': self.company_data['company'].id, }) tax_account_1 = self.env['account.account'].create({ 'code': 'tax_account_1', 'name': 'tax_account_1', 'user_type_id': self.env.ref('account.data_account_type_revenue').id, 'company_id': self.company_data['company'].id, }) tax_tags = self.env['account.account.tag'].create({ 'name': 'tax_tag_%s' % str(i), 'applicability': 'taxes', } for i in range(8)) cash_basis_tax_a_third_amount = self.env['account.tax'].create({ 'name': 'tax_1', 'amount': 33.3333, 'company_id': self.company_data['company'].id, 'cash_basis_transition_account_id': cash_basis_transfer_account.id, 'tax_exigibility': 'on_payment', 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags[0].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_account_1.id, 'tag_ids': [(6, 0, tax_tags[1].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags[2].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_account_1.id, 'tag_ids': [(6, 0, tax_tags[3].ids)], }), ], }) product_A = self.env["product.product"].create( { "name": "Product A", "type": "product", "default_code": "prda", "categ_id": self.stock_account_product_categ.id, "taxes_id": [(5, 0, 0)], "supplier_taxes_id": [(6, 0, cash_basis_tax_a_third_amount.ids)], "lst_price": 100.0, "standard_price": 10.0, "property_account_income_id": self.company_data["default_account_revenue"].id, "property_account_expense_id": self.company_data["default_account_expense"].id, } ) product_A.categ_id.write( { "property_account_creditor_price_difference_categ": False, "property_valuation": "real_time", "property_cost_method": "standard", } ) date_po_and_delivery = '2018-01-01' purchase_order = self._create_purchase(product_A, date_po_and_delivery, set_tax=True, price_unit=300.0) self._process_pickings(purchase_order.picking_ids, date=date_po_and_delivery) bill = self._create_invoice_for_po(purchase_order, '2018-02-02') bill.action_post() # Register a payment creating the CABA journal entry on the fly and reconcile it with the tax line. self.env['account.payment.register']\ .with_context(active_ids=bill.ids, active_model='account.move')\ .create({})\ ._create_payments() partial_rec = bill.mapped('line_ids.matched_debit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) # Tax values based on payment # Invoice amount 300 self.assertRecordValues(caba_move.line_ids, [ # pylint: disable=C0326 # Base amount: {'debit': 0.0, 'credit': 150.0, 'amount_currency': -300.0, 'account_id': cash_basis_base_account.id}, {'debit': 150.0, 'credit': 0.0, 'amount_currency': 300.0, 'account_id': cash_basis_base_account.id}, # tax: {'debit': 0.0, 'credit': 50.0, 'amount_currency': -100.0, 'account_id': cash_basis_transfer_account.id}, {'debit': 50.0, 'credit': 0.0, 'amount_currency': 100.0, 'account_id': tax_account_1.id}, ])
45.797778
20,609
2,501
py
PYTHON
15.0
# -*- coding: utf-8 -*- from datetime import timedelta from odoo import fields from odoo.addons.stock.tests.common2 import TestStockCommon from odoo import tools from odoo.modules.module import get_module_resource class PurchaseTestCommon(TestStockCommon): def _create_make_procurement(self, product, product_qty, date_planned=False): ProcurementGroup = self.env['procurement.group'] order_values = { 'warehouse_id': self.warehouse_1, 'action': 'pull_push', 'date_planned': date_planned or fields.Datetime.to_string(fields.datetime.now() + timedelta(days=10)), # 10 days added to current date of procurement to get future schedule date and order date of purchase order. 'group_id': self.env['procurement.group'], } return ProcurementGroup.run([self.env['procurement.group'].Procurement( product, product_qty, self.uom_unit, self.warehouse_1.lot_stock_id, product.name, '/', self.env.company, order_values) ]) @classmethod def setUpClass(cls): super(PurchaseTestCommon, cls).setUpClass() cls.env.ref('stock.route_warehouse0_mto').active = True cls.route_buy = cls.warehouse_1.buy_pull_id.route_id.id cls.route_mto = cls.warehouse_1.mto_pull_id.route_id.id # Update product_1 with type, route and Delivery Lead Time cls.product_1.write({ 'type': 'product', 'route_ids': [(6, 0, [cls.route_buy, cls.route_mto])], 'seller_ids': [(0, 0, {'name': cls.partner_1.id, 'delay': 5})]}) cls.t_shirt = cls.env['product.product'].create({ 'name': 'T-shirt', 'description': 'Internal Notes', 'route_ids': [(6, 0, [cls.route_buy, cls.route_mto])], 'seller_ids': [(0, 0, {'name': cls.partner_1.id, 'delay': 5})] }) # Update product_2 with type, route and Delivery Lead Time cls.product_2.write({ 'type': 'product', 'route_ids': [(6, 0, [cls.route_buy, cls.route_mto])], 'seller_ids': [(0, 0, {'name': cls.partner_1.id, 'delay': 2})]}) cls.res_users_purchase_user = cls.env['res.users'].create({ 'company_id': cls.env.ref('base.main_company').id, 'name': "Purchase User", 'login': "pu", 'email': "purchaseuser@yourcompany.com", 'groups_id': [(6, 0, [cls.env.ref('purchase.group_purchase_user').id])], })
43.12069
2,501
29,295
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from datetime import datetime, timedelta from freezegun import freeze_time from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon from odoo.tests import Form, tagged @freeze_time("2021-01-14 09:12:15") @tagged('post_install', '-at_install') class TestPurchaseOrder(ValuationReconciliationTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.product_id_1 = cls.env['product.product'].create({'name': 'Large Desk', 'purchase_method': 'purchase'}) cls.product_id_2 = cls.env['product.product'].create({'name': 'Conference Chair', 'purchase_method': 'purchase'}) cls.po_vals = { 'partner_id': cls.partner_a.id, 'order_line': [ (0, 0, { 'name': cls.product_id_1.name, 'product_id': cls.product_id_1.id, 'product_qty': 5.0, 'product_uom': cls.product_id_1.uom_po_id.id, 'price_unit': 500.0, 'date_planned': datetime.today().replace(hour=9).strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), (0, 0, { 'name': cls.product_id_2.name, 'product_id': cls.product_id_2.id, 'product_qty': 5.0, 'product_uom': cls.product_id_2.uom_po_id.id, 'price_unit': 250.0, 'date_planned': datetime.today().replace(hour=9).strftime(DEFAULT_SERVER_DATETIME_FORMAT), })], } def test_00_purchase_order_flow(self): # Ensure product_id_2 doesn't have res_partner_1 as supplier if self.partner_a in self.product_id_2.seller_ids.mapped('name'): id_to_remove = self.product_id_2.seller_ids.filtered(lambda r: r.name == self.partner_a).ids[0] if self.product_id_2.seller_ids.filtered(lambda r: r.name == self.partner_a) else False if id_to_remove: self.product_id_2.write({ 'seller_ids': [(2, id_to_remove, False)], }) self.assertFalse(self.product_id_2.seller_ids.filtered(lambda r: r.name == self.partner_a), 'Purchase: the partner should not be in the list of the product suppliers') self.po = self.env['purchase.order'].create(self.po_vals) self.assertTrue(self.po, 'Purchase: no purchase order created') self.assertEqual(self.po.invoice_status, 'no', 'Purchase: PO invoice_status should be "Not purchased"') self.assertEqual(self.po.order_line.mapped('qty_received'), [0.0, 0.0], 'Purchase: no product should be received"') self.assertEqual(self.po.order_line.mapped('qty_invoiced'), [0.0, 0.0], 'Purchase: no product should be invoiced"') self.po.button_confirm() self.assertEqual(self.po.state, 'purchase', 'Purchase: PO state should be "Purchase"') self.assertEqual(self.po.invoice_status, 'to invoice', 'Purchase: PO invoice_status should be "Waiting Invoices"') self.assertTrue(self.product_id_2.seller_ids.filtered(lambda r: r.name == self.partner_a), 'Purchase: the partner should be in the list of the product suppliers') seller = self.product_id_2._select_seller(partner_id=self.partner_a, quantity=2.0, date=self.po.date_planned, uom_id=self.product_id_2.uom_po_id) price_unit = seller.price if seller else 0.0 if price_unit and seller and self.po.currency_id and seller.currency_id != self.po.currency_id: price_unit = seller.currency_id._convert(price_unit, self.po.currency_id, self.po.company_id, self.po.date_order) self.assertEqual(price_unit, 250.0, 'Purchase: the price of the product for the supplier should be 250.0.') self.assertEqual(self.po.incoming_picking_count, 1, 'Purchase: one picking should be created"') self.picking = self.po.picking_ids[0] self.picking.move_line_ids.write({'qty_done': 5.0}) self.picking.button_validate() self.assertEqual(self.po.order_line.mapped('qty_received'), [5.0, 5.0], 'Purchase: all products should be received"') move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.partner_id = self.partner_a move_form.purchase_id = self.po self.invoice = move_form.save() self.assertEqual(self.po.order_line.mapped('qty_invoiced'), [5.0, 5.0], 'Purchase: all products should be invoiced"') def test_02_po_return(self): """ Test a PO with a product on Incoming shipment. Validate the PO, then do a return of the picking with Refund. """ # Draft purchase order created self.po = self.env['purchase.order'].create(self.po_vals) self.assertTrue(self.po, 'Purchase: no purchase order created') self.assertEqual(self.po.order_line.mapped('qty_received'), [0.0, 0.0], 'Purchase: no product should be received"') self.assertEqual(self.po.order_line.mapped('qty_invoiced'), [0.0, 0.0], 'Purchase: no product should be invoiced"') self.po.button_confirm() self.assertEqual(self.po.state, 'purchase', 'Purchase: PO state should be "Purchase"') self.assertEqual(self.po.invoice_status, 'to invoice', 'Purchase: PO invoice_status should be "Waiting Invoices"') # Confirm the purchase order self.po.button_confirm() self.assertEqual(self.po.state, 'purchase', 'Purchase: PO state should be "Purchase') self.assertEqual(self.po.incoming_picking_count, 1, 'Purchase: one picking should be created"') self.picking = self.po.picking_ids[0] self.picking.move_line_ids.write({'qty_done': 5.0}) self.picking.button_validate() self.assertEqual(self.po.order_line.mapped('qty_received'), [5.0, 5.0], 'Purchase: all products should be received"') #After Receiving all products create vendor bill. move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.invoice_date = move_form.date move_form.partner_id = self.partner_a move_form.purchase_id = self.po self.invoice = move_form.save() self.invoice.action_post() self.assertEqual(self.po.order_line.mapped('qty_invoiced'), [5.0, 5.0], 'Purchase: all products should be invoiced"') # Check quantity received received_qty = sum(pol.qty_received for pol in self.po.order_line) self.assertEqual(received_qty, 10.0, 'Purchase: Received quantity should be 10.0 instead of %s after validating incoming shipment' % received_qty) # Create return picking pick = self.po.picking_ids stock_return_picking_form = Form(self.env['stock.return.picking'] .with_context(active_ids=pick.ids, active_id=pick.ids[0], active_model='stock.picking')) return_wiz = stock_return_picking_form.save() return_wiz.product_return_moves.write({'quantity': 2.0, 'to_refund': True}) # Return only 2 res = return_wiz.create_returns() return_pick = self.env['stock.picking'].browse(res['res_id']) # Validate picking return_pick.move_line_ids.write({'qty_done': 2}) return_pick.button_validate() # Check Received quantity self.assertEqual(self.po.order_line[0].qty_received, 3.0, 'Purchase: delivered quantity should be 3.0 instead of "%s" after picking return' % self.po.order_line[0].qty_received) #Create vendor bill for refund qty move_form = Form(self.env['account.move'].with_context(default_move_type='in_refund')) move_form.invoice_date = move_form.date move_form.partner_id = self.partner_a move_form.purchase_id = self.po self.invoice = move_form.save() move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.quantity = 2.0 with move_form.invoice_line_ids.edit(1) as line_form: line_form.quantity = 2.0 self.invoice = move_form.save() self.invoice.action_post() self.assertEqual(self.po.order_line.mapped('qty_invoiced'), [3.0, 3.0], 'Purchase: Billed quantity should be 3.0') def test_03_po_return_and_modify(self): """Change the picking code of the delivery to internal. Make a PO for 10 units, go to the picking and return 5, edit the PO line to 15 units. The purpose of the test is to check the consistencies across the received quantities and the procurement quantities. """ # Change the code of the picking type delivery self.env['stock.picking.type'].search([('code', '=', 'outgoing')]).write({'code': 'internal'}) # Sell and deliver 10 units item1 = self.product_id_1 uom_unit = self.env.ref('uom.product_uom_unit') po1 = self.env['purchase.order'].create({ 'partner_id': self.partner_a.id, 'order_line': [ (0, 0, { 'name': item1.name, 'product_id': item1.id, 'product_qty': 10, 'product_uom': uom_unit.id, 'price_unit': 123.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po1.button_confirm() picking = po1.picking_ids wiz_act = picking.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() # Return 5 units stock_return_picking_form = Form(self.env['stock.return.picking'].with_context( active_ids=picking.ids, active_id=picking.ids[0], active_model='stock.picking' )) return_wiz = stock_return_picking_form.save() for return_move in return_wiz.product_return_moves: return_move.write({ 'quantity': 5, 'to_refund': True }) res = return_wiz.create_returns() return_pick = self.env['stock.picking'].browse(res['res_id']) wiz_act = return_pick.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() self.assertEqual(po1.order_line.qty_received, 5) # Deliver 15 instead of 10. po1.write({ 'order_line': [ (1, po1.order_line[0].id, {'product_qty': 15}), ] }) # A new move of 10 unit (15 - 5 units) self.assertEqual(po1.order_line.qty_received, 5) self.assertEqual(po1.picking_ids[-1].move_lines.product_qty, 10) def test_04_update_date_planned(self): today = datetime.today().replace(hour=9, microsecond=0) tomorrow = datetime.today().replace(hour=9, microsecond=0) + timedelta(days=1) po = self.env['purchase.order'].create(self.po_vals) po.button_confirm() # update first line po._update_date_planned_for_lines([(po.order_line[0], tomorrow)]) self.assertEqual(po.order_line[0].date_planned, tomorrow) activity = self.env['mail.activity'].search([ ('summary', '=', 'Date Updated'), ('res_model_id', '=', 'purchase.order'), ('res_id', '=', po.id), ]) self.assertTrue(activity) self.assertEqual( '<p>partner_a modified receipt dates for the following products:</p>\n' '<p> - Large Desk from %s to %s</p>\n' '<p>Those dates have been updated accordingly on the receipt %s.</p>' % (today.date(), tomorrow.date(), po.picking_ids.name), activity.note, ) # receive products wiz_act = po.picking_ids.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() # update second line old_date = po.order_line[1].date_planned po._update_date_planned_for_lines([(po.order_line[1], tomorrow)]) self.assertEqual(po.order_line[1].date_planned, old_date) self.assertEqual( '<p>partner_a modified receipt dates for the following products:</p>\n' '<p> - Large Desk from %s to %s</p>\n' '<p> - Conference Chair from %s to %s</p>\n' '<p>Those dates couldn’t be modified accordingly on the receipt %s which had already been validated.</p>' % ( today.date(), tomorrow.date(), today.date(), tomorrow.date(), po.picking_ids.name), activity.note, ) def test_05_multi_company(self): company_a = self.env.user.company_id company_b = self.env['res.company'].create({ "name": "Test Company", "currency_id": self.env['res.currency'].with_context(active_test=False).search([ ('id', '!=', company_a.currency_id.id), ], limit=1).id }) self.env.user.write({ 'company_id': company_b.id, 'company_ids': [(4, company_b.id), (4, company_a.id)], }) po = self.env['purchase.order'].create(dict(company_id=company_a.id, partner_id=self.partner_a.id)) self.assertEqual(po.company_id, company_a) self.assertEqual(po.picking_type_id.warehouse_id.company_id, company_a) self.assertEqual(po.currency_id, po.company_id.currency_id) def test_06_on_time_rate(self): company_a = self.env.user.company_id company_b = self.env['res.company'].create({ "name": "Test Company", "currency_id": self.env['res.currency'].with_context(active_test=False).search([ ('id', '!=', company_a.currency_id.id), ], limit=1).id }) # Create a purchase order with 90% qty received for company A self.env.user.write({ 'company_id': company_a.id, 'company_ids': [(6, 0, [company_a.id])], }) po = self.env['purchase.order'].create(self.po_vals) po.order_line.write({'product_qty': 10}) po.button_confirm() picking = po.picking_ids[0] # Process 9.0 out of the 10.0 ordered qty picking.move_line_ids.write({'qty_done': 9.0}) res_dict = picking.button_validate() # No backorder self.env['stock.backorder.confirmation'].with_context(res_dict['context']).process_cancel_backorder() # `on_time_rate` should be equals to the ratio of quantity received against quantity ordered expected_rate = sum(picking.move_line_ids.mapped("qty_done")) / sum(po.order_line.mapped("product_qty")) * 100 self.assertEqual(expected_rate, po.on_time_rate) # Create a purchase order with 80% qty received for company B # The On-Time Delivery Rate shouldn't be shared across multiple companies self.env.user.write({ 'company_id': company_b.id, 'company_ids': [(6, 0, [company_b.id])], }) po = self.env['purchase.order'].create(self.po_vals) po.order_line.write({'product_qty': 10}) po.button_confirm() picking = po.picking_ids[0] # Process 8.0 out of the 10.0 ordered qty picking.move_line_ids.write({'qty_done': 8.0}) res_dict = picking.button_validate() # No backorder self.env['stock.backorder.confirmation'].with_context(res_dict['context']).process_cancel_backorder() # `on_time_rate` should be equal to the ratio of quantity received against quantity ordered expected_rate = sum(picking.move_line_ids.mapped("qty_done")) / sum(po.order_line.mapped("product_qty")) * 100 self.assertEqual(expected_rate, po.on_time_rate) # Tricky corner case # As `purchase.order.on_time_rate` is a related to `partner_id.on_time_rate` # `on_time_rate` on the PO should equals `on_time_rate` on the partner. # Related fields are by default computed as sudo # while non-stored computed fields are not computed as sudo by default # If the computation of the related field (`purchase.order.on_time_rate`) was asked # and `res.partner.on_time_rate` was not yet in the cache # the `sudo` requested for the computation of the related `purchase.order.on_time_rate` # was propagated to the computation of `res.partner.on_time_rate` # and therefore the multi-company record rules were ignored. # 1. Compute `res.partner.on_time_rate` regular non-stored comptued field partner_on_time_rate = po.partner_id.on_time_rate # 2. Invalidate the cache for that record and field, so it's not reused in the next step. po.partner_id.invalidate_cache(fnames=["on_time_rate"], ids=po.partner_id.ids) # 3. Compute the related field `purchase.order.on_time_rate` po_on_time_rate = po.on_time_rate # 4. Check both are equals. self.assertEqual(partner_on_time_rate, po_on_time_rate) def test_04_multi_uom(self): yards_uom = self.env['uom.uom'].create({ 'category_id': self.env.ref('uom.uom_categ_length').id, 'name': 'Yards', 'factor_inv': 0.9144, 'uom_type': 'bigger', }) self.product_id_2.write({ 'uom_id': self.env.ref('uom.product_uom_meter').id, 'uom_po_id': yards_uom.id, }) po = self.env['purchase.order'].create({ 'partner_id': self.partner_a.id, 'order_line': [ (0, 0, { 'name': self.product_id_2.name, 'product_id': self.product_id_2.id, 'product_qty': 4.0, 'product_uom': self.product_id_2.uom_po_id.id, 'price_unit': 1.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }) ], }) po.button_confirm() picking = po.picking_ids[0] picking.move_line_ids.write({'qty_done': 3.66}) picking.button_validate() self.assertEqual(po.order_line.mapped('qty_received'), [4.0], 'Purchase: no conversion error on receipt in different uom"') def test_05_po_update_qty_stock_move_merge(self): """ This test ensures that changing product quantity when unit price has high decimal precision merged with the original instead of creating a new return """ unit_price_precision = self.env['decimal.precision'].search([('name', '=', 'Product Price')]) unit_price_precision.digits = 6 tax = self.env["account.tax"].create({ "name": "Dummy Tax", "amount": "5.00", "type_tax_use": "purchase", }) super_product = self.env['product.product'].create({ 'name': 'Super Product', 'type': 'product', 'categ_id': self.stock_account_product_categ.id, 'standard_price': 9.876543, }) purchase_order = self.env['purchase.order'].create({ 'partner_id': self.env.ref('base.res_partner_3').id, 'order_line': [(0, 0, { 'name': super_product.name, 'product_id': super_product.id, 'product_qty': 7, 'product_uom': super_product.uom_id.id, 'price_unit': super_product.standard_price, 'taxes_id': [(4, tax.id)], })], }) purchase_order.button_confirm() self.assertEqual(purchase_order.state, 'purchase') self.assertEqual(len(purchase_order.picking_ids), 1) self.assertEqual(len(purchase_order.picking_ids.move_line_ids), 1) self.assertEqual(purchase_order.picking_ids.move_line_ids.product_qty, 7) purchase_order.order_line.product_qty = 4 # updating quantity shouldn't create a seperate stock move # the new stock move (-3) should be merged with the previous purchase_order.button_confirm() self.assertEqual(len(purchase_order.picking_ids), 1) self.assertEqual(len(purchase_order.picking_ids.move_line_ids), 1) self.assertEqual(purchase_order.picking_ids.move_line_ids.product_qty, 4) def test_message_qty_already_received(self): _product = self.env['product.product'].create({ 'name': 'TempProduct', 'type': 'consu', 'company_id': self.env.user.company_id.id, }) _purchase_order = self.env['purchase.order'].create({ 'company_id': self.env.user.company_id.id, 'partner_id': self.partner_a.id, 'order_line': [ (0, 0, { 'name': _product.name, 'product_id': _product.id, 'product_qty': 25.0, 'price_unit': 250.0, })], }) _purchase_order.button_confirm() first_picking = _purchase_order.picking_ids[0] first_picking.move_lines.quantity_done = 5 backorder_wizard_dict = first_picking.button_validate() backorder_wizard = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context'])).save() backorder_wizard.process() second_picking = _purchase_order.picking_ids[1] second_picking.move_lines.quantity_done = 5 backorder_wizard_dict = second_picking.button_validate() backorder_wizard = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context'])).save() backorder_wizard.process() third_picking = _purchase_order.picking_ids[2] third_picking.move_lines.quantity_done = 5 backorder_wizard_dict = third_picking.button_validate() backorder_wizard = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context'])).save() backorder_wizard.process() _message_content = _purchase_order.message_ids.mapped("body")[0] self.assertIsNotNone(re.search(r"Received Quantity: 5.0 -&gt; 10.0", _message_content), "Already received quantity isn't correctly taken into consideration") def test_pol_description(self): """ Suppose a product with several sellers, all with the same partner. On the purchase order, the product description should be based on the correct seller """ self.env.user.write({'company_id': self.company_data['company'].id}) product = self.env['product.product'].create({ 'name': 'Super Product', 'seller_ids': [(0, 0, { 'name': self.partner_a.id, 'min_qty': 1, 'price': 10, 'product_code': 'C01', 'product_name': 'Name01', 'sequence': 1, }), (0, 0, { 'name': self.partner_a.id, 'min_qty': 20, 'price': 2, 'product_code': 'C02', 'product_name': 'Name02', 'sequence': 2, })] }) orderpoint_form = Form(self.env['stock.warehouse.orderpoint']) orderpoint_form.product_id = product orderpoint_form.product_min_qty = 1 orderpoint_form.product_max_qty = 0.000 order_point = orderpoint_form.save() self.env['procurement.group'].run_scheduler() pol = self.env['purchase.order.line'].search([('product_id', '=', product.id)]) self.assertEqual(pol.name, "[C01] Name01") with Form(pol.order_id) as po_form: with po_form.order_line.edit(0) as pol_form: pol_form.product_qty = 25 self.assertEqual(pol.name, "[C02] Name02") def test_packaging_and_qty_decrease(self): packaging = self.env['product.packaging'].create({ 'name': "Super Packaging", 'product_id': self.product_a.id, 'qty': 10.0, }) po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner_a with po_form.order_line.new() as line: line.product_id = self.product_a line.product_qty = 10 po = po_form.save() po.button_confirm() self.assertEqual(po.order_line.product_packaging_id, packaging) with Form(po) as po_form: with po_form.order_line.edit(0) as line: line.product_qty = 8 self.assertEqual(po.picking_ids.move_lines.product_uom_qty, 8) def test_packaging_propagation(self): """ Editing the packaging on an purchase.order.line should propagate to the delivery order, so that when we are editing the packaging, the lines can be merged with the new packaging and quantity. """ # set the 3 step route warehouse = self.company_data['default_warehouse'] warehouse.reception_steps = 'three_steps' packOf10 = self.env['product.packaging'].create({ 'name': 'PackOf10', 'product_id': self.product_a.id, 'qty': 10 }) packOf20 = self.env['product.packaging'].create({ 'name': 'PackOf20', 'product_id': self.product_a.id, 'qty': 20 }) po = self.env['purchase.order'].create({ 'partner_id': self.partner_a.id, 'order_line': [ (0, 0, { 'product_id': self.product_a.id, 'product_uom_qty': 10.0, 'product_uom': self.product_a.uom_id.id, 'product_packaging_id': packOf10.id, })], }) po.button_confirm() # the 3 moves for the 3 steps step_1 = po.order_line.move_ids step_2 = step_1.move_dest_ids step_3 = step_2.move_dest_ids self.assertEqual(step_1.product_packaging_id, packOf10) self.assertEqual(step_2.product_packaging_id, packOf10) self.assertEqual(step_3.product_packaging_id, packOf10) po.order_line[0].write({ 'product_packaging_id': packOf20.id, 'product_uom_qty': 20 }) self.assertEqual(step_1.product_packaging_id, packOf20) self.assertEqual(step_2.product_packaging_id, packOf20) self.assertEqual(step_3.product_packaging_id, packOf20) po.order_line[0].write({'product_packaging_id': False}) self.assertFalse(step_1.product_packaging_id) self.assertFalse(step_2.product_packaging_id) self.assertFalse(step_3.product_packaging_id) def test_putaway_strategy_in_backorder(self): stock_location = self.company_data['default_warehouse'].lot_stock_id sub_loc_01 = self.env['stock.location'].create([{ 'name': 'Sub Location 1', 'usage': 'internal', 'location_id': stock_location.id, }]) self.env["stock.putaway.rule"].create({ "location_in_id": stock_location.id, "location_out_id": sub_loc_01.id, "product_id": self.product_a.id, }) po = self.env['purchase.order'].create({ 'partner_id': self.partner_a.id, 'order_line': [ (0, 0, { 'product_id': self.product_a.id, 'product_qty': 2.0, })], }) po.button_confirm() picking = po.picking_ids self.assertEqual(po.state, "purchase") self.assertEqual(picking.move_line_ids_without_package.location_dest_id.id, sub_loc_01.id) picking.move_line_ids_without_package.write({'qty_done': 1}) res_dict = picking.button_validate() self.env[res_dict['res_model']].with_context(res_dict['context']).process() backorder = picking.backorder_ids self.assertEqual(backorder.move_line_ids_without_package.location_dest_id.id, sub_loc_01.id) def test_inventory_adjustments_with_po(self): """ check that the quant created by a PO can be applied in an inventory adjustment correctly """ product = self.env['product.product'].create({ 'name': 'Product A', 'type': 'product', }) po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner_a with po_form.order_line.new() as line: line.product_id = product line.product_qty = 5 po = po_form.save() po.button_confirm() po.picking_ids.move_lines.quantity_done = 5 po.picking_ids.button_validate() self.assertEqual(po.picking_ids.state, 'done') quant = self.env['stock.quant'].search([('product_id', '=', product.id), ('location_id.usage', '=', 'internal')]) wizard = self.env['stock.inventory.adjustment.name'].create({'quant_ids': quant}) wizard.action_apply() self.assertEqual(quant.quantity, 5)
46.496825
29,293
3,978
py
PYTHON
15.0
# -*- coding: utf-8 -*- import time from odoo.tests import tagged, Form from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon @tagged('-at_install', 'post_install') class TestFifoReturns(ValuationReconciliationTestCommon): def test_fifo_returns(self): """Test to create product and purchase order to test the FIFO returns of the product""" res_partner_3 = self.env['res.partner'].create({ 'name': 'Gemini Partner', }) # Set a product as using fifo price product_fiforet_icecream = self.env['product.product'].create({ 'default_code': 'FIFORET', 'name': 'FIFO Ice Cream', 'type': 'product', 'categ_id': self.stock_account_product_categ.id, 'standard_price': 0.0, 'uom_id': self.env.ref('uom.product_uom_kgm').id, 'uom_po_id': self.env.ref('uom.product_uom_kgm').id, 'description': 'FIFO Ice Cream', }) # I create a draft Purchase Order for first in move for 10 kg at 50 euro purchase_order_1 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': 'FIFO Ice Cream', 'product_id': product_fiforet_icecream.id, 'product_qty': 10.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 50.0, 'date_planned': time.strftime('%Y-%m-%d'), })], }) # Create a draft Purchase Order for second shipment for 30kg at 80€/kg purchase_order_2 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': 'FIFO Ice Cream', 'product_id': product_fiforet_icecream.id, 'product_qty': 30.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 80.0, 'date_planned': time.strftime('%Y-%m-%d'), })], }) # Confirm the first purchase order purchase_order_1.button_confirm() # Process the reception of purchase order 1 picking = purchase_order_1.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check the standard price of the product (fifo icecream) self.assertAlmostEqual(product_fiforet_icecream.standard_price, 50) # Confirm the second purchase order purchase_order_2.button_confirm() picking = purchase_order_2.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Return the goods of purchase order 2 picking = purchase_order_2.picking_ids[0] stock_return_picking_form = Form(self.env['stock.return.picking'] .with_context(active_ids=picking.ids, active_id=picking.ids[0], active_model='stock.picking')) return_pick_wiz = stock_return_picking_form.save() return_picking_id, dummy = return_pick_wiz.with_context(active_id=picking.id)._create_returns() # Important to pass through confirmation and assignation return_picking = self.env['stock.picking'].browse(return_picking_id) return_picking.action_confirm() return_picking.move_lines[0].quantity_done = return_picking.move_lines[0].product_uom_qty return_picking._action_done() # After the return only 10 of the second purchase order should still be in stock as it applies fifo on the return too self.assertEqual(product_fiforet_icecream.qty_available, 10.0, 'Qty available should be 10.0') self.assertEqual(product_fiforet_icecream.value_svl, 800.0, 'Stock value should be 800')
44.674157
3,976
911
py
PYTHON
15.0
from odoo.tests.common import TransactionCase class TestProductTemplate(TransactionCase): def test_name_search(self): partner = self.env['res.partner'].create({ 'name': 'Azure Interior', }) seller = self.env['product.supplierinfo'].create({ 'name': partner.id, 'price': 12.0, 'delay': 1, 'product_code': 'VOB2a', }) product_tmpl = self.env['product.template'].create({ 'name': 'Rubber Duck', 'type': 'product', 'default_code': 'VOB2A', 'seller_ids': [seller.id], 'purchase_ok': True, }) ns = self.env['product.template'].with_context(partner_id=partner.id).name_search('VOB2', [['purchase_ok', '=', True]]) self.assertEqual(len(ns), 1, "name_search should have 1 item") self.assertEqual(ns[0][1], '[VOB2A] Rubber Duck', "name_search should return the expected result")
35.038462
911
5,474
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from odoo import fields from odoo.tests.common import TransactionCase, Form from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT class TestOnchangeProductId(TransactionCase): """Test that when an included tax is mapped by a fiscal position, the included tax must be subtracted to the price of the product. """ def setUp(self): super(TestOnchangeProductId, self).setUp() self.fiscal_position_model = self.env['account.fiscal.position'] self.fiscal_position_tax_model = self.env['account.fiscal.position.tax'] self.tax_model = self.env['account.tax'] self.po_model = self.env['purchase.order'] self.po_line_model = self.env['purchase.order.line'] self.res_partner_model = self.env['res.partner'] self.product_tmpl_model = self.env['product.template'] self.product_model = self.env['product.product'] self.product_uom_model = self.env['uom.uom'] self.supplierinfo_model = self.env["product.supplierinfo"] def test_onchange_product_id(self): uom_id = self.product_uom_model.search([('name', '=', 'Units')])[0] partner_id = self.res_partner_model.create(dict(name="George")) tax_include_id = self.tax_model.create(dict(name="Include tax", amount='21.00', price_include=True, type_tax_use='purchase')) tax_exclude_id = self.tax_model.create(dict(name="Exclude tax", amount='0.00', type_tax_use='purchase')) supplierinfo_vals = { 'name': partner_id.id, 'price': 121.0, } supplierinfo = self.supplierinfo_model.create(supplierinfo_vals) product_tmpl_id = self.product_tmpl_model.create(dict(name="Voiture", list_price=121, seller_ids=[(6, 0, [supplierinfo.id])], supplier_taxes_id=[(6, 0, [tax_include_id.id])])) product_id = product_tmpl_id.product_variant_id fp_id = self.fiscal_position_model.create(dict(name="fiscal position", sequence=1)) fp_tax_id = self.fiscal_position_tax_model.create(dict(position_id=fp_id.id, tax_src_id=tax_include_id.id, tax_dest_id=tax_exclude_id.id)) po_vals = { 'partner_id': partner_id.id, 'fiscal_position_id': fp_id.id, 'order_line': [ (0, 0, { 'name': product_id.name, 'product_id': product_id.id, 'product_qty': 1.0, 'product_uom': uom_id.id, 'price_unit': 121.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), })], } po = self.po_model.create(po_vals) po_line = po.order_line[0] po_line.onchange_product_id() self.assertEqual(100, po_line.price_unit, "The included tax must be subtracted to the price") supplierinfo.write({'min_qty': 24}) po_line.write({'product_qty': 20}) po_line._onchange_quantity() self.assertEqual(0, po_line.price_unit, "Unit price should be reset to 0 since the supplier supplies minimum of 24 quantities") po_line.write({'product_qty': 3, 'product_uom': self.ref("uom.product_uom_dozen")}) po_line._onchange_quantity() self.assertEqual(1200, po_line.price_unit, "Unit price should be 1200 for one Dozen") ipad_uom = self.env['uom.category'].create({'name': 'Ipad Unit'}) ipad_lot = self.env['uom.uom'].create({ 'name': 'Ipad', 'category_id': ipad_uom.id, 'uom_type': 'reference', 'rounding': 0.001 }) ipad_lot_10 = self.env['uom.uom'].create({ 'name': '10 Ipad', 'category_id': ipad_uom.id, 'uom_type': 'bigger', 'rounding': 0.001, "factor_inv": 10 }) product_ipad = self.env['product.product'].create({ 'name': 'Conference Chair', 'standard_price': 100, 'uom_id': ipad_lot.id, 'uom_po_id': ipad_lot.id, }) po_line2 = self.po_line_model.create({ 'name': product_ipad.name, 'product_id': product_ipad.id, 'order_id': po.id, 'product_qty': 5, 'product_uom': ipad_uom.id, 'date_planned': fields.Date().today() }) po_line2.onchange_product_id() self.assertEqual(100, po_line2.price_unit, "No vendor supplies this product, hence unit price should be set to 100") po_form = Form(po) with po_form.order_line.edit(1) as order_line: order_line.product_uom = ipad_lot_10 po_form.save() self.assertEqual(1000, po_line2.price_unit, "The product_uom is multiplied by 10, hence unit price should be set to 1000")
45.239669
5,474
6,544
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon from odoo.tests import tagged, Form import time @tagged('-at_install', 'post_install') class TestAveragePrice(ValuationReconciliationTestCommon): def test_00_average_price(self): """ Testcase for average price computation""" res_partner_3 = self.env['res.partner'].create({ 'name': 'Gemini Partner', }) # Set a product as using average price. product_cable_management_box = self.env['product.product'].create({ 'default_code': 'AVG', 'name': 'Average Ice Cream', 'type': 'product', 'categ_id': self.stock_account_product_categ.id, 'list_price': 100.0, 'standard_price': 60.0, 'uom_id': self.env.ref('uom.product_uom_kgm').id, 'uom_po_id': self.env.ref('uom.product_uom_kgm').id, 'supplier_taxes_id': [], 'description': 'FIFO Ice Cream', }) product_cable_management_box.categ_id.property_cost_method = 'average' # I create a draft Purchase Order for first incoming shipment for 10 pieces at 60€ purchase_order_1 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': 'Average Ice Cream', 'product_id': product_cable_management_box.id, 'product_qty': 10.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 60.0, 'date_planned': time.strftime('%Y-%m-%d'), })] }) # Confirm the first purchase order purchase_order_1.button_confirm() # Check the "Approved" status of purchase order 1 self.assertEqual(purchase_order_1.state, 'purchase', "Wrong state of purchase order!") # Process the reception of purchase order 1 picking = purchase_order_1.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check the average_price of the product (average icecream). self.assertEqual(product_cable_management_box.qty_available, 10.0, 'Wrong quantity in stock after first reception') self.assertEqual(product_cable_management_box.standard_price, 60.0, 'Standard price should be the price of the first reception!') # I create a draft Purchase Order for second incoming shipment for 30 pieces at 80€ purchase_order_2 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': product_cable_management_box.name, 'product_id': product_cable_management_box.id, 'product_qty': 30.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'price_unit': 80.0, 'date_planned': time.strftime('%Y-%m-%d'), })] }) # Confirm the second purchase order purchase_order_2.button_confirm() # Process the reception of purchase order 2 picking = purchase_order_2.picking_ids[0] res = picking.button_validate() Form(self.env['stock.immediate.transfer'].with_context(res['context'])).save().process() # Check the standard price self.assertEqual(product_cable_management_box.standard_price, 75.0, 'After second reception, we should have an average price of 75.0 on the product') # Create picking to send some goods outgoing_shipment = self.env['stock.picking'].create({ 'picking_type_id': self.company_data['default_warehouse'].out_type_id.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id, 'move_lines': [(0, 0, { 'name': 'outgoing_shipment_avg_move', 'product_id': product_cable_management_box.id, 'product_uom_qty': 20.0, 'product_uom': self.env.ref('uom.product_uom_kgm').id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'location_dest_id': self.env.ref('stock.stock_location_customers').id})] }) # Assign this outgoing shipment and process the delivery outgoing_shipment.action_assign() res = outgoing_shipment.button_validate() Form(self.env['stock.immediate.transfer'].with_context(res['context'])).save().process() # Check the average price (60 * 10 + 30 * 80) / 40 = 75.0€ did not change self.assertEqual(product_cable_management_box.standard_price, 75.0, 'Average price should not have changed with outgoing picking!') self.assertEqual(product_cable_management_box.qty_available, 20.0, 'Pieces were not picked correctly as the quantity on hand is wrong') # Make a new purchase order with 500 g Average Ice Cream at a price of 0.2€/g purchase_order_3 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [(0, 0, { 'name': product_cable_management_box.name, 'product_id': product_cable_management_box.id, 'product_qty': 500.0, 'product_uom': self.ref('uom.product_uom_gram'), 'price_unit': 0.2, 'date_planned': time.strftime('%Y-%m-%d'), })] }) # Confirm the first purchase order purchase_order_3.button_confirm() # Process the reception of purchase order 3 in grams picking = purchase_order_3.picking_ids[0] res = picking.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check price is (75.0 * 20 + 200*0.5) / 20.5 = 78.04878€ self.assertEqual(product_cable_management_box.qty_available, 20.5, 'Reception of purchase order in grams leads to wrong quantity in stock') self.assertEqual(round(product_cable_management_box.standard_price, 2), 78.05, 'Standard price as average price of third reception with other UoM incorrect! Got %s instead of 78.05' % (round(product_cable_management_box.standard_price, 2)))
49.5
6,534
10,181
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.stock.tests.common import TestStockCommon class TestReplenishWizard(TestStockCommon): def setUp(self): super(TestReplenishWizard, self).setUp() self.vendor = self.env['res.partner'].create(dict(name='The Replenisher')) self.product1_price = 500 # Create a supplier info witch the previous vendor self.supplierinfo = self.env['product.supplierinfo'].create({ 'name': self.vendor.id, 'price': self.product1_price, }) # Create a product with the 'buy' route and # the 'supplierinfo' prevously created self.product1 = self.env['product.product'].create({ 'name': 'product a', 'type': 'product', 'categ_id': self.env.ref('product.product_category_all').id, 'seller_ids': [(4, self.supplierinfo.id, 0)], 'route_ids': [(4, self.env.ref('purchase_stock.route_warehouse0_buy').id, 0)], }) # Additional Values required by the replenish wizard self.uom_unit = self.env.ref('uom.product_uom_unit') self.wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1) def test_replenish_buy_1(self): """ Set a quantity to replenish via the "Buy" route and check if a purchase order is created with the correct values """ self.product_uom_qty = 42 replenish_wizard = self.env['product.replenish'].create({ 'product_id': self.product1.id, 'product_tmpl_id': self.product1.product_tmpl_id.id, 'product_uom_id': self.uom_unit.id, 'quantity': self.product_uom_qty, 'warehouse_id': self.wh.id, }) replenish_wizard.launch_replenishment() last_po_id = self.env['purchase.order'].search([ ('origin', 'ilike', '%Manual Replenishment%'), ('partner_id', '=', self.vendor.id) ])[-1] self.assertTrue(last_po_id, 'Purchase Order not found') order_line = last_po_id.order_line.search([('product_id', '=', self.product1.id)]) self.assertTrue(order_line, 'The product is not in the Purchase Order') self.assertEqual(order_line.product_qty, self.product_uom_qty, 'Quantities does not match') self.assertEqual(order_line.price_unit, self.product1_price, 'Prices does not match') def test_chose_supplier_1(self): """ Choose supplier based on the ordered quantity and minimum price replenish 10 1)seq1 vendor1 140 min qty 1 2)seq2 vendor1 100 min qty 10 -> 2) should be chosen """ product_to_buy = self.env['product.product'].create({ 'name': "Furniture Service", 'type': 'product', 'categ_id': self.env.ref('product.product_category_all').id, 'route_ids': [(4, self.env.ref('purchase_stock.route_warehouse0_buy').id, 0)], }) vendor1 = self.env['res.partner'].create({'name': 'vendor1', 'email': 'from.test@example.com'}) supplierinfo1 = self.env['product.supplierinfo'].create({ 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'name': vendor1.id, 'min_qty': 1, 'price': 140, 'sequence': 1, }) supplierinfo2 = self.env['product.supplierinfo'].create({ 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'name': vendor1.id, 'min_qty': 10, 'price': 100, 'sequence': 2, }) replenish_wizard = self.env['product.replenish'].create({ 'product_id': product_to_buy.id, 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'product_uom_id': self.uom_unit.id, 'quantity': 10, 'warehouse_id': self.wh.id, }) replenish_wizard.launch_replenishment() last_po_id = self.env['purchase.order'].search([ ('origin', 'ilike', '%Manual Replenishment%'), ])[-1] self.assertEqual(last_po_id.partner_id, vendor1) self.assertEqual(last_po_id.order_line.price_unit, 100) def test_chose_supplier_2(self): """ Choose supplier based on the ordered quantity and minimum price replenish 10 1)seq1 vendor1 140 min qty 1 2)seq2 vendor2 90 min qty 10 3)seq3 vendor1 100 min qty 10 -> 3) should be chosen """ product_to_buy = self.env['product.product'].create({ 'name': "Furniture Service", 'type': 'product', 'categ_id': self.env.ref('product.product_category_all').id, 'route_ids': [(4, self.env.ref('purchase_stock.route_warehouse0_buy').id, 0)], }) vendor1 = self.env['res.partner'].create({'name': 'vendor1', 'email': 'from.test@example.com'}) vendor2 = self.env['res.partner'].create({'name': 'vendor2', 'email': 'from.test2@example.com'}) supplierinfo1 = self.env['product.supplierinfo'].create({ 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'name': vendor1.id, 'min_qty': 1, 'price': 140, 'sequence': 1, }) supplierinfo2 = self.env['product.supplierinfo'].create({ 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'name': vendor2.id, 'min_qty': 10, 'price': 90, 'sequence': 2, }) supplierinfo3 = self.env['product.supplierinfo'].create({ 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'name': vendor1.id, 'min_qty': 10, 'price': 100, 'sequence': 3, }) replenish_wizard = self.env['product.replenish'].create({ 'product_id': product_to_buy.id, 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'product_uom_id': self.uom_unit.id, 'quantity': 10, 'warehouse_id': self.wh.id, }) replenish_wizard.launch_replenishment() last_po_id = self.env['purchase.order'].search([ ('origin', 'ilike', '%Manual Replenishment%'), ])[-1] self.assertEqual(last_po_id.partner_id, vendor1) self.assertEqual(last_po_id.order_line.price_unit, 100) def test_chose_supplier_3(self): """ Choose supplier based on the ordered quantity and minimum price replenish 10 1)seq2 vendor1 50 2)seq1 vendor2 50 -> 2) should be chosen """ product_to_buy = self.env['product.product'].create({ 'name': "Furniture Service", 'type': 'product', 'categ_id': self.env.ref('product.product_category_all').id, 'route_ids': [(4, self.env.ref('purchase_stock.route_warehouse0_buy').id, 0)], }) vendor1 = self.env['res.partner'].create({'name': 'vendor1', 'email': 'from.test@example.com'}) vendor2 = self.env['res.partner'].create({'name': 'vendor2', 'email': 'from.test2@example.com'}) supplierinfo1 = self.env['product.supplierinfo'].create({ 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'name': vendor1.id, 'price': 50, 'sequence': 2, }) supplierinfo2 = self.env['product.supplierinfo'].create({ 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'name': vendor2.id, 'price': 50, 'sequence': 1, }) replenish_wizard = self.env['product.replenish'].create({ 'product_id': product_to_buy.id, 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'product_uom_id': self.uom_unit.id, 'quantity': 10, 'warehouse_id': self.wh.id, }) replenish_wizard.launch_replenishment() last_po_id = self.env['purchase.order'].search([ ('origin', 'ilike', '%Manual Replenishment%'), ])[-1] self.assertEqual(last_po_id.partner_id, vendor2) def test_chose_supplier_4(self): """ Choose supplier based on the ordered quantity and minimum price replenish 10 1)seq1 vendor1 100 min qty 2 2)seq2 vendor1 60 min qty 10 2)seq3 vendor1 80 min qty 5 -> 2) should be chosen """ product_to_buy = self.env['product.product'].create({ 'name': "Furniture Service", 'type': 'product', 'categ_id': self.env.ref('product.product_category_all').id, 'route_ids': [(4, self.env.ref('purchase_stock.route_warehouse0_buy').id, 0)], }) vendor1 = self.env['res.partner'].create({'name': 'vendor1', 'email': 'from.test@example.com'}) supplierinfo1 = self.env['product.supplierinfo'].create({ 'name': vendor1.id, 'price': 100, 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'min_qty': 2 }) supplierinfo2 = self.env['product.supplierinfo'].create({ 'name': vendor1.id, 'price': 60, 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'min_qty': 10 }) supplierinfo3 = self.env['product.supplierinfo'].create({ 'name': vendor1.id, 'price': 80, 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'min_qty': 5 }) replenish_wizard = self.env['product.replenish'].create({ 'product_id': product_to_buy.id, 'product_tmpl_id': product_to_buy.product_tmpl_id.id, 'product_uom_id': self.uom_unit.id, 'quantity': 10, 'warehouse_id': self.wh.id, }) replenish_wizard.launch_replenishment() last_po_id = self.env['purchase.order'].search([ ('origin', 'ilike', '%Manual Replenishment%'), ])[-1] self.assertEqual(last_po_id.partner_id, vendor1) self.assertEqual(last_po_id.order_line.price_unit, 60)
40.88755
10,181
66,777
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from datetime import datetime from unittest.mock import patch from odoo import fields from odoo.tests import Form from odoo.tests.common import TransactionCase, tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT class TestStockValuation(TransactionCase): def setUp(self): super(TestStockValuation, self).setUp() self.supplier_location = self.env.ref('stock.stock_location_suppliers') self.stock_location = self.env.ref('stock.stock_location_stock') self.partner_id = self.env['res.partner'].create({ 'name': 'Wood Corner Partner', 'company_id': self.env.user.company_id.id, }) self.product1 = self.env['product.product'].create({ 'name': 'Large Desk', 'standard_price': 1299.0, 'list_price': 1799.0, # Ignore tax calculations for these tests. 'supplier_taxes_id': False, 'type': 'product', }) Account = self.env['account.account'] self.stock_input_account = Account.create({ 'name': 'Stock Input', 'code': 'StockIn', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'reconcile': True, }) self.stock_output_account = Account.create({ 'name': 'Stock Output', 'code': 'StockOut', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'reconcile': True, }) self.stock_valuation_account = Account.create({ 'name': 'Stock Valuation', 'code': 'Stock Valuation', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, }) self.stock_journal = self.env['account.journal'].create({ 'name': 'Stock Journal', 'code': 'STJTEST', 'type': 'general', }) self.product1.categ_id.write({ 'property_stock_account_input_categ_id': self.stock_input_account.id, 'property_stock_account_output_categ_id': self.stock_output_account.id, 'property_stock_valuation_account_id': self.stock_valuation_account.id, 'property_stock_journal': self.stock_journal.id, }) def test_change_unit_cost_average_1(self): """ Confirm a purchase order and create the associated receipt, change the unit cost of the purchase order before validating the receipt, the value of the received goods should be set according to the last unit cost. """ self.product1.product_tmpl_id.categ_id.property_cost_method = 'average' po1 = self.env['purchase.order'].create({ 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 10.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 100.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po1.button_confirm() picking1 = po1.picking_ids[0] move1 = picking1.move_lines[0] # the unit price of the purchase order line is copied to the in move self.assertEqual(move1.price_unit, 100) # update the unit price on the purchase order line po1.order_line.price_unit = 200 # validate the receipt res_dict = picking1.button_validate() wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save() wizard.process() # the unit price of the valuationlayer used the latest value self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 200) self.assertEqual(self.product1.value_svl, 2000) def test_standard_price_change_1(self): """ Confirm a purchase order and create the associated receipt, change the unit cost of the purchase order and the standard price of the product before validating the receipt, the value of the received goods should be set according to the last standard price. """ self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' # set a standard price self.product1.product_tmpl_id.standard_price = 10 po1 = self.env['purchase.order'].create({ 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 10.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 11.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po1.button_confirm() picking1 = po1.picking_ids[0] move1 = picking1.move_lines[0] # the move's unit price reflects the purchase order line's cost even if it's useless when # the product's cost method is standard self.assertEqual(move1.price_unit, 11) # set a new standard price self.product1.product_tmpl_id.standard_price = 12 # the unit price on the stock move is not directly updated self.assertEqual(move1.price_unit, 11) # validate the receipt res_dict = picking1.button_validate() wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save() wizard.process() # the unit price of the valuation layer used the latest value self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 12) self.assertEqual(self.product1.value_svl, 120) def test_extra_move_fifo_1(self): """ Check that the extra move when over processing a receipt is correctly merged back in the original move. """ self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' po1 = self.env['purchase.order'].create({ 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 10.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 100.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po1.button_confirm() picking1 = po1.picking_ids[0] move1 = picking1.move_lines[0] move1.quantity_done = 15 picking1.button_validate() # there should be only one move self.assertEqual(len(picking1.move_lines), 1) self.assertEqual(move1.price_unit, 100) self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 100) self.assertEqual(move1.product_qty, 15) self.assertEqual(self.product1.value_svl, 1500) def test_backorder_fifo_1(self): """ Check that the backordered move when under processing a receipt correctly keep the price unit of the original move. """ self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' po1 = self.env['purchase.order'].create({ 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 10.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 100.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po1.button_confirm() picking1 = po1.picking_ids[0] move1 = picking1.move_lines[0] move1.quantity_done = 5 res_dict = picking1.button_validate() self.assertEqual(res_dict['res_model'], 'stock.backorder.confirmation') wizard = self.env[(res_dict.get('res_model'))].browse(res_dict.get('res_id')).with_context(res_dict['context']) wizard.process() self.assertEqual(len(picking1.move_lines), 1) self.assertEqual(move1.price_unit, 100) self.assertEqual(move1.product_qty, 5) picking2 = po1.picking_ids.filtered(lambda p: p.backorder_id) move2 = picking2.move_lines[0] self.assertEqual(len(picking2.move_lines), 1) self.assertEqual(move2.price_unit, 100) self.assertEqual(move2.product_qty, 5) @tagged('post_install', '-at_install') class TestStockValuationWithCOA(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.supplier_location = cls.env.ref('stock.stock_location_suppliers') cls.stock_location = cls.env.ref('stock.stock_location_stock') cls.partner_id = cls.env['res.partner'].create({'name': 'Wood Corner Partner'}) cls.product1 = cls.env['product.product'].create({'name': 'Large Desk'}) cls.cat = cls.env['product.category'].create({ 'name': 'cat', }) cls.product1 = cls.env['product.product'].create({ 'name': 'product1', 'type': 'product', 'categ_id': cls.cat.id, }) cls.product1_copy = cls.env['product.product'].create({ 'name': 'product1', 'type': 'product', 'categ_id': cls.cat.id, }) Account = cls.env['account.account'] cls.usd_currency = cls.env.ref('base.USD') cls.eur_currency = cls.env.ref('base.EUR') cls.usd_currency.active = True cls.eur_currency.active = True cls.stock_input_account = Account.create({ 'name': 'Stock Input', 'code': 'StockIn', 'user_type_id': cls.env.ref('account.data_account_type_current_assets').id, 'reconcile': True, }) cls.stock_output_account = Account.create({ 'name': 'Stock Output', 'code': 'StockOut', 'user_type_id': cls.env.ref('account.data_account_type_current_assets').id, 'reconcile': True, }) cls.stock_valuation_account = Account.create({ 'name': 'Stock Valuation', 'code': 'Stock Valuation', 'user_type_id': cls.env.ref('account.data_account_type_current_assets').id, }) cls.price_diff_account = Account.create({ 'name': 'price diff account', 'code': 'price diff account', 'user_type_id': cls.env.ref('account.data_account_type_current_assets').id, }) cls.stock_journal = cls.env['account.journal'].create({ 'name': 'Stock Journal', 'code': 'STJTEST', 'type': 'general', }) cls.product1.categ_id.write({ 'property_valuation': 'real_time', 'property_stock_account_input_categ_id': cls.stock_input_account.id, 'property_stock_account_output_categ_id': cls.stock_output_account.id, 'property_stock_valuation_account_id': cls.stock_valuation_account.id, 'property_stock_journal': cls.stock_journal.id, }) def test_change_currency_rate_average_1(self): """ Confirm a purchase order in another currency and create the associated receipt, change the currency rate, validate the receipt and then check that the value of the received goods is set according to the last currency rate. """ self.env['res.currency.rate'].search([]).unlink() usd_currency = self.env.ref('base.USD') self.env.company.currency_id = usd_currency.id eur_currency = self.env.ref('base.EUR') self.product1.product_tmpl_id.categ_id.property_cost_method = 'average' # default currency is USD, create a purchase order in EUR po1 = self.env['purchase.order'].create({ 'partner_id': self.partner_id.id, 'currency_id': eur_currency.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 10.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 100.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po1.button_confirm() picking1 = po1.picking_ids[0] move1 = picking1.move_lines[0] # convert the price unit in the company currency price_unit_usd = po1.currency_id._convert( po1.order_line.price_unit, po1.company_id.currency_id, self.env.company, fields.Date.today(), round=False) # the unit price of the move is the unit price of the purchase order line converted in # the company's currency self.assertAlmostEqual(move1.price_unit, price_unit_usd, places=2) # change the rate of the currency self.env['res.currency.rate'].create({ 'name': time.strftime('%Y-%m-%d'), 'rate': 2.0, 'currency_id': eur_currency.id, 'company_id': po1.company_id.id, }) eur_currency._compute_current_rate() price_unit_usd_new_rate = po1.currency_id._convert( po1.order_line.price_unit, po1.company_id.currency_id, self.env.company, fields.Date.today(), round=False) # the new price_unit is lower than th initial because of the rate's change self.assertLess(price_unit_usd_new_rate, price_unit_usd) # the unit price on the stock move is not directly updated self.assertAlmostEqual(move1.price_unit, price_unit_usd, places=2) # validate the receipt res_dict = picking1.button_validate() wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save() wizard.process() # the unit price of the valuation layer used the latest value self.assertAlmostEqual(move1.stock_valuation_layer_ids.unit_cost, price_unit_usd_new_rate) self.assertAlmostEqual(self.product1.value_svl, price_unit_usd_new_rate * 10, delta=0.1) def test_fifo_anglosaxon_return(self): self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.property_account_creditor_price_difference = self.price_diff_account # Receive 10@10 ; create the vendor bill po1 = self.env['purchase.order'].create({ 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 10.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 10.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po1.button_confirm() receipt_po1 = po1.picking_ids[0] receipt_po1.move_lines.quantity_done = 10 receipt_po1.button_validate() move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.invoice_date = move_form.date move_form.partner_id = self.partner_id move_form.purchase_id = po1 invoice_po1 = move_form.save() invoice_po1.action_post() # Receive 10@20 ; create the vendor bill po2 = self.env['purchase.order'].create({ 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 10.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 20.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po2.button_confirm() receipt_po2 = po2.picking_ids[0] receipt_po2.move_lines.quantity_done = 10 receipt_po2.button_validate() move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.invoice_date = move_form.date move_form.partner_id = self.partner_id move_form.purchase_id = po2 invoice_po2 = move_form.save() invoice_po2.action_post() # valuation of product1 should be 300 self.assertEqual(self.product1.value_svl, 300) # return the second po stock_return_picking_form = Form(self.env['stock.return.picking'] .with_context(active_ids=receipt_po2.ids, active_id=receipt_po2.ids[0], active_model='stock.picking')) stock_return_picking = stock_return_picking_form.save() stock_return_picking.product_return_moves.quantity = 10 stock_return_picking_action = stock_return_picking.create_returns() return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id']) return_pick.move_lines[0].move_line_ids[0].qty_done = 10 return_pick.button_validate() # valuation of product1 should be 200 as the first items will be sent out self.assertEqual(self.product1.value_svl, 200) # create a credit note for po2 move_form = Form(self.env['account.move'].with_context(default_move_type='in_refund')) move_form.invoice_date = move_form.date move_form.partner_id = self.partner_id move_form.purchase_id = po2 with move_form.invoice_line_ids.edit(0) as line_form: line_form.quantity = 10 creditnote_po2 = move_form.save() creditnote_po2.action_post() # check the anglo saxon entries price_diff_entry = self.env['account.move.line'].search([('account_id', '=', self.price_diff_account.id)]) self.assertEqual(price_diff_entry.credit, 100) def test_anglosaxon_valuation(self): self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.property_account_creditor_price_difference = self.price_diff_account # Create PO po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner_id with po_form.order_line.new() as po_line: po_line.product_id = self.product1 po_line.product_qty = 1 po_line.price_unit = 10.0 order = po_form.save() order.button_confirm() # Receive the goods receipt = order.picking_ids[0] receipt.move_lines.quantity_done = 1 receipt.button_validate() # Create an invoice with a different price move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.invoice_date = move_form.date move_form.partner_id = order.partner_id move_form.purchase_id = order with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 15.0 invoice = move_form.save() invoice.action_post() # Check what was posted in the price difference account price_diff_aml = self.env['account.move.line'].search([('account_id','=', self.price_diff_account.id)]) self.assertEqual(len(price_diff_aml), 1, "Only one line should have been generated in the price difference account.") self.assertAlmostEqual(price_diff_aml.debit, 5, "Price difference should be equal to 5 (15-10)") # Check what was posted in stock input account input_aml = self.env['account.move.line'].search([('account_id','=',self.stock_input_account.id)]) self.assertEqual(len(input_aml), 3, "Only three lines should have been generated in stock input account: one when receiving the product, one when making the invoice.") invoice_amls = input_aml.filtered(lambda l: l.move_id == invoice) picking_aml = input_aml - invoice_amls self.assertAlmostEqual(sum(invoice_amls.mapped('debit')), 15, "Total debit value on stock input account should be equal to the original PO price of the product.") self.assertAlmostEqual(sum(invoice_amls.mapped('credit')), 5, "Total debit value on stock input account should be equal to the original PO price of the product.") self.assertAlmostEqual(sum(picking_aml.mapped('credit')), 10, "Total credit value on stock input account should be equal to the original PO price of the product.") def test_valuation_from_increasing_tax(self): """ Check that a tax without account will increment the stock value. """ tax_with_no_account = self.env['account.tax'].create({ 'name': "Tax with no account", 'amount_type': 'fixed', 'amount': 5, 'sequence': 8, }) self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' # Receive 10@10 ; create the vendor bill po1 = self.env['purchase.order'].create({ 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'taxes_id': [(4, tax_with_no_account.id)], 'product_qty': 10.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 10.0, 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), }), ], }) po1.button_confirm() receipt_po1 = po1.picking_ids[0] receipt_po1.move_lines.quantity_done = 10 receipt_po1.button_validate() # valuation of product1 should be 15 as the tax with no account set # has gone to the stock account, and must be reflected in inventory valuation self.assertEqual(self.product1.value_svl, 150) def test_standard_valuation_multicurrency(self): company = self.env.user.company_id company.anglo_saxon_accounting = True company.currency_id = self.usd_currency date_po = '2019-01-01' self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.property_account_creditor_price_difference = self.price_diff_account self.product1.standard_price = 10 # SetUp currency and rates 1$ = 2 Euros self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", (self.usd_currency.id, company.id)) self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.0, 'currency_id': self.usd_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 2, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) # Create PO po = self.env['purchase.order'].create({ 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 1.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 100.0, # 50$ 'date_planned': date_po, }), ], }) po.button_confirm() # Receive the goods receipt = po.picking_ids[0] receipt.move_lines.quantity_done = 1 receipt.button_validate() # Create a vendor bill inv = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'invoice_date': date_po, 'date': date_po, 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'invoice_line_ids': [(0, 0, { 'name': 'Test', 'price_unit': 100.0, 'product_id': self.product1.id, 'purchase_line_id': po.order_line.id, 'quantity': 1.0, 'account_id': self.stock_input_account.id, })] }) inv.action_post() # Check what was posted in stock input account input_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)]) self.assertEqual(len(input_amls), 3, "Only three lines should have been generated in stock input account: one when receiving the product, one when making the invoice.") invoice_amls = input_amls.filtered(lambda l: l.move_id == inv) picking_aml = input_amls - invoice_amls payable_aml = invoice_amls.filtered(lambda l: l.amount_currency > 0) diff_aml = invoice_amls - payable_aml # check USD self.assertAlmostEqual(payable_aml.debit, 50, "Total debit value should be equal to the original PO price of the product.") self.assertAlmostEqual(picking_aml.credit, 10, "credit value for stock should be equal to the standard price of the product.") self.assertAlmostEqual(diff_aml.credit, 40, "credit value for price difference") # check EUR self.assertAlmostEqual(payable_aml.amount_currency, 100, "Total debit value should be equal to the original PO price of the product.") self.assertAlmostEqual(picking_aml.amount_currency, -20, "credit value for stock should be equal to the standard price of the product.") self.assertAlmostEqual(diff_aml.amount_currency, -80, "credit value for price difference") def test_valuation_multicurecny_with_tax(self): """ Check that a tax without account will increment the stock value. """ company = self.env.user.company_id company.anglo_saxon_accounting = True company.currency_id = self.usd_currency date_po = '2019-01-01' self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.property_account_creditor_price_difference = self.price_diff_account # SetUp currency and rates 1$ = 2Euros self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", (self.usd_currency.id, company.id)) self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.0, 'currency_id': self.usd_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 2, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) tax_with_no_account = self.env['account.tax'].create({ 'name': "Tax with no account", 'amount_type': 'fixed', 'amount': 5, 'sequence': 8, 'price_include': True, }) # Create PO po = self.env['purchase.order'].create({ 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 1.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 100.0, # 50$ 'taxes_id': [(4, tax_with_no_account.id)], 'date_planned': date_po, }), ], }) po.button_confirm() # Receive the goods receipt = po.picking_ids[0] receipt.move_lines.quantity_done = 1 receipt.button_validate() # Create a vendor bill inv = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'invoice_date': date_po, 'date': date_po, 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'invoice_line_ids': [(0, 0, { 'name': 'Test', 'price_unit': 100.0, 'product_id': self.product1.id, 'purchase_line_id': po.order_line.id, 'quantity': 1.0, 'account_id': self.stock_input_account.id, })] }) inv.action_post() # Check what was posted in stock input account input_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)]) self.assertEqual(len(input_amls), 2, "Only two lines should have been generated in stock input account: one when receiving the product, one when making the invoice.") invoice_aml = input_amls.filtered(lambda l: l.move_id == inv) picking_aml = input_amls - invoice_aml # check EUR self.assertAlmostEqual(invoice_aml.amount_currency, 100, "Total debit value should be equal to the original PO price of the product.") self.assertAlmostEqual(picking_aml.amount_currency, -95, "credit value for stock should be equal to the untaxed price of the product.") def test_average_realtime_anglo_saxon_valuation_multicurrency_same_date(self): """ The PO and invoice are in the same foreign currency. The PO is invoiced on the same date as its creation. This shouldn't create a price difference entry. """ company = self.env.user.company_id company.anglo_saxon_accounting = True company.currency_id = self.usd_currency date_po = '2019-01-01' # SetUp product self.product1.product_tmpl_id.cost_method = 'average' self.product1.product_tmpl_id.valuation = 'real_time' self.product1.product_tmpl_id.purchase_method = 'purchase' self.product1.property_account_creditor_price_difference = self.price_diff_account # SetUp currency and rates self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", (self.usd_currency.id, company.id)) self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.0, 'currency_id': self.usd_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.5, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) # Proceed po = self.env['purchase.order'].create({ 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 1.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 100.0, 'date_planned': date_po, }), ], }) po.button_confirm() inv = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'invoice_date': date_po, 'date': date_po, 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'invoice_line_ids': [(0, 0, { 'name': 'Test', 'price_unit': 100.0, 'product_id': self.product1.id, 'purchase_line_id': po.order_line.id, 'quantity': 1.0, 'account_id': self.stock_input_account.id, })] }) inv.action_post() move_lines = inv.line_ids self.assertEqual(len(move_lines), 4) payable_line = move_lines.filtered(lambda l: l.account_id.internal_type == 'payable') self.assertEqual(payable_line.amount_currency, -100.0) self.assertAlmostEqual(payable_line.balance, -66.67) stock_line = move_lines.filtered(lambda l: l.account_id == self.stock_input_account and l.balance > 0) self.assertEqual(stock_line.amount_currency, 100.0) self.assertAlmostEqual(stock_line.balance, 66.67) def test_realtime_anglo_saxon_valuation_multicurrency_different_dates(self): """ The PO and invoice are in the same foreign currency. The PO is invoiced at a later date than its creation. This should create a price difference entry for standard cost method Not for average cost method though, since the PO and invoice have the same currency """ company = self.env.user.company_id company.anglo_saxon_accounting = True company.currency_id = self.usd_currency self.product1.product_tmpl_id.categ_id.property_cost_method = 'average' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' date_po = '2019-01-01' date_invoice = '2019-01-16' # SetUp product Average self.product1.product_tmpl_id.write({ 'purchase_method': 'purchase', 'property_account_creditor_price_difference': self.price_diff_account.id, }) # SetUp product Standard # should have bought at 60 USD # actually invoiced at 70 EUR > 35 USD product_categ_standard = self.cat.copy({ 'property_cost_method': 'standard', 'property_stock_account_input_categ_id': self.stock_input_account.id, 'property_stock_account_output_categ_id': self.stock_output_account.id, 'property_stock_valuation_account_id': self.stock_valuation_account.id, 'property_stock_journal': self.stock_journal.id, }) product_standard = self.product1_copy product_standard.write({ 'categ_id': product_categ_standard.id, 'name': 'Standard Val', 'standard_price': 60, 'property_account_creditor_price_difference': self.price_diff_account.id }) # SetUp currency and rates self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", (self.usd_currency.id, company.id)) self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.0, 'currency_id': self.usd_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.5, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_invoice, 'rate': 2, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) # To allow testing validation of PO def _today(*args, **kwargs): return date_po patchers = [ patch('odoo.fields.Date.context_today', _today), ] for p in patchers: p.start() # Proceed po = self.env['purchase.order'].create({ 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_qty': 1.0, 'product_uom': self.product1.uom_po_id.id, 'price_unit': 100.0, 'date_planned': date_po, }), (0, 0, { 'name': product_standard.name, 'product_id': product_standard.id, 'product_qty': 1.0, 'product_uom': product_standard.uom_po_id.id, 'price_unit': 40.0, 'date_planned': date_po, }), ], }) po.button_confirm() line_product_average = po.order_line.filtered(lambda l: l.product_id == self.product1) line_product_standard = po.order_line.filtered(lambda l: l.product_id == product_standard) inv = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'invoice_date': date_invoice, 'date': date_invoice, 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'invoice_line_ids': [ (0, 0, { 'name': self.product1.name, 'price_subtotal': 100.0, 'price_unit': 100.0, 'product_id': self.product1.id, 'purchase_line_id': line_product_average.id, 'quantity': 1.0, 'account_id': self.stock_input_account.id, }), (0, 0, { 'name': product_standard.name, 'price_subtotal': 70.0, 'price_unit': 70.0, 'product_id': product_standard.id, 'purchase_line_id': line_product_standard.id, 'quantity': 1.0, 'account_id': self.stock_input_account.id, }) ] }) inv.action_post() for p in patchers: p.stop() move_lines = inv.line_ids self.assertEqual(len(move_lines), 5) # Ensure no exchange difference move has been created self.assertTrue(all([not l.reconciled for l in move_lines])) # PAYABLE CHECK payable_line = move_lines.filtered(lambda l: l.account_id.internal_type == 'payable') self.assertEqual(payable_line.amount_currency, -170.0) self.assertAlmostEqual(payable_line.balance, -85.00) # PRODUCTS CHECKS # NO EXCHANGE DIFFERENCE (average) # We ordered for a value of 100 EUR # But by the time we are invoiced for it # the foreign currency appreciated from 1.5 to 2.0 # We still have to pay 100 EUR, which now values at 50 USD product_lines = move_lines.filtered(lambda l: l.product_id == self.product1) # Stock-wise, we have been invoiced 100 EUR, and we ordered 100 EUR # there is no price difference # However, 100 EUR should be converted at the time of the invoice stock_lines = product_lines.filtered(lambda l: l.account_id == self.stock_input_account) self.assertAlmostEqual(sum(stock_lines.mapped('amount_currency')), 100.00) self.assertAlmostEqual(sum(stock_lines.mapped('balance')), 50.00) # PRICE DIFFERENCE (STANDARD) # We ordered a product that should have cost 60 USD (120 EUR) # However, we effectively got invoiced 70 EUR (35 USD) product_lines = move_lines.filtered(lambda l: l.product_id == product_standard) stock_lines = product_lines.filtered(lambda l: l.account_id == self.stock_input_account) self.assertAlmostEqual(sum(stock_lines.mapped('amount_currency')), 120.00) self.assertAlmostEqual(sum(stock_lines.mapped('balance')), 60.00) price_diff_line = product_lines.filtered(lambda l: l.account_id == self.price_diff_account) self.assertEqual(price_diff_line.amount_currency, -50.00) self.assertAlmostEqual(price_diff_line.balance, -25.00) def test_average_realtime_with_delivery_anglo_saxon_valuation_multicurrency_different_dates(self): """ The PO and invoice are in the same foreign currency. The delivery occurs in between PO validation and invoicing The invoice is created at an even different date This should create a price difference entry. """ company = self.env.user.company_id company.anglo_saxon_accounting = True company.currency_id = self.usd_currency self.product1.product_tmpl_id.categ_id.property_cost_method = 'average' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' date_po = '2019-01-01' date_delivery = '2019-01-08' date_invoice = '2019-01-16' product_avg = self.product1_copy product_avg.write({ 'purchase_method': 'purchase', 'name': 'AVG', 'standard_price': 60, 'property_account_creditor_price_difference': self.price_diff_account.id }) # SetUp currency and rates self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", (self.usd_currency.id, company.id)) self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.0, 'currency_id': self.usd_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.5, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_delivery, 'rate': 0.7, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_invoice, 'rate': 2, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) # To allow testing validation of PO and Delivery today = date_po def _today(*args, **kwargs): return datetime.strptime(today, "%Y-%m-%d").date() def _now(*args, **kwargs): return datetime.strptime(today + ' 01:00:00', "%Y-%m-%d %H:%M:%S") patchers = [ patch('odoo.fields.Date.context_today', _today), patch('odoo.fields.Datetime.now', _now), ] for p in patchers: p.start() # Proceed po = self.env['purchase.order'].create({ 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'order_line': [ (0, 0, { 'name': product_avg.name, 'product_id': product_avg.id, 'product_qty': 1.0, 'product_uom': product_avg.uom_po_id.id, 'price_unit': 30.0, 'date_planned': date_po, }) ], }) po.button_confirm() line_product_avg = po.order_line.filtered(lambda l: l.product_id == product_avg) today = date_delivery picking = po.picking_ids (picking.move_lines .filtered(lambda l: l.purchase_line_id == line_product_avg) .write({'quantity_done': 1.0})) picking.button_validate() # 5 Units received at rate 0.7 = 42.86 self.assertAlmostEqual(product_avg.standard_price, 42.86) today = date_invoice inv = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'invoice_date': date_invoice, 'date': date_invoice, 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'invoice_line_ids': [ (0, 0, { 'name': product_avg.name, 'price_unit': 30.0, 'product_id': product_avg.id, 'purchase_line_id': line_product_avg.id, 'quantity': 1.0, 'account_id': self.stock_input_account.id, }) ] }) inv.action_post() for p in patchers: p.stop() move_lines = inv.line_ids self.assertEqual(len(move_lines), 2) # PAYABLE CHECK payable_line = move_lines.filtered(lambda l: l.account_id.internal_type == 'payable') self.assertEqual(payable_line.amount_currency, -30.0) self.assertAlmostEqual(payable_line.balance, -15.00) # PRODUCTS CHECKS # DELIVERY DIFFERENCE (AVERAGE) # We ordered a product at 30 EUR valued at 20 USD # We received it when the exchange rate has appreciated # So, the actualized 20 USD are now 20*1.5/0.7 = 42.86 USD product_lines = move_lines.filtered(lambda l: l.product_id == product_avg) # Although those 42.86 USD are just due to the exchange difference stock_line = product_lines.filtered(lambda l: l.account_id == self.stock_input_account) self.assertEqual(stock_line.journal_id, inv.journal_id) self.assertEqual(stock_line.amount_currency, 30.00) self.assertAlmostEqual(stock_line.balance, 15.00) full_reconcile = stock_line.full_reconcile_id self.assertTrue(full_reconcile.exists()) reconciled_lines = full_reconcile.reconciled_line_ids - stock_line self.assertEqual(len(reconciled_lines), 2) stock_journal_line = reconciled_lines.filtered(lambda l: l.journal_id == self.stock_journal) self.assertEqual(stock_journal_line.amount_currency, -30.00) self.assertAlmostEqual(stock_journal_line.balance, -42.86) exhange_diff_journal = company.currency_exchange_journal_id.exists() exchange_stock_line = reconciled_lines.filtered(lambda l: l.journal_id == exhange_diff_journal) self.assertEqual(exchange_stock_line.amount_currency, 0.00) self.assertAlmostEqual(exchange_stock_line.balance, 27.86) def test_average_realtime_with_two_delivery_anglo_saxon_valuation_multicurrency_different_dates(self): """ The PO and invoice are in the same foreign currency. The deliveries occur at different times and rates The invoice is created at an even different date This should create a price difference entry. """ company = self.env.user.company_id company.anglo_saxon_accounting = True company.currency_id = self.usd_currency exchange_diff_journal = company.currency_exchange_journal_id.exists() date_po = '2019-01-01' date_delivery = '2019-01-08' date_delivery1 = '2019-01-10' date_invoice = '2019-01-16' date_invoice1 = '2019-01-20' self.product1.categ_id.property_valuation = 'real_time' self.product1.categ_id.property_cost_method = 'average' product_avg = self.product1_copy product_avg.write({ 'purchase_method': 'purchase', 'name': 'AVG', 'standard_price': 0, 'property_account_creditor_price_difference': self.price_diff_account.id }) # SetUp currency and rates self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", (self.usd_currency.id, company.id)) self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.0, 'currency_id': self.usd_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_po, 'rate': 1.5, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_delivery, 'rate': 0.7, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_delivery1, 'rate': 0.8, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_invoice, 'rate': 2, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) self.env['res.currency.rate'].create({ 'name': date_invoice1, 'rate': 2.2, 'currency_id': self.eur_currency.id, 'company_id': company.id, }) # To allow testing validation of PO and Delivery today = date_po def _today(*args, **kwargs): return datetime.strptime(today, "%Y-%m-%d").date() def _now(*args, **kwargs): return datetime.strptime(today + ' 01:00:00', "%Y-%m-%d %H:%M:%S") patchers = [ patch('odoo.fields.Date.context_today', _today), patch('odoo.fields.Datetime.now', _now), ] for p in patchers: p.start() # Proceed po = self.env['purchase.order'].create({ 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'date_order': date_po, 'order_line': [ (0, 0, { 'name': product_avg.name, 'product_id': product_avg.id, 'product_qty': 10.0, 'product_uom': product_avg.uom_po_id.id, 'price_unit': 30.0, 'date_planned': date_po, }) ], }) po.button_confirm() line_product_avg = po.order_line.filtered(lambda l: l.product_id == product_avg) today = date_delivery picking = po.picking_ids (picking.move_lines .filtered(lambda l: l.purchase_line_id == line_product_avg) .write({'quantity_done': 5.0})) picking.button_validate() picking._action_done() # Create Backorder # 5 Units received at rate 0.7 = 42.86 self.assertAlmostEqual(product_avg.standard_price, 42.86) today = date_invoice inv = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'invoice_date': date_invoice, 'date': date_invoice, 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'invoice_line_ids': [ (0, 0, { 'name': product_avg.name, 'price_unit': 20.0, 'product_id': product_avg.id, 'purchase_line_id': line_product_avg.id, 'quantity': 5.0, 'account_id': self.stock_input_account.id, }) ] }) inv.action_post() today = date_delivery1 backorder_picking = self.env['stock.picking'].search([('backorder_id', '=', picking.id)]) (backorder_picking.move_lines .filtered(lambda l: l.purchase_line_id == line_product_avg) .write({'quantity_done': 5.0})) backorder_picking.button_validate() # 5 Units received at rate 0.7 (42.86) + 5 Units received at rate 0.8 (37.50) = 40.18 self.assertAlmostEqual(product_avg.standard_price, 40.18) today = date_invoice1 inv1 = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'invoice_date': date_invoice1, 'date': date_invoice1, 'currency_id': self.eur_currency.id, 'partner_id': self.partner_id.id, 'invoice_line_ids': [ (0, 0, { 'name': product_avg.name, 'price_unit': 40.0, 'product_id': product_avg.id, 'purchase_line_id': line_product_avg.id, 'quantity': 5.0, 'account_id': self.stock_input_account.id, }) ] }) inv1.action_post() for p in patchers: p.stop() ########################## # Invoice 0 # ########################## move_lines = inv.line_ids self.assertEqual(len(move_lines), 4) # PAYABLE CHECK payable_line = move_lines.filtered(lambda l: l.account_id.internal_type == 'payable') self.assertEqual(payable_line.amount_currency, -100.0) self.assertAlmostEqual(payable_line.balance, -50.00) # # PRODUCTS CHECKS # DELIVERY DIFFERENCE (AVERAGE) stock_lines = move_lines.filtered(lambda l: l.account_id == self.stock_input_account) self.assertEqual(len(stock_lines), 2) self.assertAlmostEqual(sum(stock_lines.mapped('amount_currency')), 150.00) self.assertAlmostEqual(sum(stock_lines.mapped('balance')), 75.00) price_diff_line = move_lines.filtered(lambda l: l.account_id == self.price_diff_account) self.assertAlmostEqual(price_diff_line.amount_currency, -50.00) self.assertAlmostEqual(price_diff_line.balance, -25.00) full_reconcile = stock_lines.mapped('full_reconcile_id') self.assertTrue(full_reconcile.exists()) reconciled_lines = full_reconcile.reconciled_line_ids - stock_lines self.assertEqual(len(reconciled_lines), 2) stock_journal_line = reconciled_lines.filtered(lambda l: l.journal_id == self.stock_journal) self.assertEqual(stock_journal_line.amount_currency, -150) self.assertAlmostEqual(stock_journal_line.balance, -214.29) exchange_stock_line = reconciled_lines.filtered(lambda l: l.journal_id == exchange_diff_journal) self.assertEqual(exchange_stock_line.amount_currency, 0.00) self.assertAlmostEqual(exchange_stock_line.balance, 139.29) ########################## # Invoice 1 # ########################## move_lines = inv1.line_ids self.assertEqual(len(move_lines), 4) # PAYABLE CHECK payable_line = move_lines.filtered(lambda l: l.account_id.internal_type == 'payable') self.assertEqual(payable_line.amount_currency, -200.0) self.assertAlmostEqual(payable_line.balance, -90.91) # # PRODUCTS CHECKS # DELIVERY DIFFERENCE (AVERAGE) stock_lines = move_lines.filtered(lambda l: l.account_id == self.stock_input_account) self.assertEqual(stock_lines.mapped('journal_id'), inv.journal_id) self.assertAlmostEqual(sum(stock_lines.mapped('amount_currency')), 150.00) self.assertAlmostEqual(sum(stock_lines.mapped('balance')), 68.18) price_diff_line = move_lines.filtered(lambda l: l.account_id == self.price_diff_account) self.assertEqual(price_diff_line.amount_currency, 50.00) self.assertAlmostEqual(price_diff_line.balance, 22.73) full_reconcile = stock_lines.mapped('full_reconcile_id') self.assertTrue(full_reconcile.exists()) reconciled_lines = full_reconcile.reconciled_line_ids - stock_lines self.assertEqual(len(reconciled_lines), 3) stock_journal_line = reconciled_lines.filtered(lambda l: l.journal_id == self.stock_journal) self.assertEqual(stock_journal_line.amount_currency, -150) self.assertAlmostEqual(stock_journal_line.balance, -187.5) exchange_stock_lines = reconciled_lines.filtered(lambda l: l.journal_id == exchange_diff_journal) self.assertAlmostEqual(sum(exchange_stock_lines.mapped('amount_currency')), 0.00) self.assertAlmostEqual(sum(exchange_stock_lines.mapped('balance')), 119.32) def test_anglosaxon_valuation_price_total_diff_discount(self): """ PO: price unit: 110 Inv: price unit: 100 discount: 10 """ self.env.company.anglo_saxon_accounting = True self.product1.categ_id.property_cost_method = 'fifo' self.product1.categ_id.property_valuation = 'real_time' self.product1.property_account_creditor_price_difference = self.price_diff_account # Create PO po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner_id with po_form.order_line.new() as po_line: po_line.product_id = self.product1 po_line.product_qty = 1 po_line.price_unit = 110.0 order = po_form.save() order.button_confirm() # Receive the goods receipt = order.picking_ids[0] receipt.move_lines.quantity_done = 1 receipt.button_validate() # Create an invoice with a different price and a discount invoice_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) invoice_form.invoice_date = invoice_form.date invoice_form.purchase_id = order with invoice_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 100.0 line_form.discount = 10.0 invoice = invoice_form.save() invoice.action_post() # Check what was posted in the price difference account price_diff_aml = self.env['account.move.line'].search([('account_id','=', self.price_diff_account.id)]) self.assertEqual(len(price_diff_aml), 1, "Only one line should have been generated in the price difference account.") self.assertAlmostEqual(price_diff_aml.credit, 20, "Price difference should be equal to 20 (110-90)") # Check what was posted in stock input account input_aml = self.env['account.move.line'].search([('account_id','=', self.stock_input_account.id)]) self.assertEqual(len(input_aml), 3, "Only two lines should have been generated in stock input account: one when receiving the product, two when making the invoice.") self.assertAlmostEqual(sum(input_aml.mapped('debit')), 110, "Total debit value on stock input account should be equal to the original PO price of the product.") self.assertAlmostEqual(sum(input_aml.mapped('credit')), 110, "Total credit value on stock input account should be equal to the original PO price of the product.") def test_anglosaxon_valuation_discount(self): """ PO: price unit: 100 Inv: price unit: 100 discount: 10 """ self.env.company.anglo_saxon_accounting = True self.product1.categ_id.property_cost_method = 'fifo' self.product1.categ_id.property_valuation = 'real_time' self.product1.property_account_creditor_price_difference = self.price_diff_account # Create PO po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner_id with po_form.order_line.new() as po_line: po_line.product_id = self.product1 po_line.product_qty = 1 po_line.price_unit = 100.0 order = po_form.save() order.button_confirm() # Receive the goods receipt = order.picking_ids[0] receipt.move_lines.quantity_done = 1 receipt.button_validate() # Create an invoice with a different price and a discount invoice_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) invoice_form.invoice_date = invoice_form.date invoice_form.purchase_id = order with invoice_form.invoice_line_ids.edit(0) as line_form: line_form.tax_ids.clear() line_form.discount = 10.0 invoice = invoice_form.save() invoice.action_post() # Check what was posted in the price difference account price_diff_aml = self.env['account.move.line'].search([('account_id', '=', self.price_diff_account.id)]) self.assertEqual(len(price_diff_aml), 1, "Only one line should have been generated in the price difference account.") self.assertAlmostEqual(price_diff_aml.credit, 10, "Price difference should be equal to 10 (100-90)") # Check what was posted in stock input account input_aml = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)]) self.assertEqual(len(input_aml), 3, "Three lines generated in stock input account: one when receiving the product, two when making the invoice.") self.assertAlmostEqual(sum(input_aml.mapped('debit')), 100, "Total debit value on stock input account should be equal to the original PO price of the product.") self.assertAlmostEqual(sum(input_aml.mapped('credit')), 100, "Total credit value on stock input account should be equal to the original PO price of the product.") def test_anglosaxon_valuation_price_unit_diff_discount(self): """ PO: price unit: 90 Inv: price unit: 100 discount: 10 """ self.env.company.anglo_saxon_accounting = True self.product1.categ_id.property_cost_method = 'fifo' self.product1.categ_id.property_valuation = 'real_time' self.product1.property_account_creditor_price_difference = self.price_diff_account # Create PO po_form = Form(self.env['purchase.order']) po_form.partner_id = self.partner_id with po_form.order_line.new() as po_line: po_line.product_id = self.product1 po_line.product_qty = 1 po_line.price_unit = 90.0 order = po_form.save() order.button_confirm() # Receive the goods receipt = order.picking_ids[0] receipt.move_lines.quantity_done = 1 receipt.button_validate() # Create an invoice with a different price and a discount invoice_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) invoice_form.invoice_date = invoice_form.date invoice_form.purchase_id = order with invoice_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 100.0 line_form.discount = 10.0 invoice = invoice_form.save() invoice.action_post() # Check if something was posted in the price difference account price_diff_aml = self.env['account.move.line'].search([('account_id','=', self.price_diff_account.id)]) self.assertEqual(len(price_diff_aml), 0, "No line should have been generated in the price difference account.") # Check what was posted in stock input account input_aml = self.env['account.move.line'].search([('account_id','=', self.stock_input_account.id)]) self.assertEqual(len(input_aml), 2, "Only two lines should have been generated in stock input account: one when receiving the product, one when making the invoice.") self.assertAlmostEqual(sum(input_aml.mapped('debit')), 90, "Total debit value on stock input account should be equal to the original PO price of the product.") self.assertAlmostEqual(sum(input_aml.mapped('credit')), 90, "Total credit value on stock input account should be equal to the original PO price of the product.") def test_anglosaxon_valuation_price_unit_diff_avco(self): """ Inv: price unit: 100 """ self.env.company.anglo_saxon_accounting = True self.product1.categ_id.property_cost_method = 'average' self.product1.categ_id.property_valuation = 'real_time' self.product1.categ_id.property_account_creditor_price_difference_categ = self.price_diff_account self.product1.standard_price = 1.01 invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'invoice_date': '2022-03-31', 'partner_id': self.partner_id.id, 'invoice_line_ids': [ (0, 0, {'product_id': self.product1.id, 'quantity': 10.50, 'price_unit': 1.01, 'tax_ids': self.tax_purchase_a.ids}) ] }) invoice.action_post() # Check if something was posted in the price difference account price_diff_aml = invoice.line_ids.filtered(lambda l: l.account_id == self.price_diff_account) self.assertEqual(len(price_diff_aml), 0, "No line should have been generated in the price difference account.") def test_anglosaxon_valuation_price_unit_diff_standard(self): """ Check the price unit difference account is hit with the correct amount """ self.env.ref("product.decimal_price").digits = 6 self.env.company.anglo_saxon_accounting = True self.product1.categ_id.property_cost_method = 'standard' self.product1.categ_id.property_valuation = 'real_time' self.product1.categ_id.property_account_creditor_price_difference_categ = self.price_diff_account self.product1.standard_price = 0.01719 invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'invoice_date': '2022-03-31', 'partner_id': self.partner_id.id, 'invoice_line_ids': [ (0, 0, {'product_id': self.product1.id, 'quantity': 30000, 'price_unit': 0.01782, 'tax_ids': self.tax_purchase_a.ids}) ] }) invoice.action_post() # Check if something was posted in the price difference account price_diff_aml = invoice.line_ids.filtered(lambda l: l.account_id == self.price_diff_account) self.assertEqual(len(price_diff_aml), 1, "A line should have been generated in the price difference account.") self.assertAlmostEqual(price_diff_aml.balance, 18.90)
42.723608
66,777
15,288
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from .common import PurchaseTestCommon class TestMoveCancelPropagation(PurchaseTestCommon): def setUp(self): super(TestMoveCancelPropagation, self).setUp() self.customer = self.env['res.partner'].create({'name': 'abc'}) self.group = self.env['procurement.group'].create({'partner_id': self.customer.id, 'name': 'New Group'}) self.warehouse = self.env.ref('stock.warehouse0') cust_location = self.env.ref('stock.stock_location_customers') seller = self.env['product.supplierinfo'].create({ 'name': self.customer.id, 'price': 100.0, }) product = self.env['product.product'].create({ 'name': 'Geyser', 'type': 'product', 'route_ids': [(4, self.route_mto), (4, self.route_buy)], 'seller_ids': [(6, 0, [seller.id])], }) self.picking_out = self.env['stock.picking'].create({ 'location_id': self.warehouse.out_type_id.default_location_src_id.id, 'location_dest_id': cust_location.id, 'partner_id': self.customer.id, 'group_id': self.group.id, 'picking_type_id': self.ref('stock.picking_type_out'), }) self.move = self.env['stock.move'].create({ 'name': product.name, 'product_id': product.id, 'product_uom_qty': 10, 'product_uom': product.uom_id.id, 'picking_id': self.picking_out.id, 'group_id': self.group.id, 'location_id': self.warehouse.out_type_id.default_location_src_id.id, 'location_dest_id': cust_location.id, 'procure_method': 'make_to_order', }) def test_01_cancel_draft_purchase_order_one_steps(self): """ Check the picking and moves status related PO, When canceling purchase order Ex. 1) Set one steps of receiption and delivery on the warehouse. 2) Create Delivery order with mto move and confirm the order, related RFQ should be generated. 3) Cancel 'draft' purchase order should not cancel < Delivery > """ self.warehouse.write({'delivery_steps': 'ship_only', 'reception_steps': 'one_step'}) self.picking_out.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.move.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.picking_out.action_confirm() # Find PO related to picking. purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.customer.id)]) # Po should be create related picking. self.assertTrue(purchase_order, 'No purchase order created.') # Check status of Purchase Order self.assertEqual(purchase_order.state, 'draft', "Purchase order should be in 'draft' state.") # Cancel Purchase order. purchase_order.button_cancel() # Check the status of picking after canceling po. self.assertNotEqual(self.picking_out.state, 'cancel') def test_02_cancel_confirm_purchase_order_one_steps(self): """ Check the picking and moves status related purchase order, When canceling purchase order after confirming. Ex. 1) Set one steps of receiption and delivery on the warehouse. 2) Create Delivery order with mto move and confirm the order, related RFQ should be generated. 3) Cancel 'confirmed' purchase order, should cancel releted < Receiption > but it should not cancel < Delivery > order. """ self.warehouse.write({'delivery_steps': 'ship_only', 'reception_steps': 'one_step'}) self.picking_out.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.move.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.picking_out.action_confirm() # Find PO related to picking. purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.customer.id)]) # Po should be create related picking. self.assertTrue(purchase_order, 'No purchase order created.') # Check status of Purchase Order self.assertEqual(purchase_order.state, 'draft', "Purchase order should be in 'draft' state.") purchase_order .button_confirm() picking_in = purchase_order.picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.in_type_id) # Cancel Purchase order. purchase_order .button_cancel() # Check the status of picking after canceling po. self.assertEqual(picking_in.state, 'cancel') self.assertNotEqual(self.picking_out.state, 'cancel') def test_03_cancel_draft_purchase_order_two_steps(self): """ Check the picking and moves status related PO, When canceling purchase order in 'draft' state. Ex. 1) Set two steps of receiption and delivery on the warehouse. 2) Create Delivery order with mto move and confirm the order, related RFQ should be generated. 3) Cancel 'draft' purchase order should cancel < Input to Stock> but it should not cancel < PICK, Delivery > """ self.warehouse.write({'delivery_steps': 'pick_ship', 'reception_steps': 'two_steps'}) self.picking_out.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.move.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.picking_out.action_confirm() # Find purchase order related to picking. purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.customer.id)]) # Purchase order should be created for picking. self.assertTrue(purchase_order, 'No purchase order created.') picking_ids = self.env['stock.picking'].search([('group_id', '=', self.group.id)]) internal = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.int_type_id and r.group_id.id == self.group.id) pick = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.pick_type_id and r.group_id.id == self.group.id) # Check status of Purchase Order self.assertEqual(purchase_order.state, 'draft', "Purchase order should be in 'draft' state.") # Cancel Purchase order. purchase_order.button_cancel() # Check the status of picking after canceling po. for res in internal: self.assertEqual(res.state, 'cancel') self.assertNotEqual(pick.state, 'cancel') self.assertNotEqual(self.picking_out.state, 'cancel') def test_04_cancel_confirm_purchase_order_two_steps(self): """ Check the picking and moves status related PO, When canceling purchase order Ex. 1) Set 2 steps of receiption and delivery on the warehouse. 2) Create Delivery order with mto move and confirm the order, related RFQ should be generated. 3) Cancel 'comfirm' purchase order should cancel releted < Receiption Picking IN, INT> not < PICK, SHIP > """ self.warehouse.write({'delivery_steps': 'pick_ship', 'reception_steps': 'two_steps'}) self.picking_out.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.move.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.picking_out.action_confirm() # Find PO related to picking. purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.customer.id)]) # Po should be create related picking. self.assertTrue(purchase_order, 'purchase order is created.') picking_ids = self.env['stock.picking'].search([('group_id', '=', self.group.id)]) internal = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.int_type_id) pick = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.pick_type_id) # Check status of Purchase Order self.assertEqual(purchase_order.state, 'draft', "Purchase order should be in 'draft' state.") purchase_order.button_confirm() picking_in = purchase_order.picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.in_type_id) # Cancel Purchase order. purchase_order.button_cancel() # Check the status of picking after canceling po. self.assertEqual(picking_in.state, 'cancel') for res in internal: self.assertEqual(res.state, 'cancel') self.assertNotEqual(pick.state, 'cancel') self.assertNotEqual(self.picking_out.state, 'cancel') def test_05_cancel_draft_purchase_order_three_steps(self): """ Check the picking and moves status related PO, When canceling purchase order Ex. 1) Set 3 steps of receiption and delivery on the warehouse. 2) Create Delivery order with mto move and confirm the order, related RFQ should be generated. 3) Cancel 'draft' purchase order should cancel releted < Receiption Picking IN> not < PICK, PACK, SHIP > """ self.warehouse.write({'delivery_steps': 'pick_pack_ship', 'reception_steps': 'three_steps'}) self.picking_out.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.move.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.picking_out.action_confirm() # Find PO related to picking. purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.customer.id)]) # Po should be create related picking. self.assertTrue(purchase_order, 'No purchase order created.') picking_ids = self.env['stock.picking'].search([('group_id', '=', self.group.id)]) internal = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.int_type_id) pick = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.pick_type_id) pack = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.pack_type_id) # Check status of Purchase Order self.assertEqual(purchase_order.state, 'draft', "Purchase order should be in 'draft' state.") # Cancel Purchase order. purchase_order.button_cancel() # Check the status of picking after canceling po. for res in internal: self.assertEqual(res.state, 'cancel') self.assertNotEqual(pick.state, 'cancel') self.assertNotEqual(pack.state, 'cancel') self.assertNotEqual(self.picking_out.state, 'cancel') def test_06_cancel_confirm_purchase_order_three_steps(self): """ Check the picking and moves status related PO, When canceling purchase order Ex. 1) Set 3 steps of receiption and delivery on the warehouse. 2) Create Delivery order with mto move and confirm the order, related RFQ should be generated. 3) Cancel 'comfirm' purchase order should cancel releted < Receiption Picking IN, INT> not < PICK, PACK, SHIP > """ self.warehouse.write({'delivery_steps': 'pick_pack_ship', 'reception_steps': 'three_steps'}) self.picking_out.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.move.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) self.picking_out.action_confirm() # Find PO related to picking. purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.customer.id)]) # Po should be create related picking. self.assertTrue(purchase_order, 'No purchase order created.') picking_ids = self.env['stock.picking'].search([('group_id', '=', self.group.id)]) internal = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.int_type_id) pick = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.pick_type_id) pack = picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.pack_type_id) # Check status of Purchase Order self.assertEqual(purchase_order.state, 'draft', "Purchase order should be in 'draft' state.") purchase_order.button_confirm() picking_in = purchase_order.picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse.in_type_id) # Cancel Purchase order. purchase_order.button_cancel() # Check the status of picking after canceling po. self.assertEqual(picking_in.state, 'cancel') for res in internal: self.assertEqual(res.state, 'cancel') self.assertNotEqual(pick.state, 'cancel') self.assertNotEqual(pack.state, 'cancel') self.assertNotEqual(self.picking_out.state, 'cancel') def test_cancel_move_lines_operation(self): """Check for done and cancelled moves. Ensure that the RFQ cancellation will not impact the delivery state if it's already cancelled. """ stock_location = self.env.ref('stock.stock_location_stock') customer_location = self.env.ref('stock.stock_location_customers') picking_type_out = self.env.ref('stock.picking_type_out') partner = self.env['res.partner'].create({ 'name': 'Steve' }) seller = self.env['product.supplierinfo'].create({ 'name': partner.id, 'price': 10.0, }) product_car = self.env['product.product'].create({ 'name': 'Car', 'type': 'product', 'route_ids': [(4, self.ref('stock.route_warehouse0_mto')), (4, self.ref('purchase_stock.route_warehouse0_buy'))], 'seller_ids': [(6, 0, [seller.id])], 'categ_id': self.env.ref('product.product_category_all').id, }) customer_picking = self.env['stock.picking'].create({ 'location_id': stock_location.id, 'location_dest_id': customer_location.id, 'partner_id': partner.id, 'picking_type_id': picking_type_out.id, }) customer_move = self.env['stock.move'].create({ 'name': 'move out', 'location_id': stock_location.id, 'location_dest_id': customer_location.id, 'product_id': product_car.id, 'product_uom': product_car.uom_id.id, 'product_uom_qty': 10.0, 'procure_method': 'make_to_order', 'picking_id': customer_picking.id, }) customer_move._action_confirm() purchase_order = self.env['purchase.order'].search([('partner_id', '=', partner.id)]) customer_move._action_cancel() self.assertEqual(customer_move.state, 'cancel', 'Move should be cancelled') purchase_order.button_cancel() self.assertEqual(customer_move.state, 'cancel', 'State of cancelled and done moves should not change.')
52.177474
15,288
709
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class StockReplenishmentInfo(models.TransientModel): _inherit = 'stock.replenishment.info' _description = 'Stock supplier replenishment information' supplierinfo_id = fields.Many2one(related='orderpoint_id.supplier_id') supplierinfo_ids = fields.Many2many( 'product.supplierinfo', compute='_compute_supplierinfo_ids', store=True) @api.depends('orderpoint_id') def _compute_supplierinfo_ids(self): for replenishment_info in self: replenishment_info.supplierinfo_ids = replenishment_info.product_id.seller_ids
37.315789
709
32,910
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from markupsafe import Markup from dateutil.relativedelta import relativedelta from odoo import api, fields, models, SUPERUSER_ID, _ from odoo.tools.float_utils import float_compare, float_is_zero, float_round from odoo.exceptions import UserError from odoo.addons.purchase.models.purchase import PurchaseOrder as Purchase class PurchaseOrder(models.Model): _inherit = 'purchase.order' @api.model def _default_picking_type(self): return self._get_picking_type(self.env.context.get('company_id') or self.env.company.id) incoterm_id = fields.Many2one('account.incoterms', 'Incoterm', states={'done': [('readonly', True)]}, help="International Commercial Terms are a series of predefined commercial terms used in international transactions.") incoming_picking_count = fields.Integer("Incoming Shipment count", compute='_compute_incoming_picking_count') picking_ids = fields.Many2many('stock.picking', compute='_compute_picking_ids', string='Receptions', copy=False, store=True) picking_type_id = fields.Many2one('stock.picking.type', 'Deliver To', states=Purchase.READONLY_STATES, required=True, default=_default_picking_type, domain="['|', ('warehouse_id', '=', False), ('warehouse_id.company_id', '=', company_id)]", help="This will determine operation type of incoming shipment") default_location_dest_id_usage = fields.Selection(related='picking_type_id.default_location_dest_id.usage', string='Destination Location Type', help="Technical field used to display the Drop Ship Address", readonly=True) group_id = fields.Many2one('procurement.group', string="Procurement Group", copy=False) is_shipped = fields.Boolean(compute="_compute_is_shipped") effective_date = fields.Datetime("Effective Date", compute='_compute_effective_date', store=True, copy=False, help="Completion date of the first receipt order.") on_time_rate = fields.Float(related='partner_id.on_time_rate', compute_sudo=False) @api.depends('order_line.move_ids.picking_id') def _compute_picking_ids(self): for order in self: order.picking_ids = order.order_line.move_ids.picking_id @api.depends('picking_ids') def _compute_incoming_picking_count(self): for order in self: order.incoming_picking_count = len(order.picking_ids) @api.depends('picking_ids.date_done') def _compute_effective_date(self): for order in self: pickings = order.picking_ids.filtered(lambda x: x.state == 'done' and x.location_dest_id.usage != 'supplier' and x.date_done) order.effective_date = min(pickings.mapped('date_done'), default=False) @api.depends('picking_ids', 'picking_ids.state') def _compute_is_shipped(self): for order in self: if order.picking_ids and all(x.state in ['done', 'cancel'] for x in order.picking_ids): order.is_shipped = True else: order.is_shipped = False @api.onchange('picking_type_id') def _onchange_picking_type_id(self): if self.picking_type_id.default_location_dest_id.usage != 'customer': self.dest_address_id = False @api.onchange('company_id') def _onchange_company_id(self): p_type = self.picking_type_id if not(p_type and p_type.code == 'incoming' and (p_type.warehouse_id.company_id == self.company_id or not p_type.warehouse_id)): self.picking_type_id = self._get_picking_type(self.company_id.id) # -------------------------------------------------- # CRUD # -------------------------------------------------- def write(self, vals): if vals.get('order_line') and self.state == 'purchase': for order in self: pre_order_line_qty = {order_line: order_line.product_qty for order_line in order.mapped('order_line')} res = super(PurchaseOrder, self).write(vals) if vals.get('order_line') and self.state == 'purchase': for order in self: to_log = {} for order_line in order.order_line: if pre_order_line_qty.get(order_line, False) and float_compare(pre_order_line_qty[order_line], order_line.product_qty, precision_rounding=order_line.product_uom.rounding) > 0: to_log[order_line] = (order_line.product_qty, pre_order_line_qty[order_line]) if to_log: order._log_decrease_ordered_quantity(to_log) return res # -------------------------------------------------- # Actions # -------------------------------------------------- def button_approve(self, force=False): result = super(PurchaseOrder, self).button_approve(force=force) self._create_picking() return result def button_cancel(self): for order in self: for move in order.order_line.mapped('move_ids'): if move.state == 'done': raise UserError(_('Unable to cancel purchase order %s as some receptions have already been done.') % (order.name)) # If the product is MTO, change the procure_method of the closest move to purchase to MTS. # The purpose is to link the po that the user will manually generate to the existing moves's chain. if order.state in ('draft', 'sent', 'to approve', 'purchase'): for order_line in order.order_line: order_line.move_ids._action_cancel() if order_line.move_dest_ids: move_dest_ids = order_line.move_dest_ids if order_line.propagate_cancel: move_dest_ids._action_cancel() else: move_dest_ids.write({'procure_method': 'make_to_stock'}) move_dest_ids._recompute_state() for pick in order.picking_ids.filtered(lambda r: r.state != 'cancel'): pick.action_cancel() order.order_line.write({'move_dest_ids':[(5,0,0)]}) return super(PurchaseOrder, self).button_cancel() def action_view_picking(self): return self._get_action_view_picking(self.picking_ids) def _get_action_view_picking(self, pickings): """ This function returns an action that display existing picking orders of given purchase order ids. When only one found, show the picking immediately. """ self.ensure_one() result = self.env["ir.actions.actions"]._for_xml_id('stock.action_picking_tree_all') # override the context to get rid of the default filtering on operation type result['context'] = {'default_partner_id': self.partner_id.id, 'default_origin': self.name, 'default_picking_type_id': self.picking_type_id.id} # choose the view_mode accordingly if not pickings or len(pickings) > 1: result['domain'] = [('id', 'in', pickings.ids)] elif len(pickings) == 1: res = self.env.ref('stock.view_picking_form', False) form_view = [(res and res.id or False, 'form')] result['views'] = form_view + [(state, view) for state, view in result.get('views', []) if view != 'form'] result['res_id'] = pickings.id return result def _prepare_invoice(self): invoice_vals = super()._prepare_invoice() invoice_vals['invoice_incoterm_id'] = self.incoterm_id.id return invoice_vals # -------------------------------------------------- # Business methods # -------------------------------------------------- def _log_decrease_ordered_quantity(self, purchase_order_lines_quantities): def _keys_in_sorted(move): """ sort by picking and the responsible for the product the move. """ return (move.picking_id.id, move.product_id.responsible_id.id) def _keys_in_groupby(move): """ group by picking and the responsible for the product the move. """ return (move.picking_id, move.product_id.responsible_id) def _render_note_exception_quantity_po(order_exceptions): order_line_ids = self.env['purchase.order.line'].browse([order_line.id for order in order_exceptions.values() for order_line in order[0]]) purchase_order_ids = order_line_ids.mapped('order_id') move_ids = self.env['stock.move'].concat(*rendering_context.keys()) impacted_pickings = move_ids.mapped('picking_id')._get_impacted_pickings(move_ids) - move_ids.mapped('picking_id') values = { 'purchase_order_ids': purchase_order_ids, 'order_exceptions': order_exceptions.values(), 'impacted_pickings': impacted_pickings, } return self.env.ref('purchase_stock.exception_on_po')._render(values=values) documents = self.env['stock.picking']._log_activity_get_documents(purchase_order_lines_quantities, 'move_ids', 'DOWN', _keys_in_sorted, _keys_in_groupby) filtered_documents = {} for (parent, responsible), rendering_context in documents.items(): if parent._name == 'stock.picking': if parent.state in ['cancel', 'done']: continue filtered_documents[(parent, responsible)] = rendering_context self.env['stock.picking']._log_activity(_render_note_exception_quantity_po, filtered_documents) def _get_destination_location(self): self.ensure_one() if self.dest_address_id: return self.dest_address_id.property_stock_customer.id return self.picking_type_id.default_location_dest_id.id @api.model def _get_picking_type(self, company_id): picking_type = self.env['stock.picking.type'].search([('code', '=', 'incoming'), ('warehouse_id.company_id', '=', company_id)]) if not picking_type: picking_type = self.env['stock.picking.type'].search([('code', '=', 'incoming'), ('warehouse_id', '=', False)]) return picking_type[:1] def _prepare_picking(self): if not self.group_id: self.group_id = self.group_id.create({ 'name': self.name, 'partner_id': self.partner_id.id }) if not self.partner_id.property_stock_supplier.id: raise UserError(_("You must set a Vendor Location for this partner %s", self.partner_id.name)) return { 'picking_type_id': self.picking_type_id.id, 'partner_id': self.partner_id.id, 'user_id': False, 'date': self.date_order, 'origin': self.name, 'location_dest_id': self._get_destination_location(), 'location_id': self.partner_id.property_stock_supplier.id, 'company_id': self.company_id.id, } def _create_picking(self): StockPicking = self.env['stock.picking'] for order in self.filtered(lambda po: po.state in ('purchase', 'done')): if any(product.type in ['product', 'consu'] for product in order.order_line.product_id): order = order.with_company(order.company_id) pickings = order.picking_ids.filtered(lambda x: x.state not in ('done', 'cancel')) if not pickings: res = order._prepare_picking() picking = StockPicking.with_user(SUPERUSER_ID).create(res) else: picking = pickings[0] moves = order.order_line._create_stock_moves(picking) moves = moves.filtered(lambda x: x.state not in ('done', 'cancel'))._action_confirm() seq = 0 for move in sorted(moves, key=lambda move: move.date): seq += 5 move.sequence = seq moves._action_assign() picking.message_post_with_view('mail.message_origin_link', values={'self': picking, 'origin': order}, subtype_id=self.env.ref('mail.mt_note').id) return True def _add_picking_info(self, activity): """Helper method to add picking info to the Date Updated activity when vender updates date_planned of the po lines. """ validated_picking = self.picking_ids.filtered(lambda p: p.state == 'done') if validated_picking: message = _("Those dates couldn’t be modified accordingly on the receipt %s which had already been validated.", validated_picking[0].name) elif not self.picking_ids: message = _("Corresponding receipt not found.") else: message = _("Those dates have been updated accordingly on the receipt %s.", self.picking_ids[0].name) activity.note += Markup('<p>{}</p>').format(message) def _create_update_date_activity(self, updated_dates): activity = super()._create_update_date_activity(updated_dates) self._add_picking_info(activity) def _update_update_date_activity(self, updated_dates, activity): # remove old picking info to update it note_lines = activity.note.split('<p>') note_lines.pop() activity.note = Markup('<p>').join(note_lines) super()._update_update_date_activity(updated_dates, activity) self._add_picking_info(activity) @api.model def _get_orders_to_remind(self): """When auto sending reminder mails, don't send for purchase order with validated receipts.""" return super()._get_orders_to_remind().filtered(lambda p: not p.effective_date) class PurchaseOrderLine(models.Model): _inherit = 'purchase.order.line' qty_received_method = fields.Selection(selection_add=[('stock_moves', 'Stock Moves')]) move_ids = fields.One2many('stock.move', 'purchase_line_id', string='Reservation', readonly=True, copy=False) orderpoint_id = fields.Many2one('stock.warehouse.orderpoint', 'Orderpoint', copy=False, index=True) move_dest_ids = fields.One2many('stock.move', 'created_purchase_line_id', 'Downstream Moves') product_description_variants = fields.Char('Custom Description') propagate_cancel = fields.Boolean('Propagate cancellation', default=True) forecasted_issue = fields.Boolean(compute='_compute_forecasted_issue') def _compute_qty_received_method(self): super(PurchaseOrderLine, self)._compute_qty_received_method() for line in self.filtered(lambda l: not l.display_type): if line.product_id.type in ['consu', 'product']: line.qty_received_method = 'stock_moves' def _get_po_line_moves(self): self.ensure_one() moves = self.move_ids.filtered(lambda m: m.product_id == self.product_id) if self._context.get('accrual_entry_date'): moves = moves.filtered(lambda r: fields.Date.context_today(r, r.date) <= self._context['accrual_entry_date']) return moves @api.depends('move_ids.state', 'move_ids.product_uom_qty', 'move_ids.product_uom') def _compute_qty_received(self): from_stock_lines = self.filtered(lambda order_line: order_line.qty_received_method == 'stock_moves') super(PurchaseOrderLine, self - from_stock_lines)._compute_qty_received() for line in self: if line.qty_received_method == 'stock_moves': total = 0.0 # In case of a BOM in kit, the products delivered do not correspond to the products in # the PO. Therefore, we can skip them since they will be handled later on. for move in line._get_po_line_moves(): if move.state == 'done': if move._is_purchase_return(): if move.to_refund: total -= move.product_uom._compute_quantity(move.product_uom_qty, line.product_uom, rounding_method='HALF-UP') elif move.origin_returned_move_id and move.origin_returned_move_id._is_dropshipped() and not move._is_dropshipped_returned(): # Edge case: the dropship is returned to the stock, no to the supplier. # In this case, the received quantity on the PO is set although we didn't # receive the product physically in our stock. To avoid counting the # quantity twice, we do nothing. pass else: total += move.product_uom._compute_quantity(move.product_uom_qty, line.product_uom, rounding_method='HALF-UP') line._track_qty_received(total) line.qty_received = total @api.depends('product_uom_qty', 'date_planned') def _compute_forecasted_issue(self): for line in self: warehouse = line.order_id.picking_type_id.warehouse_id line.forecasted_issue = False if line.product_id: virtual_available = line.product_id.with_context(warehouse=warehouse.id, to_date=line.date_planned).virtual_available if line.state == 'draft': virtual_available += line.product_uom_qty if virtual_available < 0: line.forecasted_issue = True @api.model_create_multi def create(self, vals_list): lines = super(PurchaseOrderLine, self).create(vals_list) lines.filtered(lambda l: l.order_id.state == 'purchase')._create_or_update_picking() return lines def write(self, values): if values.get('date_planned'): new_date = fields.Datetime.to_datetime(values['date_planned']) self.filtered(lambda l: not l.display_type)._update_move_date_deadline(new_date) lines = self.filtered(lambda l: l.order_id.state == 'purchase') if 'product_packaging_id' in values: self.move_ids.filtered( lambda m: m.state not in ['cancel', 'done'] ).product_packaging_id = values['product_packaging_id'] previous_product_uom_qty = {line.id: line.product_uom_qty for line in lines} previous_product_qty = {line.id: line.product_qty for line in lines} result = super(PurchaseOrderLine, self).write(values) if 'price_unit' in values: for line in lines: # Avoid updating kit components' stock.move moves = line.move_ids.filtered(lambda s: s.state not in ('cancel', 'done') and s.product_id == line.product_id) moves.write({'price_unit': line._get_stock_move_price_unit()}) if 'product_qty' in values: lines = lines.filtered(lambda l: float_compare(previous_product_qty[l.id], l.product_qty, precision_rounding=l.product_uom.rounding) != 0) lines.with_context(previous_product_qty=previous_product_uom_qty)._create_or_update_picking() return result def action_product_forecast_report(self): self.ensure_one() action = self.product_id.action_product_forecast_report() action['context'] = { 'active_id': self.product_id.id, 'active_model': 'product.product', 'move_to_match_ids': self.move_ids.filtered(lambda m: m.product_id == self.product_id).ids, 'purchase_line_to_match_id': self.id, } warehouse = self.order_id.picking_type_id.warehouse_id if warehouse: action['context']['warehouse'] = warehouse.id return action def unlink(self): self.move_ids._action_cancel() ppg_cancel_lines = self.filtered(lambda line: line.propagate_cancel) ppg_cancel_lines.move_dest_ids._action_cancel() not_ppg_cancel_lines = self.filtered(lambda line: not line.propagate_cancel) not_ppg_cancel_lines.move_dest_ids.write({'procure_method': 'make_to_stock'}) not_ppg_cancel_lines.move_dest_ids._recompute_state() return super().unlink() # -------------------------------------------------- # Business methods # -------------------------------------------------- def _update_move_date_deadline(self, new_date): """ Updates corresponding move picking line deadline dates that are not yet completed. """ moves_to_update = self.move_ids.filtered(lambda m: m.state not in ('done', 'cancel')) if not moves_to_update: moves_to_update = self.move_dest_ids.filtered(lambda m: m.state not in ('done', 'cancel')) for move in moves_to_update: move.date_deadline = new_date def _create_or_update_picking(self): for line in self: if line.product_id and line.product_id.type in ('product', 'consu'): # Prevent decreasing below received quantity if float_compare(line.product_qty, line.qty_received, line.product_uom.rounding) < 0: raise UserError(_('You cannot decrease the ordered quantity below the received quantity.\n' 'Create a return first.')) if float_compare(line.product_qty, line.qty_invoiced, line.product_uom.rounding) == -1: # If the quantity is now below the invoiced quantity, create an activity on the vendor bill # inviting the user to create a refund. line.invoice_lines[0].move_id.activity_schedule( 'mail.mail_activity_data_warning', note=_('The quantities on your purchase order indicate less than billed. You should ask for a refund.')) # If the user increased quantity of existing line or created a new line pickings = line.order_id.picking_ids.filtered(lambda x: x.state not in ('done', 'cancel') and x.location_dest_id.usage in ('internal', 'transit', 'customer')) picking = pickings and pickings[0] or False if not picking: res = line.order_id._prepare_picking() picking = self.env['stock.picking'].create(res) moves = line._create_stock_moves(picking) moves._action_confirm()._action_assign() def _get_stock_move_price_unit(self): self.ensure_one() order = self.order_id price_unit = self.price_unit price_unit_prec = self.env['decimal.precision'].precision_get('Product Price') if self.taxes_id: qty = self.product_qty or 1 price_unit = self.taxes_id.with_context(round=False).compute_all( price_unit, currency=self.order_id.currency_id, quantity=qty, product=self.product_id, partner=self.order_id.partner_id )['total_void'] price_unit = float_round(price_unit / qty, precision_digits=price_unit_prec) if self.product_uom.id != self.product_id.uom_id.id: price_unit *= self.product_uom.factor / self.product_id.uom_id.factor if order.currency_id != order.company_id.currency_id: price_unit = order.currency_id._convert( price_unit, order.company_id.currency_id, self.company_id, self.date_order or fields.Date.today(), round=False) return price_unit def _prepare_stock_moves(self, picking): """ Prepare the stock moves data for one order line. This function returns a list of dictionary ready to be used in stock.move's create() """ self.ensure_one() res = [] if self.product_id.type not in ['product', 'consu']: return res price_unit = self._get_stock_move_price_unit() qty = self._get_qty_procurement() move_dests = self.move_dest_ids if not move_dests: move_dests = self.move_ids.move_dest_ids.filtered(lambda m: m.state != 'cancel' and not m.location_dest_id.usage == 'supplier') if not move_dests: qty_to_attach = 0 qty_to_push = self.product_qty - qty else: move_dests_initial_demand = self.product_id.uom_id._compute_quantity( sum(move_dests.filtered(lambda m: m.state != 'cancel' and not m.location_dest_id.usage == 'supplier').mapped('product_qty')), self.product_uom, rounding_method='HALF-UP') qty_to_attach = move_dests_initial_demand - qty qty_to_push = self.product_qty - move_dests_initial_demand if float_compare(qty_to_attach, 0.0, precision_rounding=self.product_uom.rounding) > 0: product_uom_qty, product_uom = self.product_uom._adjust_uom_quantities(qty_to_attach, self.product_id.uom_id) res.append(self._prepare_stock_move_vals(picking, price_unit, product_uom_qty, product_uom)) if not float_is_zero(qty_to_push, precision_rounding=self.product_uom.rounding): product_uom_qty, product_uom = self.product_uom._adjust_uom_quantities(qty_to_push, self.product_id.uom_id) extra_move_vals = self._prepare_stock_move_vals(picking, price_unit, product_uom_qty, product_uom) extra_move_vals['move_dest_ids'] = False # don't attach res.append(extra_move_vals) return res def _get_qty_procurement(self): self.ensure_one() qty = 0.0 outgoing_moves, incoming_moves = self._get_outgoing_incoming_moves() for move in outgoing_moves: qty -= move.product_uom._compute_quantity(move.product_uom_qty, self.product_uom, rounding_method='HALF-UP') for move in incoming_moves: qty += move.product_uom._compute_quantity(move.product_uom_qty, self.product_uom, rounding_method='HALF-UP') return qty def _check_orderpoint_picking_type(self): warehouse_loc = self.order_id.picking_type_id.warehouse_id.view_location_id dest_loc = self.move_dest_ids.location_id or self.orderpoint_id.location_id if warehouse_loc and dest_loc and dest_loc.warehouse_id and not warehouse_loc.parent_path in dest_loc[0].parent_path: raise UserError(_('For the product %s, the warehouse of the operation type (%s) is inconsistent with the location (%s) of the reordering rule (%s). Change the operation type or cancel the request for quotation.', self.product_id.display_name, self.order_id.picking_type_id.display_name, self.orderpoint_id.location_id.display_name, self.orderpoint_id.display_name)) def _prepare_stock_move_vals(self, picking, price_unit, product_uom_qty, product_uom): self.ensure_one() self._check_orderpoint_picking_type() product = self.product_id.with_context(lang=self.order_id.dest_address_id.lang or self.env.user.lang) date_planned = self.date_planned or self.order_id.date_planned return { # truncate to 2000 to avoid triggering index limit error # TODO: remove index in master? 'name': (self.product_id.display_name or '')[:2000], 'product_id': self.product_id.id, 'date': date_planned, 'date_deadline': date_planned, 'location_id': self.order_id.partner_id.property_stock_supplier.id, 'location_dest_id': (self.orderpoint_id and not (self.move_ids | self.move_dest_ids)) and self.orderpoint_id.location_id.id or self.order_id._get_destination_location(), 'picking_id': picking.id, 'partner_id': self.order_id.dest_address_id.id, 'move_dest_ids': [(4, x) for x in self.move_dest_ids.ids], 'state': 'draft', 'purchase_line_id': self.id, 'company_id': self.order_id.company_id.id, 'price_unit': price_unit, 'picking_type_id': self.order_id.picking_type_id.id, 'group_id': self.order_id.group_id.id, 'origin': self.order_id.name, 'description_picking': product.description_pickingin or self.name, 'propagate_cancel': self.propagate_cancel, 'warehouse_id': self.order_id.picking_type_id.warehouse_id.id, 'product_uom_qty': product_uom_qty, 'product_uom': product_uom.id, 'product_packaging_id': self.product_packaging_id.id, 'sequence': self.sequence, } @api.model def _prepare_purchase_order_line_from_procurement(self, product_id, product_qty, product_uom, company_id, values, po): line_description = '' if values.get('product_description_variants'): line_description = values['product_description_variants'] supplier = values.get('supplier') res = self._prepare_purchase_order_line(product_id, product_qty, product_uom, company_id, supplier, po) # We need to keep the vendor name set in _prepare_purchase_order_line. To avoid redundancy # in the line name, we add the line_description only if different from the product name. # This way, we shoud not lose any valuable information. if line_description and product_id.name != line_description: res['name'] += '\n' + line_description res['date_planned'] = values.get('date_planned') res['move_dest_ids'] = [(4, x.id) for x in values.get('move_dest_ids', [])] res['orderpoint_id'] = values.get('orderpoint_id', False) and values.get('orderpoint_id').id res['propagate_cancel'] = values.get('propagate_cancel') res['product_description_variants'] = values.get('product_description_variants') return res def _create_stock_moves(self, picking): values = [] for line in self.filtered(lambda l: not l.display_type): for val in line._prepare_stock_moves(picking): values.append(val) line.move_dest_ids.created_purchase_line_id = False return self.env['stock.move'].create(values) def _find_candidate(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values): """ Return the record in self where the procument with values passed as args can be merged. If it returns an empty record then a new line will be created. """ description_picking = '' if values.get('product_description_variants'): description_picking = values['product_description_variants'] lines = self.filtered( lambda l: l.propagate_cancel == values['propagate_cancel'] and (l.orderpoint_id == values['orderpoint_id'] if values['orderpoint_id'] and not values['move_dest_ids'] else True) ) # In case 'product_description_variants' is in the values, we also filter on the PO line # name. This way, we can merge lines with the same description. To do so, we need the # product name in the context of the PO partner. if lines and values.get('product_description_variants'): partner = self.mapped('order_id.partner_id')[:1] product_lang = product_id.with_context( lang=partner.lang, partner_id=partner.id, ) name = product_lang.display_name if product_lang.description_purchase: name += '\n' + product_lang.description_purchase lines = lines.filtered(lambda l: l.name == name + '\n' + description_picking) if lines: return lines[0] return lines and lines[0] or self.env['purchase.order.line'] def _get_outgoing_incoming_moves(self): outgoing_moves = self.env['stock.move'] incoming_moves = self.env['stock.move'] for move in self.move_ids.filtered(lambda r: r.state != 'cancel' and not r.scrapped and self.product_id == r.product_id): if move.location_dest_id.usage == "supplier" and move.to_refund: outgoing_moves |= move elif move.location_dest_id.usage != "supplier": if not move.origin_returned_move_id or (move.origin_returned_move_id and move.to_refund): incoming_moves |= move return outgoing_moves, incoming_moves def _update_date_planned(self, updated_date): move_to_update = self.move_ids.filtered(lambda m: m.state not in ['done', 'cancel']) if not self.move_ids or move_to_update: # Only change the date if there is no move done or none super()._update_date_planned(updated_date) if move_to_update: self._update_move_date_deadline(updated_date) @api.model def _update_qty_received_method(self): """Update qty_received_method for old PO before install this module.""" self.search(['!', ('state', 'in', ['purchase', 'done'])])._compute_qty_received_method()
53.508943
32,908
17,848
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.tools.float_utils import float_round, float_is_zero from odoo.exceptions import UserError from odoo.osv.expression import AND from dateutil.relativedelta import relativedelta class StockPicking(models.Model): _inherit = 'stock.picking' purchase_id = fields.Many2one('purchase.order', related='move_lines.purchase_line_id.order_id', string="Purchase Orders", readonly=True) class StockMove(models.Model): _inherit = 'stock.move' purchase_line_id = fields.Many2one('purchase.order.line', 'Purchase Order Line', ondelete='set null', index=True, readonly=True) created_purchase_line_id = fields.Many2one('purchase.order.line', 'Created Purchase Order Line', ondelete='set null', readonly=True, copy=False, index=True) @api.model def _prepare_merge_moves_distinct_fields(self): distinct_fields = super(StockMove, self)._prepare_merge_moves_distinct_fields() distinct_fields += ['purchase_line_id', 'created_purchase_line_id'] return distinct_fields @api.model def _prepare_merge_negative_moves_excluded_distinct_fields(self): return super()._prepare_merge_negative_moves_excluded_distinct_fields() + ['created_purchase_line_id'] def _get_price_unit(self): """ Returns the unit price for the move""" self.ensure_one() if not self.origin_returned_move_id and self.purchase_line_id and self.product_id.id == self.purchase_line_id.product_id.id: price_unit_prec = self.env['decimal.precision'].precision_get('Product Price') line = self.purchase_line_id order = line.order_id price_unit = line.price_unit if line.taxes_id: qty = line.product_qty or 1 price_unit = line.taxes_id.with_context(round=False).compute_all(price_unit, currency=line.order_id.currency_id, quantity=qty)['total_void'] price_unit = float_round(price_unit / qty, precision_digits=price_unit_prec) if line.product_uom.id != line.product_id.uom_id.id: price_unit *= line.product_uom.factor / line.product_id.uom_id.factor if order.currency_id != order.company_id.currency_id: # The date must be today, and not the date of the move since the move move is still # in assigned state. However, the move date is the scheduled date until move is # done, then date of actual move processing. See: # https://github.com/odoo/odoo/blob/2f789b6863407e63f90b3a2d4cc3be09815f7002/addons/stock/models/stock_move.py#L36 price_unit = order.currency_id._convert( price_unit, order.company_id.currency_id, order.company_id, fields.Date.context_today(self), round=False) return price_unit return super(StockMove, self)._get_price_unit() def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id, description): """ Overridden from stock_account to support amount_currency on valuation lines generated from po """ self.ensure_one() rslt = super(StockMove, self)._generate_valuation_lines_data(partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id, description) if self.purchase_line_id: purchase_currency = self.purchase_line_id.currency_id if purchase_currency != self.company_id.currency_id: if(self.purchase_line_id.product_id.cost_method == 'standard'): purchase_price_unit = self.purchase_line_id.product_id.cost_currency_id._convert( self.purchase_line_id.product_id.standard_price, purchase_currency, self.company_id, self.date, round=False, ) else: # Do not use price_unit since we want the price tax excluded. And by the way, qty # is in the UOM of the product, not the UOM of the PO line. purchase_price_unit = ( self.purchase_line_id.price_subtotal / self.purchase_line_id.product_uom_qty if self.purchase_line_id.product_uom_qty else self.purchase_line_id.price_unit ) currency_move_valuation = purchase_currency.round(purchase_price_unit * abs(qty)) rslt['credit_line_vals']['amount_currency'] = rslt['credit_line_vals']['credit'] and -currency_move_valuation or currency_move_valuation rslt['credit_line_vals']['currency_id'] = purchase_currency.id rslt['debit_line_vals']['amount_currency'] = rslt['debit_line_vals']['credit'] and -currency_move_valuation or currency_move_valuation rslt['debit_line_vals']['currency_id'] = purchase_currency.id return rslt def _prepare_extra_move_vals(self, qty): vals = super(StockMove, self)._prepare_extra_move_vals(qty) vals['purchase_line_id'] = self.purchase_line_id.id return vals def _prepare_move_split_vals(self, uom_qty): vals = super(StockMove, self)._prepare_move_split_vals(uom_qty) vals['purchase_line_id'] = self.purchase_line_id.id return vals def _clean_merged(self): super(StockMove, self)._clean_merged() self.write({'created_purchase_line_id': False}) def _get_upstream_documents_and_responsibles(self, visited): if self.created_purchase_line_id and self.created_purchase_line_id.state not in ('done', 'cancel') \ and (self.created_purchase_line_id.state != 'draft' or self._context.get('include_draft_documents')): return [(self.created_purchase_line_id.order_id, self.created_purchase_line_id.order_id.user_id, visited)] elif self.purchase_line_id and self.purchase_line_id.state not in ('done', 'cancel'): return[(self.purchase_line_id.order_id, self.purchase_line_id.order_id.user_id, visited)] else: return super(StockMove, self)._get_upstream_documents_and_responsibles(visited) def _get_related_invoices(self): """ Overridden to return the vendor bills related to this stock move. """ rslt = super(StockMove, self)._get_related_invoices() rslt += self.mapped('picking_id.purchase_id.invoice_ids').filtered(lambda x: x.state == 'posted') return rslt def _get_source_document(self): res = super()._get_source_document() return self.purchase_line_id.order_id or res def _get_valuation_price_and_qty(self, related_aml, to_curr): valuation_price_unit_total = 0 valuation_total_qty = 0 for val_stock_move in self: # In case val_stock_move is a return move, its valuation entries have been made with the # currency rate corresponding to the original stock move valuation_date = val_stock_move.origin_returned_move_id.date or val_stock_move.date svl = val_stock_move.with_context(active_test=False).mapped('stock_valuation_layer_ids').filtered( lambda l: l.quantity) layers_qty = sum(svl.mapped('quantity')) layers_values = sum(svl.mapped('value')) valuation_price_unit_total += related_aml.company_currency_id._convert( layers_values, to_curr, related_aml.company_id, valuation_date, round=False, ) valuation_total_qty += layers_qty if float_is_zero(valuation_total_qty, precision_rounding=related_aml.product_uom_id.rounding or related_aml.product_id.uom_id.rounding): raise UserError( _('Odoo is not able to generate the anglo saxon entries. The total valuation of %s is zero.') % related_aml.product_id.display_name) return valuation_price_unit_total, valuation_total_qty def _is_purchase_return(self): self.ensure_one() return self.location_dest_id.usage == "supplier" or ( self.location_dest_id.usage == "internal" and self.location_id.usage != "supplier" and self.warehouse_id and self.location_dest_id not in self.env["stock.location"].search([("id", "child_of", self.warehouse_id.view_location_id.id)]) ) class StockWarehouse(models.Model): _inherit = 'stock.warehouse' buy_to_resupply = fields.Boolean('Buy to Resupply', default=True, help="When products are bought, they can be delivered to this warehouse") buy_pull_id = fields.Many2one('stock.rule', 'Buy rule') def _get_global_route_rules_values(self): rules = super(StockWarehouse, self)._get_global_route_rules_values() location_id = self.in_type_id.default_location_dest_id rules.update({ 'buy_pull_id': { 'depends': ['reception_steps', 'buy_to_resupply'], 'create_values': { 'action': 'buy', 'picking_type_id': self.in_type_id.id, 'group_propagation_option': 'none', 'company_id': self.company_id.id, 'route_id': self._find_global_route('purchase_stock.route_warehouse0_buy', _('Buy')).id, 'propagate_cancel': self.reception_steps != 'one_step', }, 'update_values': { 'active': self.buy_to_resupply, 'name': self._format_rulename(location_id, False, 'Buy'), 'location_id': location_id.id, 'propagate_cancel': self.reception_steps != 'one_step', } } }) return rules def _get_all_routes(self): routes = super(StockWarehouse, self)._get_all_routes() routes |= self.filtered(lambda self: self.buy_to_resupply and self.buy_pull_id and self.buy_pull_id.route_id).mapped('buy_pull_id').mapped('route_id') return routes def get_rules_dict(self): result = super(StockWarehouse, self).get_rules_dict() for warehouse in self: result[warehouse.id].update(warehouse._get_receive_rules_dict()) return result def _get_routes_values(self): routes = super(StockWarehouse, self)._get_routes_values() routes.update(self._get_receive_routes_values('buy_to_resupply')) return routes def _update_name_and_code(self, name=False, code=False): res = super(StockWarehouse, self)._update_name_and_code(name, code) warehouse = self[0] #change the buy stock rule name if warehouse.buy_pull_id and name: warehouse.buy_pull_id.write({'name': warehouse.buy_pull_id.name.replace(warehouse.name, name, 1)}) return res class ReturnPicking(models.TransientModel): _inherit = "stock.return.picking" def _prepare_move_default_values(self, return_line, new_picking): vals = super(ReturnPicking, self)._prepare_move_default_values(return_line, new_picking) vals['purchase_line_id'] = return_line.move_id.purchase_line_id.id return vals class Orderpoint(models.Model): _inherit = "stock.warehouse.orderpoint" show_supplier = fields.Boolean('Show supplier column', compute='_compute_show_suppplier') supplier_id = fields.Many2one( 'product.supplierinfo', string='Product Supplier', check_company=True, domain="['|', ('product_id', '=', product_id), '&', ('product_id', '=', False), ('product_tmpl_id', '=', product_tmpl_id)]") vendor_id = fields.Many2one(related='supplier_id.name', string="Vendor", store=True) @api.depends('product_id.purchase_order_line_ids', 'product_id.purchase_order_line_ids.state') def _compute_qty(self): """ Extend to add more depends values """ return super()._compute_qty() @api.depends('supplier_id') def _compute_lead_days(self): return super()._compute_lead_days() @api.depends('route_id') def _compute_show_suppplier(self): buy_route = [] for res in self.env['stock.rule'].search_read([('action', '=', 'buy')], ['route_id']): buy_route.append(res['route_id'][0]) for orderpoint in self: orderpoint.show_supplier = orderpoint.route_id.id in buy_route def action_view_purchase(self): """ This function returns an action that display existing purchase orders of given orderpoint. """ result = self.env['ir.actions.act_window']._for_xml_id('purchase.purchase_rfq') # Remvove the context since the action basically display RFQ and not PO. result['context'] = {} order_line_ids = self.env['purchase.order.line'].search([('orderpoint_id', '=', self.id)]) purchase_ids = order_line_ids.mapped('order_id') result['domain'] = "[('id','in',%s)]" % (purchase_ids.ids) return result def _get_lead_days_values(self): values = super()._get_lead_days_values() if self.supplier_id: values['supplierinfo'] = self.supplier_id return values def _get_replenishment_order_notification(self): self.ensure_one() domain = [('orderpoint_id', 'in', self.ids)] if self.env.context.get('written_after'): domain = AND([domain, [('write_date', '>', self.env.context.get('written_after'))]]) order = self.env['purchase.order.line'].search(domain, limit=1).order_id if order: action = self.env.ref('purchase.action_rfq_form') return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'title': _('The following replenishment order has been generated'), 'message': '%s', 'links': [{ 'label': order.display_name, 'url': f'#action={action.id}&id={order.id}&model=purchase.order', }], 'sticky': False, } } return super()._get_replenishment_order_notification() def _prepare_procurement_values(self, date=False, group=False): values = super()._prepare_procurement_values(date=date, group=group) values['supplierinfo_id'] = self.supplier_id return values def _quantity_in_progress(self): res = super()._quantity_in_progress() qty_by_product_location, dummy = self.product_id._get_quantity_in_progress(self.location_id.ids) for orderpoint in self: product_qty = qty_by_product_location.get((orderpoint.product_id.id, orderpoint.location_id.id), 0.0) product_uom_qty = orderpoint.product_id.uom_id._compute_quantity(product_qty, orderpoint.product_uom, round=False) res[orderpoint.id] += product_uom_qty return res def _set_default_route_id(self): route_id = self.env['stock.rule'].search([ ('action', '=', 'buy') ]).route_id orderpoint_wh_supplier = self.filtered(lambda o: o.product_id.seller_ids) if route_id and orderpoint_wh_supplier: orderpoint_wh_supplier.route_id = route_id[0].id return super()._set_default_route_id() def _get_orderpoint_procurement_date(self): date = super()._get_orderpoint_procurement_date() if any(rule.action == 'buy' for rule in self.rule_ids): date -= relativedelta(days=self.company_id.po_lead) return date class ProductionLot(models.Model): _inherit = 'stock.production.lot' purchase_order_ids = fields.Many2many('purchase.order', string="Purchase Orders", compute='_compute_purchase_order_ids', readonly=True, store=False) purchase_order_count = fields.Integer('Purchase order count', compute='_compute_purchase_order_ids') @api.depends('name') def _compute_purchase_order_ids(self): for lot in self: stock_moves = self.env['stock.move.line'].search([ ('lot_id', '=', lot.id), ('state', '=', 'done') ]).mapped('move_id') stock_moves = stock_moves.search([('id', 'in', stock_moves.ids)]).filtered( lambda move: move.picking_id.location_id.usage == 'supplier' and move.state == 'done') lot.purchase_order_ids = stock_moves.mapped('purchase_line_id.order_id') lot.purchase_order_count = len(lot.purchase_order_ids) def action_view_po(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("purchase.purchase_form_action") action['domain'] = [('id', 'in', self.mapped('purchase_order_ids.id'))] action['context'] = dict(self._context, create=False) return action class ProcurementGroup(models.Model): _inherit = 'procurement.group' @api.model def run(self, procurements, raise_user_error=True): wh_by_comp = dict() for procurement in procurements: routes = procurement.values.get('route_ids') if routes and any(r.action == 'buy' for r in routes.rule_ids): company = procurement.company_id if company not in wh_by_comp: wh_by_comp[company] = self.env['stock.warehouse'].search([('company_id', '=', company.id)]) wh = wh_by_comp[company] procurement.values['route_ids'] |= wh.reception_route_id return super().run(procurements, raise_user_error=raise_user_error)
49.303867
17,848