#31 Merge branch 'mig/12.0/hr_payroll_rate' into mig/12.0/us_payroll

This commit is contained in:
Jared Kipe
2019-02-10 13:24:36 -08:00
30 changed files with 1191 additions and 0 deletions

View File

@@ -0,0 +1 @@
from . import models

16
hr_payroll_rate/__manifest__.py Executable file
View File

@@ -0,0 +1,16 @@
{
'name': 'Payroll Rates',
'description': 'Payroll Rates',
'version': '12.0.1.0.1',
'website': 'https://hibou.io/',
'author': 'Hibou Corp. <hello@hibou.io>',
'license': 'AGPL-3',
'category': 'Human Resources',
'data': [
'security/ir.model.access.csv',
'views/payroll_views.xml',
],
'depends': [
'hr_payroll',
],
}

View File

@@ -0,0 +1 @@
from . import payroll

View File

@@ -0,0 +1,37 @@
from odoo import api, fields, models
class PayrollRate(models.Model):
_name = 'hr.payroll.rate'
_description = 'Payroll Rate'
active = fields.Boolean(string='Active', default=True)
name = fields.Char(string='Name')
date_from = fields.Date(string='Date From', required=True)
date_to = fields.Date(string='Date To')
company_id = fields.Many2one('res.company', string='Company', copy=False,
default=False)
rate = fields.Float(string='Rate', digits=(12, 6), required=True)
code = fields.Char(string='Code', required=True)
limit_payslip = fields.Float(string='Payslip Limit')
limit_year = fields.Float(string='Year Limit')
wage_limit_payslip = fields.Float(string='Payslip Wage Limit')
wage_limit_year = fields.Float(string='Year Wage Limit')
class Payslip(models.Model):
_inherit = 'hr.payslip'
def _get_rate_domain(self, code):
return [
'|', ('date_to', '=', False), ('date_to', '>=', self.date_to),
'|', ('company_id', '=', False), ('company_id', '=', self.company_id.id),
('code', '=', code),
('date_from', '<=', self.date_from),
]
def get_rate(self, code):
self.ensure_one()
return self.env['hr.payroll.rate'].search(
self._get_rate_domain(code), limit=1, order='date_from DESC, company_id ASC')

View File

@@ -0,0 +1,2 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_hr_payroll_rate,access_hr_payroll_rate,model_hr_payroll_rate,hr_payroll.group_hr_payroll_manager,1,1,1,1
1 id name model_id:id group_id:id perm_read perm_write perm_create perm_unlink
2 access_hr_payroll_rate access_hr_payroll_rate model_hr_payroll_rate hr_payroll.group_hr_payroll_manager 1 1 1 1

View File

@@ -0,0 +1 @@
from . import test_payroll_rate

View File

@@ -0,0 +1,101 @@
from odoo.tests import common
from odoo import fields
class TestPayrollRate(common.TransactionCase):
def setUp(self):
super(TestPayrollRate, self).setUp()
self.employee = self.env['hr.employee'].create({
'birthday': '1985-03-14',
'country_id': self.ref('base.us'),
'department_id': self.ref('hr.dep_rd'),
'gender': 'male',
'name': 'Jared'
})
self.contract = self.env['hr.contract'].create({
'name': 'test',
'employee_id': self.employee.id,
'type_id': self.ref('hr_contract.hr_contract_type_emp'),
'struct_id': self.ref('hr_payroll.structure_base'),
'resource_calendar_id': self.ref('resource.resource_calendar_std'),
'wage': 21.50,
'date_start': '2018-01-01',
'state': 'open',
'schedule_pay': 'monthly',
})
self.payslip = self.env['hr.payslip'].create({
'employee_id': self.employee.id,
})
self.company_other = self.env['res.company'].create({
'name': 'Other'
})
def test_payroll_rate_basic(self):
rate = self.payslip.get_rate('TEST')
self.assertFalse(rate)
test_rate = self.env['hr.payroll.rate'].create({
'name': 'Test Rate',
'code': 'TEST',
'rate': 1.65,
'date_from': '2018-01-01',
})
rate = self.payslip.get_rate('TEST')
self.assertEqual(rate, test_rate)
def test_payroll_rate_multicompany(self):
test_rate_other = self.env['hr.payroll.rate'].create({
'name': 'Test Rate',
'code': 'TEST',
'rate': 1.65,
'date_from': '2018-01-01',
'company_id': self.company_other.id,
})
rate = self.payslip.get_rate('TEST')
self.assertFalse(rate)
test_rate = self.env['hr.payroll.rate'].create({
'name': 'Test Rate',
'code': 'TEST',
'rate': 1.65,
'date_from': '2018-01-01',
})
rate = self.payslip.get_rate('TEST')
self.assertEqual(rate, test_rate)
test_rate_more_specific = self.env['hr.payroll.rate'].create({
'name': 'Test Rate Specific',
'code': 'TEST',
'rate': 1.65,
'date_from': '2018-01-01',
'company_id': self.payslip.company_id.id,
})
rate = self.payslip.get_rate('TEST')
self.assertEqual(rate, test_rate_more_specific)
def test_payroll_rate_newer(self):
test_rate_old = self.env['hr.payroll.rate'].create({
'name': 'Test Rate',
'code': 'TEST',
'rate': 1.65,
'date_from': '2018-01-01',
})
test_rate = self.env['hr.payroll.rate'].create({
'name': 'Test Rate',
'code': 'TEST',
'rate': 2.65,
'date_from': '2019-01-01',
})
rate = self.payslip.get_rate('TEST')
self.assertEqual(rate, test_rate)
def test_payroll_rate_precision(self):
test_rate = self.env['hr.payroll.rate'].create({
'name': 'Test Rate',
'code': 'TEST',
'rate': 2.65001,
'date_from': '2019-01-01',
})
self.assertEqual(round(test_rate.rate * 100000), 265001.0)

View File

@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="payroll_rate_view_tree" model="ir.ui.view">
<field name="name">hr.payroll.rate.tree</field>
<field name="model">hr.payroll.rate</field>
<field name="arch" type="xml">
<tree string="Payroll Rates">
<field name="code"/>
<field name="name"/>
<field name="rate"/>
<field name="date_from"/>
<field name="date_to"/>
<field name="company_id" groups="base.group_multi_company" options="{'no_create': True}"/>
</tree>
</field>
</record>
<record id="payroll_rate_view_form" model="ir.ui.view">
<field name="name">hr.payroll.rate.form</field>
<field name="model">hr.payroll.rate</field>
<field name="arch" type="xml">
<form string="Payroll Rate">
<sheet>
<group>
<group>
<field name="active"/>
<field name="name"/>
<field name="code"/>
<field name="rate"/>
</group>
<group>
<field name="date_from"/>
<field name="date_to"/>
<field name="company_id" groups="base.group_multi_company" options="{'no_create': True}"/>
</group>
<group name="limits">
<field name="limit_payslip"/>
<field name="limit_year"/>
<field name="wage_limit_payslip"/>
<field name="wage_limit_year"/>
</group>
</group>
</sheet>
</form>
</field>
</record>
<record id="payroll_rate_view_search" model="ir.ui.view">
<field name="name">hr.payroll.rate.search</field>
<field name="model">hr.payroll.rate</field>
<field name="arch" type="xml">
<search string="Payroll Rates">
<field name="name"/>
<field name="code"/>
</search>
</field>
</record>
<record id="payroll_rate_view_action_main" model="ir.actions.act_window">
<field name="name">Payroll Rates</field>
<field name="res_model">hr.payroll.rate</field>
<field name="view_type">form</field>
<field name="view_mode">tree,form</field>
<field name="help" type="html">
<p>
No rates
</p>
</field>
</record>
<menuitem id="payroll_rate_menu_main" name="Payroll Rates"
action="payroll_rate_view_action_main"
sequence="13" parent="hr_payroll.menu_hr_payroll_configuration"/>
</odoo>

View File

@@ -0,0 +1 @@
from . import wizard

View File

@@ -0,0 +1,21 @@
{
'name': 'Purchase by Sale History',
'author': 'Hibou Corp. <hello@hibou.io>',
'version': '12.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,
}

View File

@@ -0,0 +1 @@
from . import test_purchase_by_sale_history

View File

@@ -0,0 +1,180 @@
from odoo import fields
from odoo.tests import common
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',
})
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,
'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 + 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 + 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 + 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 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))
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 + 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 + 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 + 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, 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_validate()
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)

View File

@@ -0,0 +1 @@
from . import purchase_by_sale_history

View File

@@ -0,0 +1,135 @@
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.')
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')
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):
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_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()
# 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 = 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:
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, history_product_ids)

View File

@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="purchase_sale_history_make_form" model="ir.ui.view">
<field name="name">purchase.sale.history.make.form</field>
<field name="model">purchase.sale.history.make</field>
<field name="arch" type="xml">
<form string="Fill PO From Sales History">
<sheet>
<field name="id" invisible="1"/>
<field name="purchase_id" invisible="1"/>
<group>
<group>
<field name="history_start"/>
<field name="history_end"/>
<field name="history_days"/>
<field name="history_warehouse_ids" widget="many2many_tags"/>
</group>
<group>
<field name="procure_days"/>
<field name="product_count"/>
</group>
</group>
</sheet>
<footer>
<button string='Run' name="action_confirm" type="object" class="btn-primary"/>
<button string="Cancel" class="btn-default" special="cancel"/>
</footer>
</form>
</field>
</record>
<record id="purchase_sale_history_make_action" model="ir.actions.act_window">
<field name="name">Fill PO From Sales History</field>
<field name="res_model">purchase.sale.history.make</field>
<field name="view_type">form</field>
<field name="view_mode">form</field>
<field name="view_id" ref="purchase_sale_history_make_form"/>
<field name="target">new</field>
<field name="context">{'default_purchase_id': active_id}</field>
</record>
<!-- Button on Purchase Order to launch wizard -->
<record id="purchase_order_form_inherit" model="ir.ui.view">
<field name="name">purchase.order.form.inherit</field>
<field name="model">purchase.order</field>
<field name="inherit_id" ref="purchase.purchase_order_form"/>
<field name="arch" type="xml">
<xpath expr="//button[@name='button_confirm']" position="after">
<button name="%(purchase_by_sale_history.purchase_sale_history_make_action)d" type="action" string="Fill by Sales" attrs="{'invisible': ['|', ('state', 'in', ('purchase', 'done', 'cancel')), ('partner_id', '=', False)]}"/>
</xpath>
</field>
</record>
</odoo>

View File

@@ -0,0 +1 @@
from . import wizard

View File

@@ -0,0 +1,20 @@
{
'name': 'Purchase by Sale History MRP',
'author': 'Hibou Corp. <hello@hibou.io>',
'version': '12.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,
}

View File

@@ -0,0 +1 @@
from . import test_purchase_by_sale_history

View File

@@ -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_validate()
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)

View File

@@ -0,0 +1 @@
from . import purchase_by_sale_history

View File

@@ -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)

View File

@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="purchase_sale_history_make_form" model="ir.ui.view">
<field name="name">purchase.sale.history.make.form</field>
<field name="model">purchase.sale.history.make</field>
<field name="arch" type="xml">
<form string="Fill PO From Sales History">
<sheet>
<field name="id" invisible="1"/>
<field name="purchase_id" invisible="1"/>
<group>
<group>
<field name="history_start"/>
<field name="history_end"/>
<field name="history_days"/>
<field name="history_warehouse_ids" widget="many2many_tags"/>
</group>
<group>
<field name="procure_days"/>
<field name="product_count"/>
</group>
</group>
</sheet>
<footer>
<button string='Run' name="action_confirm" type="object" class="btn-primary"/>
<button string="Cancel" class="btn-default" special="cancel"/>
</footer>
</form>
</field>
</record>
<record id="purchase_sale_history_make_action" model="ir.actions.act_window">
<field name="name">Fill PO From Sales History</field>
<field name="res_model">purchase.sale.history.make</field>
<field name="view_type">form</field>
<field name="view_mode">form</field>
<field name="view_id" ref="purchase_sale_history_make_form"/>
<field name="target">new</field>
<field name="context">{'default_purchase_id': active_id}</field>
</record>
<!-- Button on Purchase Order to launch wizard -->
<record id="purchase_order_form_inherit" model="ir.ui.view">
<field name="name">purchase.order.form.inherit</field>
<field name="model">purchase.order</field>
<field name="inherit_id" ref="purchase.purchase_order_form"/>
<field name="arch" type="xml">
<xpath expr="//button[@name='button_confirm']" position="after">
<button name="%(purchase_by_sale_history.purchase_sale_history_make_action)d" type="action" string="Fill by Sales" attrs="{'invisible': ['|', ('state', 'in', ('purchase', 'done', 'cancel')), ('partner_id', '=', False)]}"/>
</xpath>
</field>
</record>
</odoo>

View File

@@ -0,0 +1 @@
from . import models

View File

@@ -0,0 +1,24 @@
{
'name': 'Sale Payment Deposit',
'author': 'Hibou Corp. <hello@hibou.io>',
'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',
],
}

View File

@@ -0,0 +1,3 @@
from . import account
from . import sale
from . import sale_patch

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="view_payment_term_form_inherit" model="ir.ui.view">
<field name="name">account.payment.term.form.inherit</field>
<field name="model">account.payment.term</field>
<field name="inherit_id" ref="account.view_payment_term_form"/>
<field name="arch" type="xml">
<xpath expr="//group/group" position="inside">
<field name="deposit_percentage"/>
</xpath>
</field>
</record>
</odoo>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<template id="sale_order_portal_template_deposit" name="Sales Order Portal Template - Deposit" inherit_id="sale.sale_order_portal_template">
<!-- Display the Deposit amount prominently -->
<xpath expr="//t[@t-set='title']/h2" position="replace">
<h2 class="mb-0"><b t-field="sale_order.amount_total"/></h2>
<h5 t-if="sale_order.amount_total_deposit"><b t-field="sale_order.amount_total_deposit"/> Deposit</h5>
</xpath>
<!-- Display the Deposit and Total when Signing -->
<xpath expr="//div[@id='modalaccept']/div/form//li[2]" position="replace">
<li><span>For an amount of:</span> <b data-id="total_amount" t-field="sale_order.amount_total"/></li>
<li t-if="sale_order.amount_total_deposit"><span>Deposit today of:</span> <b data-id="total_amount_deposit" t-field="sale_order.amount_total_deposit"/></li>
<li t-if="sale_order.payment_term_id.note"><span t-field="sale_order.payment_term_id.note"/></li>
</xpath>
<!-- Display the Deposit when Paying -->
<xpath expr="//div[@id='modalaccept']/div/main//li[2]" position="replace">
<li t-if="sale_order.amount_total_deposit"><span>For the deposit amount of:</span> <b data-id="total_amount_deposit" t-field="sale_order.amount_total_deposit"/></li>
<li t-else=""><span>For an amount of:</span> <b data-id="total_amount" t-field="sale_order.amount_total"/></li>
<li t-if="sale_order.payment_term_id.note"><span t-field="sale_order.payment_term_id.note"/></li>
</xpath>
</template>
</odoo>