From 518ff819a7e42d78dc44a77f0943cddf1c369f8e Mon Sep 17 00:00:00 2001 From: Jared Kipe Date: Wed, 30 Jan 2019 12:55:01 -0800 Subject: [PATCH 01/13] Initial commit of `sale_payment_deposit` for 12.0 --- sale_payment_deposit/__init__.py | 1 + sale_payment_deposit/__manifest__.py | 24 ++++++ sale_payment_deposit/models/__init__.py | 3 + sale_payment_deposit/models/account.py | 31 +++++++ sale_payment_deposit/models/sale.py | 47 ++++++++++ sale_payment_deposit/models/sale_patch.py | 86 +++++++++++++++++++ sale_payment_deposit/views/account_views.xml | 13 +++ .../views/sale_portal_templates.xml | 22 +++++ 8 files changed, 227 insertions(+) create mode 100755 sale_payment_deposit/__init__.py create mode 100755 sale_payment_deposit/__manifest__.py create mode 100644 sale_payment_deposit/models/__init__.py create mode 100644 sale_payment_deposit/models/account.py create mode 100644 sale_payment_deposit/models/sale.py create mode 100644 sale_payment_deposit/models/sale_patch.py create mode 100644 sale_payment_deposit/views/account_views.xml create mode 100644 sale_payment_deposit/views/sale_portal_templates.xml diff --git a/sale_payment_deposit/__init__.py b/sale_payment_deposit/__init__.py new file mode 100755 index 00000000..0650744f --- /dev/null +++ b/sale_payment_deposit/__init__.py @@ -0,0 +1 @@ +from . import models diff --git a/sale_payment_deposit/__manifest__.py b/sale_payment_deposit/__manifest__.py new file mode 100755 index 00000000..4689959c --- /dev/null +++ b/sale_payment_deposit/__manifest__.py @@ -0,0 +1,24 @@ +{ + 'name': 'Sale Payment Deposit', + 'author': 'Hibou Corp. ', + 'category': 'Sales', + 'version': '12.0.1.0.0', + 'description': + """ +Sale Deposits +============= + +Automates the creation of 'Deposit' invoices and payments. For example, someone confirming +a sale with "50% Deposit, 50% on Delivery" payment terms, will pay the +50% deposit payment up front instead of the entire order. + """, + 'depends': [ + 'sale', + 'payment', + ], + 'auto_install': False, + 'data': [ + 'views/account_views.xml', + 'views/sale_portal_templates.xml', + ], +} diff --git a/sale_payment_deposit/models/__init__.py b/sale_payment_deposit/models/__init__.py new file mode 100644 index 00000000..13088db7 --- /dev/null +++ b/sale_payment_deposit/models/__init__.py @@ -0,0 +1,3 @@ +from . import account +from . import sale +from . import sale_patch diff --git a/sale_payment_deposit/models/account.py b/sale_payment_deposit/models/account.py new file mode 100644 index 00000000..111e748f --- /dev/null +++ b/sale_payment_deposit/models/account.py @@ -0,0 +1,31 @@ +from odoo import api, fields, models + + +class AccountPaymentTerm(models.Model): + _inherit = 'account.payment.term' + + deposit_percentage = fields.Float(string='Deposit Percentage', + help='Require deposit when paying on the front end.') + + +class PaymentTransaction(models.Model): + _inherit = 'payment.transaction' + + @api.multi + def _post_process_after_done(self): + now = fields.Datetime.now() + res = super(PaymentTransaction, self)._post_process_after_done() + + # Post Process Payments made on the front of the website, reconciling to Deposit. + for transaction in self.filtered(lambda t: t.payment_id + and t.sale_order_ids + and sum(t.sale_order_ids.mapped('amount_total_deposit')) + and not t.invoice_ids and (now - t.date).seconds < 1200): + if not transaction.sale_order_ids.mapped('invoice_ids'): + # don't process ones that we might still be able to process later... + transaction.write({'is_processed': False}) + else: + # we have a payment and could attempt to reconcile to an invoice + # Leave the payment in 'is_processed': True + transaction.sale_order_ids._auto_deposit_payment_match() + return res diff --git a/sale_payment_deposit/models/sale.py b/sale_payment_deposit/models/sale.py new file mode 100644 index 00000000..293a03bb --- /dev/null +++ b/sale_payment_deposit/models/sale.py @@ -0,0 +1,47 @@ +from odoo import api, fields, models +from json import loads as json_loads + + +class SaleOrder(models.Model): + _inherit = 'sale.order' + + amount_total_deposit = fields.Monetary(string='Deposit', compute='_amount_total_deposit') + + @api.depends('amount_total', 'payment_term_id.deposit_percentage') + def _amount_total_deposit(self): + for order in self: + order.amount_total_deposit = order.amount_total * float(order.payment_term_id.deposit_percentage) / 100.0 + + def action_confirm(self): + res = super(SaleOrder, self).action_confirm() + self._auto_deposit_invoice() + return res + + def _auto_deposit_invoice(self): + wizard_model = self.env['sale.advance.payment.inv'].sudo() + for sale in self.sudo().filtered(lambda o: o.amount_total_deposit): + # Create Deposit Invoices + wizard = wizard_model.create({ + 'advance_payment_method': 'percentage', + 'amount': sale.payment_term_id.deposit_percentage, + }) + wizard.with_context(active_ids=sale.ids).create_invoices() + # Validate Invoices + sale.invoice_ids.filtered(lambda i: i.state == 'draft').action_invoice_open() + # Attempt to reconcile + sale._auto_deposit_payment_match() + + def _auto_deposit_payment_match(self): + # Attempt to find payments that could be used on this new invoice and reconcile them. + # Note that this probably doesn't work for a payment made on the front, see .account.PaymentTransaction + aml_model = self.env['account.move.line'].sudo() + for sale in self.sudo(): + for invoice in sale.invoice_ids.filtered(lambda i: i.state == 'open'): + outstanding = json_loads(invoice.outstanding_credits_debits_widget) + if isinstance(outstanding, dict) and outstanding.get('content'): + for line in outstanding.get('content'): + if abs(line.get('amount', 0.0) - invoice.residual) < 0.01 and line.get('id'): + aml = aml_model.browse(line.get('id')) + aml += invoice.move_id.line_ids.filtered(lambda l: l.account_id == aml.account_id) + if aml.reconcile(): + break diff --git a/sale_payment_deposit/models/sale_patch.py b/sale_payment_deposit/models/sale_patch.py new file mode 100644 index 00000000..c306a21b --- /dev/null +++ b/sale_payment_deposit/models/sale_patch.py @@ -0,0 +1,86 @@ +from odoo import api, fields, models +from odoo.exceptions import ValidationError +from odoo.addons.sale.models.sale import SaleOrder + + +@api.multi +def _create_payment_transaction(self, vals): + # This is a copy job from odoo.addons.sale.models.sale due to the closed nature of the vals.update(dict) call + # Ultimately, only the 'vals.update' with the new amount is really used. + '''Similar to self.env['payment.transaction'].create(vals) but the values are filled with the + current sales orders fields (e.g. the partner or the currency). + :param vals: The values to create a new payment.transaction. + :return: The newly created payment.transaction record. + ''' + # Ensure the currencies are the same. + + # extract variable for use later. + sale = self[0] + + currency = sale.pricelist_id.currency_id + if any([so.pricelist_id.currency_id != currency for so in self]): + raise ValidationError(_('A transaction can\'t be linked to sales orders having different currencies.')) + + # Ensure the partner are the same. + partner = sale.partner_id + if any([so.partner_id != partner for so in self]): + raise ValidationError(_('A transaction can\'t be linked to sales orders having different partners.')) + + # Try to retrieve the acquirer. However, fallback to the token's acquirer. + acquirer_id = vals.get('acquirer_id') + acquirer = False + payment_token_id = vals.get('payment_token_id') + + if payment_token_id: + payment_token = self.env['payment.token'].sudo().browse(payment_token_id) + + # Check payment_token/acquirer matching or take the acquirer from token + if acquirer_id: + acquirer = self.env['payment.acquirer'].browse(acquirer_id) + if payment_token and payment_token.acquirer_id != acquirer: + raise ValidationError(_('Invalid token found! Token acquirer %s != %s') % ( + payment_token.acquirer_id.name, acquirer.name)) + if payment_token and payment_token.partner_id != partner: + raise ValidationError(_('Invalid token found! Token partner %s != %s') % ( + payment_token.partner.name, partner.name)) + else: + acquirer = payment_token.acquirer_id + + # Check an acquirer is there. + if not acquirer_id and not acquirer: + raise ValidationError(_('A payment acquirer is required to create a transaction.')) + + if not acquirer: + acquirer = self.env['payment.acquirer'].browse(acquirer_id) + + # Check a journal is set on acquirer. + if not acquirer.journal_id: + raise ValidationError(_('A journal must be specified of the acquirer %s.' % acquirer.name)) + + if not acquirer_id and acquirer: + vals['acquirer_id'] = acquirer.id + + # Override for Deposit + amount = sum(self.mapped('amount_total')) + # This is a patch, all databases will run this code even if this field doesn't exist. + if hasattr(sale, 'amount_total_deposit') and sum(self.mapped('amount_total_deposit')): + amount = sum(self.mapped('amount_total_deposit')) + + vals.update({ + 'amount': amount, + 'currency_id': currency.id, + 'partner_id': partner.id, + 'sale_order_ids': [(6, 0, self.ids)], + }) + + transaction = self.env['payment.transaction'].create(vals) + + # Process directly if payment_token + if transaction.payment_token_id: + transaction.s2s_do_transaction() + + return transaction + + +# Patch core implementation. +SaleOrder._create_payment_transaction = _create_payment_transaction diff --git a/sale_payment_deposit/views/account_views.xml b/sale_payment_deposit/views/account_views.xml new file mode 100644 index 00000000..aa174032 --- /dev/null +++ b/sale_payment_deposit/views/account_views.xml @@ -0,0 +1,13 @@ + + + + account.payment.term.form.inherit + account.payment.term + + + + + + + + \ No newline at end of file diff --git a/sale_payment_deposit/views/sale_portal_templates.xml b/sale_payment_deposit/views/sale_portal_templates.xml new file mode 100644 index 00000000..cd52552d --- /dev/null +++ b/sale_payment_deposit/views/sale_portal_templates.xml @@ -0,0 +1,22 @@ + + + + \ No newline at end of file From 4f9e35f325cba40498f10db60ad2a36f6f273b79 Mon Sep 17 00:00:00 2001 From: Jared Kipe Date: Sat, 25 Aug 2018 15:13:16 -0700 Subject: [PATCH 02/13] Initial commit of `purchase_by_sale_history` module for 11.0 --- purchase_by_sale_history/__init__.py | 1 + purchase_by_sale_history/__manifest__.py | 21 +++ purchase_by_sale_history/tests/__init__.py | 1 + .../tests/test_purchase_by_sale_history.py | 133 ++++++++++++++++++ purchase_by_sale_history/wizard/__init__.py | 1 + .../wizard/purchase_by_sale_history.py | 100 +++++++++++++ .../wizard/purchase_by_sale_history_views.xml | 52 +++++++ 7 files changed, 309 insertions(+) create mode 100755 purchase_by_sale_history/__init__.py create mode 100755 purchase_by_sale_history/__manifest__.py create mode 100644 purchase_by_sale_history/tests/__init__.py create mode 100644 purchase_by_sale_history/tests/test_purchase_by_sale_history.py create mode 100644 purchase_by_sale_history/wizard/__init__.py create mode 100644 purchase_by_sale_history/wizard/purchase_by_sale_history.py create mode 100644 purchase_by_sale_history/wizard/purchase_by_sale_history_views.xml diff --git a/purchase_by_sale_history/__init__.py b/purchase_by_sale_history/__init__.py new file mode 100755 index 00000000..40272379 --- /dev/null +++ b/purchase_by_sale_history/__init__.py @@ -0,0 +1 @@ +from . import wizard diff --git a/purchase_by_sale_history/__manifest__.py b/purchase_by_sale_history/__manifest__.py new file mode 100755 index 00000000..65eb47a8 --- /dev/null +++ b/purchase_by_sale_history/__manifest__.py @@ -0,0 +1,21 @@ +{ + 'name': 'Purchase by Sale History', + 'author': 'Hibou Corp. ', + 'version': '11.0.1.0.0', + 'category': 'Purchases', + 'sequence': 95, + 'summary': 'Fill Purchase Orders by Sales History', + 'description': """ +Adds wizard to Purchase Orders that will fill the purchase order with products based on sales history. + """, + 'website': 'https://hibou.io/', + 'depends': [ + 'sale_stock', + 'purchase', + ], + 'data': [ + 'wizard/purchase_by_sale_history_views.xml', + ], + 'installable': True, + 'application': False, +} diff --git a/purchase_by_sale_history/tests/__init__.py b/purchase_by_sale_history/tests/__init__.py new file mode 100644 index 00000000..6cc4addf --- /dev/null +++ b/purchase_by_sale_history/tests/__init__.py @@ -0,0 +1 @@ +from . import test_purchase_by_sale_history 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 new file mode 100644 index 00000000..3152bef9 --- /dev/null +++ b/purchase_by_sale_history/tests/test_purchase_by_sale_history.py @@ -0,0 +1,133 @@ +from odoo import fields +from odoo.tests import common +from datetime import datetime, timedelta + + +class TestPurchaseBySaleHistory(common.TransactionCase): + + def test_00_wizard(self): + 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, + }) + + # 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': product11.product_tmpl_id.id, + 'product_id': product11.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, + }) + 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 == product12).product_qty, 0.0) + self.assertEqual(po1.order_line.filtered(lambda l: l.product_id == product2).product_qty, 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 == product11).product_qty, 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) + + # 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 == product11).product_qty, 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) + + # 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 == 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) + diff --git a/purchase_by_sale_history/wizard/__init__.py b/purchase_by_sale_history/wizard/__init__.py new file mode 100644 index 00000000..bbdff949 --- /dev/null +++ b/purchase_by_sale_history/wizard/__init__.py @@ -0,0 +1 @@ +from . import purchase_by_sale_history diff --git a/purchase_by_sale_history/wizard/purchase_by_sale_history.py b/purchase_by_sale_history/wizard/purchase_by_sale_history.py new file mode 100644 index 00000000..fb1e6d30 --- /dev/null +++ b/purchase_by_sale_history/wizard/purchase_by_sale_history.py @@ -0,0 +1,100 @@ +from odoo import api, fields, models +from math import ceil +from datetime import timedelta + + +class PurchaseBySaleHistory(models.TransientModel): + _name = 'purchase.sale.history.make' + + purchase_id = fields.Many2one('purchase.order', string='Purchase Order') + history_start = fields.Date(string='Sales History Start', default=lambda o: fields.Date.from_string(fields.Date.today()) - timedelta(days=30)) + history_end = fields.Date(string='Sales History End', default=fields.Date.today) + history_days = fields.Integer(string='Sales History Days', compute='_compute_history_days') + procure_days = fields.Integer(string='Days to Procure', + default=30, + help='History will be computed as an average per day, ' + '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.') + + @api.multi + @api.depends('history_start', 'history_end') + def _compute_history_days(self): + for wiz in self: + if not all((wiz.history_end, wiz.history_start)): + wiz.history_days = 0 + else: + delta = fields.Date.from_string(wiz.history_end) - fields.Date.from_string(wiz.history_start) + wiz.history_days = delta.days + + @api.multi + @api.depends('purchase_id', 'purchase_id.order_line', 'purchase_id.partner_id') + def _compute_product_count(self): + for wiz in self: + if wiz.purchase_id.order_line: + wiz.product_count = len(set(wiz.purchase_id.order_line.mapped('product_id.id'))) + elif wiz.purchase_id.partner_id: + self.env.cr.execute("""SELECT COUNT(DISTINCT(psi.product_id)) + COUNT(DISTINCT(p.id)) + FROM product_supplierinfo psi + LEFT JOIN product_product p ON p.product_tmpl_id = psi.product_tmpl_id AND psi.product_id IS NULL + WHERE psi.name = %d;""" + % (wiz.purchase_id.partner_id.id, )) + wiz.product_count = self.env.cr.fetchall()[0][0] + + def _history_product_ids(self): + if self.purchase_id.order_line: + return self.purchase_id.order_line.mapped('product_id.id') + + self.env.cr.execute("""SELECT DISTINCT(COALESCE(psi.product_id, p.id)) + FROM product_supplierinfo psi + LEFT JOIN product_product p ON p.product_tmpl_id = psi.product_tmpl_id AND psi.product_id IS NULL + WHERE psi.name = %d;""" + % (self.purchase_id.partner_id.id, )) + rows = self.env.cr.fetchall() + 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))) + return self.env.cr.fetchall() + + def _apply_history(self, history): + line_model = self.env['purchase.order.line'] + updated_lines = line_model.browse() + for pid, sold_qty in history: + # TODO: Should convert from Sale UOM to Purchase UOM + qty = ceil(sold_qty * self.procure_days / self.history_days) + # Find line that already exists on PO + line = self.purchase_id.order_line.filtered(lambda l: l.product_id.id == pid) + if line: + line.write({'product_qty': qty}) + line._onchange_quantity() + else: + # Create new PO line + line = line_model.new({ + 'order_id': self.purchase_id.id, + 'product_id': pid, + 'product_qty': qty, + }) + line.onchange_product_id() + line_vals = line._convert_to_write(line._cache) + line_vals['product_qty'] = qty + line = line_model.create(line_vals) + updated_lines += line + + # Lines not touched should now not be ordered. + other_lines = self.purchase_id.order_line - updated_lines + other_lines.write({'product_qty': 0.0}) + for line in other_lines: + line._onchange_quantity() + + @api.multi + def action_confirm(self): + self.ensure_one() + history_product_ids = self._history_product_ids() + history = self._sale_history(history_product_ids) + self._apply_history(history) + + 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 new file mode 100644 index 00000000..2841283e --- /dev/null +++ b/purchase_by_sale_history/wizard/purchase_by_sale_history_views.xml @@ -0,0 +1,52 @@ + + + + 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 + + + +