diff --git a/purchase_by_sale_history/tests/test_purchase_by_sale_history.py b/purchase_by_sale_history/tests/test_purchase_by_sale_history.py index 3152bef9..08c68337 100644 --- a/purchase_by_sale_history/tests/test_purchase_by_sale_history.py +++ b/purchase_by_sale_history/tests/test_purchase_by_sale_history.py @@ -6,6 +6,12 @@ from datetime import datetime, timedelta class TestPurchaseBySaleHistory(common.TransactionCase): def test_00_wizard(self): + wh1 = self.env.ref('stock.warehouse0') + wh2 = self.env['stock.warehouse'].create({ + 'name': 'WH2', + 'code': 'twh2', + }) + sale_partner = self.env.ref('base.res_partner_2') purchase_partner = self.env['res.partner'].create({ 'name': 'Purchase Partner', @@ -74,12 +80,13 @@ class TestPurchaseBySaleHistory(common.TransactionCase): 'history_start': history_start, 'history_end': history_end, 'procure_days': days, + 'history_warehouse_ids': [(4, wh1.id, None)], }) self.assertEqual(wiz.history_days, days) wiz.action_confirm() - self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 3.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 3.0 + 3.0) # 3 from Sales History, 3 from Demand (from the sale) self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) - self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 3.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 3.0 + 3.0) # Make additional sales history... sale_date = fields.Datetime.to_string(datetime.now() - timedelta(days=15)) @@ -96,9 +103,29 @@ class TestPurchaseBySaleHistory(common.TransactionCase): }).action_confirm() wiz.action_confirm() - self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 6.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 6.0 + 6.0) self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) - self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 6.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 6.0 + 6.0) + + # Make additional sales history in other warehouse + sale_date = fields.Datetime.to_string(datetime.now() - timedelta(days=15)) + self.env['sale.order'].create({ + 'partner_id': sale_partner.id, + 'date_order': sale_date, + 'confirmation_date': sale_date, + 'picking_policy': 'direct', + 'warehouse_id': wh2.id, + 'order_line': [ + (0, 0, {'product_id': product11.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product12.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product2.id, 'product_uom_qty': 3.0}), + ], + }).action_confirm() + + wiz.action_confirm() + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 6.0 + 6.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 6.0 + 6.0) # Make additional sales history that should NOT be counted... sale_date = fields.Datetime.to_string(datetime.now() - timedelta(days=61)) @@ -115,19 +142,39 @@ class TestPurchaseBySaleHistory(common.TransactionCase): }).action_confirm() wiz.action_confirm() - self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 6.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 6.0 + 9.0) self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) - self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 6.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 6.0 + 9.0) # Test that the wizard will only use the existing PO line products now that we have lines. po1.order_line.filtered(lambda l: l.product_id == product2).unlink() wiz.action_confirm() - self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 6.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 6.0 + 9.0) self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 0.0) # Plan for 1/2 the days of inventory wiz.procure_days = days / 2.0 wiz.action_confirm() - self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 6.0 / 2.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 3.0 + 9.0) + # Cause Inventory on existing product to make sure we don't order it. + adjust_product11 = self.env['stock.inventory'].create({ + 'name': 'Product11', + 'location_id': wh1.lot_stock_id.id, + 'product_id': product11.id, + 'filter': 'product', + }) + adjust_product11.action_start() + adjust_product11.line_ids.create({ + 'inventory_id': adjust_product11.id, + 'product_id': product11.id, + 'product_qty': 100.0, + 'location_id': wh1.lot_stock_id.id, + }) + adjust_product11.action_done() + + wiz.action_confirm() + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 0.0) # Because we have so much in stock now. + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 0.0) diff --git a/purchase_by_sale_history/wizard/purchase_by_sale_history.py b/purchase_by_sale_history/wizard/purchase_by_sale_history.py index fb1e6d30..2e9c91ae 100644 --- a/purchase_by_sale_history/wizard/purchase_by_sale_history.py +++ b/purchase_by_sale_history/wizard/purchase_by_sale_history.py @@ -16,6 +16,11 @@ class PurchaseBySaleHistory(models.TransientModel): 'and then multiplied by the days you wish to procure for.') product_count = fields.Integer(string='Product Count', compute='_compute_product_count', help='Products on the PO or that the Vendor provides.') + history_warehouse_ids = fields.Many2many('stock.warehouse', string='Warehouses', + help='Sales are calculated by these warehouses. ' + 'Current Inventory is summed from these warehouses. ' + 'If it is left blank then all warehouses and inventory ' + 'will be considered.') @api.multi @api.depends('history_start', 'history_end') @@ -54,18 +59,48 @@ class PurchaseBySaleHistory(models.TransientModel): return [r[0] for r in rows if r[0]] def _sale_history(self, product_ids): - self.env.cr.execute("""SELECT product_id, sum(product_uom_qty) - FROM sale_report - WHERE date BETWEEN %s AND %s AND product_id IN %s - GROUP BY 1""", (self.history_start, self.history_end, tuple(product_ids))) + p_ids = tuple(product_ids) + if self.history_warehouse_ids: + wh_ids = tuple(self.history_warehouse_ids.ids) + self.env.cr.execute("""SELECT product_id, sum(product_uom_qty) + FROM sale_report + WHERE date BETWEEN %s AND %s AND product_id IN %s AND warehouse_id IN %s + GROUP BY 1""", + (self.history_start, self.history_end, p_ids, wh_ids)) + else: + self.env.cr.execute("""SELECT product_id, sum(product_uom_qty) + FROM sale_report + WHERE date BETWEEN %s AND %s AND product_id IN %s + GROUP BY 1""", + (self.history_start, self.history_end, p_ids)) return self.env.cr.fetchall() - def _apply_history(self, history): + def _apply_history_product(self, product, history): + qty = ceil(history['sold_qty'] * self.procure_days / self.history_days) + history['buy_qty'] = max((0.0, qty - product.virtual_available)) + + def _apply_history(self, history, product_ids): line_model = self.env['purchase.order.line'] updated_lines = line_model.browse() - for pid, sold_qty in history: + + # Collect stock to consider against the sales demand. + product_model = self.env['product.product'] + if self.history_warehouse_ids: + product_model = self.env['product.product']\ + .with_context({'location': [wh.lot_stock_id.id for wh in self.history_warehouse_ids]}) + products = product_model.browse(product_ids) + + #product_available_stock = {p.id: p.virtual_available for p in products} + history_dict = {pid: {'sold_qty': sold_qty} for pid, sold_qty in history} + for p in products: + if p.id not in history_dict: + history_dict[p.id] = {'sold_qty': 0.0} + self._apply_history_product(p, history_dict[p.id]) + + for pid, history in history_dict.items(): # TODO: Should convert from Sale UOM to Purchase UOM - qty = ceil(sold_qty * self.procure_days / self.history_days) + qty = history.get('buy_qty', 0.0) + # Find line that already exists on PO line = self.purchase_id.order_line.filtered(lambda l: l.product_id.id == pid) if line: @@ -95,6 +130,6 @@ class PurchaseBySaleHistory(models.TransientModel): self.ensure_one() history_product_ids = self._history_product_ids() history = self._sale_history(history_product_ids) - self._apply_history(history) + self._apply_history(history, history_product_ids) diff --git a/purchase_by_sale_history/wizard/purchase_by_sale_history_views.xml b/purchase_by_sale_history/wizard/purchase_by_sale_history_views.xml index 2841283e..41b2b3b3 100644 --- a/purchase_by_sale_history/wizard/purchase_by_sale_history_views.xml +++ b/purchase_by_sale_history/wizard/purchase_by_sale_history_views.xml @@ -13,6 +13,7 @@ + diff --git a/purchase_by_sale_history_mrp/__init__.py b/purchase_by_sale_history_mrp/__init__.py new file mode 100755 index 00000000..40272379 --- /dev/null +++ b/purchase_by_sale_history_mrp/__init__.py @@ -0,0 +1 @@ +from . import wizard diff --git a/purchase_by_sale_history_mrp/__manifest__.py b/purchase_by_sale_history_mrp/__manifest__.py new file mode 100755 index 00000000..711bda72 --- /dev/null +++ b/purchase_by_sale_history_mrp/__manifest__.py @@ -0,0 +1,20 @@ +{ + 'name': 'Purchase by Sale History MRP', + 'author': 'Hibou Corp. ', + 'version': '11.0.1.0.0', + 'category': 'Purchases', + 'sequence': 95, + 'summary': 'Buy Raw materials based on sales from Finished products.', + 'description': """ +Buy Raw materials based on sales from Finished products. + """, + 'website': 'https://hibou.io/', + 'depends': [ + 'purchase_by_sale_history', + 'mrp', + ], + 'data': [ + ], + 'installable': True, + 'application': False, +} diff --git a/purchase_by_sale_history_mrp/tests/__init__.py b/purchase_by_sale_history_mrp/tests/__init__.py new file mode 100644 index 00000000..6cc4addf --- /dev/null +++ b/purchase_by_sale_history_mrp/tests/__init__.py @@ -0,0 +1 @@ +from . import test_purchase_by_sale_history diff --git a/purchase_by_sale_history_mrp/tests/test_purchase_by_sale_history.py b/purchase_by_sale_history_mrp/tests/test_purchase_by_sale_history.py new file mode 100644 index 00000000..74e6a810 --- /dev/null +++ b/purchase_by_sale_history_mrp/tests/test_purchase_by_sale_history.py @@ -0,0 +1,203 @@ +from odoo.addons.purchase_by_sale_history.tests import test_purchase_by_sale_history +from odoo import fields +from datetime import datetime, timedelta +import logging + +_logger = logging.getLogger(__name__) + + +class MTestPurchaseBySaleHistoryMRP(test_purchase_by_sale_history.TestPurchaseBySaleHistory): + + def test_00_wizard(self): + wh1 = self.env.ref('stock.warehouse0') + wh2 = self.env['stock.warehouse'].create({ + 'name': 'WH2', + 'code': 'twh2', + }) + + sale_partner = self.env.ref('base.res_partner_2') + purchase_partner = self.env['res.partner'].create({ + 'name': 'Purchase Partner', + }) + + product11 = self.env['product.product'].create({ + 'name': 'Product 1', + 'type': 'product', + }) + product12 = self.env['product.product'].create({ + 'name': 'Product 1.1', + 'type': 'product', + 'product_tmpl_id': product11.product_tmpl_id.id, + }) + product2 = self.env['product.product'].create({ + 'name': 'Product 2', + 'type': 'product', + }) + + po1 = self.env['purchase.order'].create({ + 'partner_id': purchase_partner.id, + }) + + product_raw = self.env['product.product'].create({ + 'name': 'Product Raw', + 'type': 'product', + }) + _logger.warn('product_raw: ' + str(product_raw)) + + product11_bom = self.env['mrp.bom'].create({ + 'product_tmpl_id': product11.product_tmpl_id.id, + 'product_qty': 1.0, + 'product_uom_id': product11.uom_id.id, + 'bom_line_ids': [(0, 0, { + 'product_id': product_raw.id, + 'product_qty': 2.0, + 'product_uom_id': product_raw.uom_id.id, + })] + }) + + # Create initial wizard, it won't apply to any products because the PO is empty, and the vendor + # doesn't supply any products yet. + wiz = self.env['purchase.sale.history.make'].create({ + 'purchase_id': po1.id, + }) + + self.assertEqual(wiz.product_count, 0.0, 'There shouldn\'t be any products for this vendor yet.') + + # Assign vendor to products created earlier. + self.env['product.supplierinfo'].create({ + 'name': purchase_partner.id, + 'product_tmpl_id': product_raw.product_tmpl_id.id, + 'product_id': product_raw.id, + }) + self.env['product.supplierinfo'].create({ + 'name': purchase_partner.id, + 'product_tmpl_id': product2.product_tmpl_id.id, + }) + # New wizard picks up the correct number of products supplied by this vendor. + wiz = self.env['purchase.sale.history.make'].create({ + 'purchase_id': po1.id, + }) + self.assertEqual(wiz.product_count, 2) + + # Make some sales history... + sale_date = fields.Datetime.to_string(datetime.now() - timedelta(days=30)) + self.env['sale.order'].create({ + 'partner_id': sale_partner.id, + 'date_order': sale_date, + 'confirmation_date': sale_date, + 'picking_policy': 'direct', + 'order_line': [ + (0, 0, {'product_id': product11.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product12.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product2.id, 'product_uom_qty': 3.0}), + ], + }).action_confirm() + + days = 60 + history_start = fields.Date.to_string(datetime.now() - timedelta(days=days)) + history_end = fields.Date.today() + wiz.write({ + 'history_start': history_start, + 'history_end': history_end, + 'procure_days': days, + 'history_warehouse_ids': [(4, wh1.id, None)], + }) + self.assertEqual(wiz.history_days, days) + wiz.action_confirm() + self.assertTrue(po1.order_line.filtered(lambda l: l.product_id == product_raw)) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product_raw).product_qty, 24.0) # x + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 3.0 + 3.0) + + # Make additional sales history... + sale_date = fields.Datetime.to_string(datetime.now() - timedelta(days=15)) + self.env['sale.order'].create({ + 'partner_id': sale_partner.id, + 'date_order': sale_date, + 'confirmation_date': sale_date, + 'picking_policy': 'direct', + 'order_line': [ + (0, 0, {'product_id': product11.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product12.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product2.id, 'product_uom_qty': 3.0}), + ], + }).action_confirm() + + wiz.action_confirm() + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product_raw).product_qty, 48.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 6.0 + 6.0) + + # Make additional sales history in other warehouse + sale_date = fields.Datetime.to_string(datetime.now() - timedelta(days=15)) + self.env['sale.order'].create({ + 'partner_id': sale_partner.id, + 'date_order': sale_date, + 'confirmation_date': sale_date, + 'picking_policy': 'direct', + 'warehouse_id': wh2.id, + 'order_line': [ + (0, 0, {'product_id': product11.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product12.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product2.id, 'product_uom_qty': 3.0}), + ], + }).action_confirm() + + wiz.action_confirm() + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product_raw).product_qty, 48.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 6.0 + 6.0) + + # Make additional sales history that should NOT be counted... + sale_date = fields.Datetime.to_string(datetime.now() - timedelta(days=61)) + self.env['sale.order'].create({ + 'partner_id': sale_partner.id, + 'date_order': sale_date, + 'confirmation_date': sale_date, + 'picking_policy': 'direct', + 'order_line': [ + (0, 0, {'product_id': product11.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product12.id, 'product_uom_qty': 3.0}), + (0, 0, {'product_id': product2.id, 'product_uom_qty': 3.0}), + ], + }).action_confirm() + + wiz.action_confirm() + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product_raw).product_qty, 60.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 6.0 + 9.0) + + # Test that the wizard will only use the existing PO line products now that we have lines. + po1.order_line.filtered(lambda l: l.product_id == product2).unlink() + + # Plan for 1/2 the days of inventory + wiz.procure_days = days / 2.0 + wiz.action_confirm() + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product_raw).product_qty, 48.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 0.0) + + # Cause Inventory on existing product to make sure we don't order it. + adjust_product11 = self.env['stock.inventory'].create({ + 'name': 'Product11', + 'location_id': wh1.lot_stock_id.id, + 'product_id': product11.id, + 'filter': 'product', + }) + adjust_product11.action_start() + adjust_product11.line_ids.create({ + 'inventory_id': adjust_product11.id, + 'product_id': product11.id, + 'product_qty': 100.0, + 'location_id': wh1.lot_stock_id.id, + }) + adjust_product11.action_done() + + wiz.action_confirm() + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product_raw).product_qty, 24.0) # No longer have needs on product11 but we still have them for product12 + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product11).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product12).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 0.0) diff --git a/purchase_by_sale_history_mrp/wizard/__init__.py b/purchase_by_sale_history_mrp/wizard/__init__.py new file mode 100644 index 00000000..bbdff949 --- /dev/null +++ b/purchase_by_sale_history_mrp/wizard/__init__.py @@ -0,0 +1 @@ +from . import purchase_by_sale_history diff --git a/purchase_by_sale_history_mrp/wizard/purchase_by_sale_history.py b/purchase_by_sale_history_mrp/wizard/purchase_by_sale_history.py new file mode 100644 index 00000000..b6f877b5 --- /dev/null +++ b/purchase_by_sale_history_mrp/wizard/purchase_by_sale_history.py @@ -0,0 +1,60 @@ +from odoo import api, fields, models +from odoo.exceptions import UserError + + +class PurchaseBySaleHistory(models.TransientModel): + _inherit = 'purchase.sale.history.make' + + def _apply_history_product(self, product, history): + # Override to recursively collect sales and forcast for products produced by this product. + bom_line_model = self.env['mrp.bom.line'] + product_model = self.env['product.product'] + if self.history_warehouse_ids: + product_model = self.env['product.product'] \ + .with_context({'location': [wh.lot_stock_id.id for wh in self.history_warehouse_ids]}) + visited_product_ids = set() + + def bom_parent_product_ids(product): + if product.id in visited_product_ids: + # Cycle detected + return 0.0 + visited_product_ids.add(product.id) + + bom_lines = bom_line_model.search([('product_id', '=', product.id), ('bom_id.active', '=', True)]) + if not bom_lines: + # Recursive Basecase + return 0.0 + + product_ids = set() + for line in bom_lines: + product_ids |= bom_parent_product_ids_line(line) + product_ids_dict = {} + for pid, ratio in product_ids: + if pid in product_ids_dict: + raise UserError('You cannot have two identical finished goods being created from different ratios.') + product_ids_dict[pid] = {'ratio': ratio} + + history = self._sale_history(product_ids_dict.keys()) + products = product_model.browse(product_ids_dict.keys()) + + for pid, sold_qty in history: + product_ids_dict[pid]['sold_qty'] = sold_qty + for p in products: + qty = product_ids_dict[p.id].get('sold_qty', 0.0) * self.procure_days / self.history_days + product_ids_dict[p.id]['buy_qty'] = max((0.0, qty - p.virtual_available)) + product_ids_dict[p.id]['buy_qty'] += bom_parent_product_ids(p) + product_ids_dict[p.id]['buy_qty'] *= product_ids_dict[p.id].get('ratio', 1.0) + + return sum(vals['buy_qty'] for vals in product_ids_dict.values()) + + def bom_parent_product_ids_line(line): + product_ids = set() + if line.bom_id.product_id: + product_ids.add((line.bom_id.product_id, line.product_qty)) + else: + for p in line.bom_id.product_tmpl_id.product_variant_ids: + product_ids.add((p.id, line.product_qty)) + return product_ids + + super(PurchaseBySaleHistory, self)._apply_history_product(product, history) + history['buy_qty'] += bom_parent_product_ids(product) diff --git a/purchase_by_sale_history_mrp/wizard/purchase_by_sale_history_views.xml b/purchase_by_sale_history_mrp/wizard/purchase_by_sale_history_views.xml new file mode 100644 index 00000000..41b2b3b3 --- /dev/null +++ b/purchase_by_sale_history_mrp/wizard/purchase_by_sale_history_views.xml @@ -0,0 +1,53 @@ + + + + purchase.sale.history.make.form + purchase.sale.history.make + +
+ + + + + + + + + + + + + + + + +
+
+
+
+
+ + + Fill PO From Sales History + purchase.sale.history.make + form + form + + new + {'default_purchase_id': active_id} + + + + + purchase.order.form.inherit + purchase.order + + + +