diff --git a/addons/account/data/account_data.xml b/addons/account/data/account_data.xml index 723ec6da155..8aa6fc9527c 100644 --- a/addons/account/data/account_data.xml +++ b/addons/account/data/account_data.xml @@ -57,7 +57,7 @@ - + diff --git a/addons/account_anglo_saxon/stock.py b/addons/account_anglo_saxon/stock.py index 278deb9a2a8..2b40bb67cf3 100644 --- a/addons/account_anglo_saxon/stock.py +++ b/addons/account_anglo_saxon/stock.py @@ -42,7 +42,7 @@ class stock_picking(osv.osv): '''Return ids of created invoices for the pickings''' res = super(stock_picking,self).action_invoice_create(cr, uid, ids, journal_id, group, type, context=context) if type == 'in_refund': - for inv in self.pool.get('account.invoice').browse(cr, uid, res.values(), context=context): + for inv in self.pool.get('account.invoice').browse(cr, uid, res, context=context): for ol in inv.invoice_line: if ol.product_id: oa = ol.product_id.property_stock_account_output and ol.product_id.property_stock_account_output.id @@ -54,7 +54,7 @@ class stock_picking(osv.osv): self.pool.get('account.invoice.line').write(cr, uid, [ol.id], {'account_id': a}) elif type == 'in_invoice': - for inv in self.pool.get('account.invoice').browse(cr, uid, res.values(), context=context): + for inv in self.pool.get('account.invoice').browse(cr, uid, res, context=context): for ol in inv.invoice_line: if ol.product_id: oa = ol.product_id.property_stock_account_input and ol.product_id.property_stock_account_input.id diff --git a/addons/account_anglo_saxon/test/anglo_saxon.yml b/addons/account_anglo_saxon/test/anglo_saxon.yml index 042f35a5271..9c953482f53 100644 --- a/addons/account_anglo_saxon/test/anglo_saxon.yml +++ b/addons/account_anglo_saxon/test/anglo_saxon.yml @@ -103,7 +103,7 @@ I configure the product with required accounts, and cost method = standard - !python {model: product.product}: | - self.write(cr, uid, [ref('product.product_product_3')], {'list_price': 20.00,'standard_price': 9,'categ_id': ref('product.product_category_4'),'valuation': 'real_time', + self.write(cr, uid, [ref('product.product_product_10')], {'list_price': 20.00,'standard_price': 9,'categ_id': ref('product.product_category_4'),'valuation': 'real_time', 'property_account_income': ref('account_anglo_income'),'property_account_expense': ref('account_anglo_cogs'), 'property_account_creditor_price_difference': ref('account_anglo_price_difference'),'property_stock_account_input': ref('account_anglo_stock_input'), 'property_stock_account_output': ref('account_anglo_stock_output'), 'cost_method': 'standard'}) @@ -115,7 +115,7 @@ location_id: stock.stock_location_stock pricelist_id: 1 order_line: - - product_id: product.product_product_3 + - product_id: product.product_product_10 product_qty: 1 price_unit: 10 date_planned: !eval "'%s' % (time.strftime('%Y-%m-%d'))" @@ -126,10 +126,9 @@ - Reception is ready for process so now done the reception. - - !python {model: stock.partial.picking}: | - pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_001")).picking_ids - partial_id = self.create(cr, uid, {},context={'active_model': 'stock.picking','active_ids': [pick_ids[0].id]}) - self.do_partial(cr, uid, [partial_id]) + !python {model: stock.picking}: | + picking_id = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_001")).picking_ids[0] + picking_id.do_transfer(context=context) - I check the Stock Interim account (Received) is credited successfully. - @@ -192,38 +191,37 @@ - !record {model: stock.picking, id: stock_picking_out001}: partner_id: base.res_partner_13 - invoice_state: 2binvoiced move_lines: - company_id: base.main_company location_id: stock.stock_location_stock - product_id: product.product_product_3 - product_qty: 1.0 + product_id: product.product_product_10 + product_uom_qty: 1.0 product_uom: product.product_uom_unit location_dest_id: stock.stock_location_customers + invoice_state: 2binvoiced move_type: direct - type: out + picking_type_id: stock.picking_type_out - I need to check the availability of the product, So I make my picking order for processing later. - !python {model: stock.picking}: | - self.draft_force_assign(cr, uid, [ref("stock_picking_out001")], {"lang": "en_US", "search_default_available": - 1, "tz": False, "active_model": "ir.ui.menu", "contact_display": "partner", - "active_ids": [ref("stock.menu_action_picking_tree")], "active_id": ref("stock.menu_action_picking_tree"), - }) + self.action_confirm(cr, uid, [ref('stock_picking_out001')], context=context) + - I check the product availability, Product is available in the stock and ready to be sent. - !python {model: stock.picking}: | - self.action_assign(cr, uid, [ref("stock_picking_out001")], {"lang": "en_US", "search_default_available": - 1, "tz": False, "active_model": "ir.ui.menu", "contact_display": "partner", - "active_ids": [ref("stock.menu_action_picking_tree")], "active_id": ref("stock.menu_action_picking_tree"), - }) + picking = self.browse(cr, uid, ref("stock_picking_out001")) + assert picking.state == "confirmed", "Picking should be confirmed." + for move_line in picking.move_lines: + assert move_line.state == "confirmed", "Move should be confirmed." + - I process the delivery. - - !python {model: stock.partial.picking}: | - partial_id = self.create(cr, uid, {}, context={'active_model':'stock.picking','active_ids':[ref('stock_picking_out001')]}) - self.do_partial(cr, uid, [partial_id]) + !python {model: stock.picking}: | + picking = self.pool.get('stock.picking').browse(cr, uid, ref("stock_picking_out001")) + picking.do_transfer(context=context) - I check Stock Interim account (Delivery) is debited successfully. - @@ -240,9 +238,7 @@ !python {model: stock.invoice.onshipping}: | wiz_id = self.create(cr, uid, {'journal_id': ref('account.sales_journal')}, {'active_ids': [ref("stock_picking_out001")], "active_model": "stock.picking"}) - self.create_invoice(cr, uid, [wiz_id], {"lang": "en_US", - "search_default_available": 1, "tz": False, "active_model": "stock.picking", - "contact_display": "partner", "active_ids": [ref("stock_picking_out001")], "active_id": ref("stock_picking_out001")}) + self.create_invoice(cr, uid, [wiz_id], {"active_ids": [ref("stock_picking_out001")], "active_id": ref("stock_picking_out001")}) - I check that the customer invoice is created successfully. - diff --git a/addons/account_anglo_saxon/test/anglo_saxon_avg_fifo.yml b/addons/account_anglo_saxon/test/anglo_saxon_avg_fifo.yml index 92d331f97d7..b9d290c89e3 100644 --- a/addons/account_anglo_saxon/test/anglo_saxon_avg_fifo.yml +++ b/addons/account_anglo_saxon/test/anglo_saxon_avg_fifo.yml @@ -134,10 +134,9 @@ - Reception is ready for process so now done the reception. - - !python {model: stock.partial.picking}: | - pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_001_fifo")).picking_ids - partial_id = self.create(cr, uid, {},context={'active_model': 'stock.picking','active_ids': [pick_ids[0].id]}) - self.do_partial(cr, uid, [partial_id]) + !python {model: stock.picking}: | + picking_id = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_001_fifo")).picking_ids[0] + picking_id.do_transfer(context=context) - I check the Stock Interim account (Received) is credit successfully. - @@ -195,37 +194,34 @@ - !record {model: stock.picking, id: stock_picking_out001_fifo}: partner_id: base.res_partner_13 - invoice_state: 2binvoiced move_lines: - company_id: base.main_company location_id: stock.stock_location_stock product_id: product_fifo_anglo_saxon - product_qty: 1.0 + product_uom_qty: 1.0 location_dest_id: stock.stock_location_customers + invoice_state: 2binvoiced move_type: direct - type: out + picking_type_id: stock.picking_type_out - I need to check the availability of the product, So I make my picking order for processing later. - !python {model: stock.picking}: | - self.draft_force_assign(cr, uid, [ref("stock_picking_out001_fifo")], {"lang": "en_US", "search_default_available": - 1, "tz": False, "active_model": "ir.ui.menu", "contact_display": "partner", - "active_ids": [ref("stock.menu_action_picking_tree")], "active_id": ref("stock.menu_action_picking_tree"), - }) + self.action_confirm(cr, uid, [ref('stock_picking_out001_fifo')], context=context) - I check the product availability, Product is available in the stock and ready to be sent. - !python {model: stock.picking}: | - self.action_assign(cr, uid, [ref("stock_picking_out001_fifo")], {"lang": "en_US", "search_default_available": - 1, "tz": False, "active_model": "ir.ui.menu", "contact_display": "partner", - "active_ids": [ref("stock.menu_action_picking_tree")], "active_id": ref("stock.menu_action_picking_tree"), - }) + picking = self.browse(cr, uid, ref("stock_picking_out001_fifo")) + assert picking.state == "confirmed", "Picking should be confirmed." + for move_line in picking.move_lines: + assert move_line.state == "confirmed", "Move should be confirmed." - I process the delivery. - - !python {model: stock.partial.picking}: | - partial_id = self.create(cr, uid, {}, context={'active_model':'stock.picking','active_ids':[ref('stock_picking_out001_fifo')]}) - self.do_partial(cr, uid, [partial_id]) + !python {model: stock.picking}: | + picking = self.pool.get('stock.picking').browse(cr, uid, ref("stock_picking_out001_fifo")) + picking.do_transfer(context=context) - I check Stock Interim account (Delivery) is debited successfully. - diff --git a/addons/claim_from_delivery/claim_delivery_data.xml b/addons/claim_from_delivery/claim_delivery_data.xml index 1b69087d4b8..5dabdc25931 100644 --- a/addons/claim_from_delivery/claim_delivery_data.xml +++ b/addons/claim_from_delivery/claim_delivery_data.xml @@ -4,7 +4,7 @@ Delivery Order - stock.picking.out + stock.picking diff --git a/addons/claim_from_delivery/claim_delivery_view.xml b/addons/claim_from_delivery/claim_delivery_view.xml index 6f9ca5e4a66..f676b03ac47 100644 --- a/addons/claim_from_delivery/claim_delivery_view.xml +++ b/addons/claim_from_delivery/claim_delivery_view.xml @@ -6,17 +6,17 @@ crm.claim form - {'default_ref': 'stock.picking.out,'+str(context.get('active_id', False))} - [('ref','=','stock.picking.out,'+str(context.get('active_id',False)))] + {'default_ref': 'stock.picking,'+str(context.get('active_id', False))} + [('ref','=','stock.picking,'+str(context.get('active_id',False)))] crm.claim.from_delivery.form - stock.picking.out - + stock.picking +
- diff --git a/addons/claim_from_delivery/stock_picking.py b/addons/claim_from_delivery/stock_picking.py index 6929809bfe2..dd6164b2ce6 100644 --- a/addons/claim_from_delivery/stock_picking.py +++ b/addons/claim_from_delivery/stock_picking.py @@ -7,7 +7,7 @@ class stock_picking(osv.osv): def _claim_count_out(self, cr, uid, ids, field_name, arg, context=None): Claim = self.pool['crm.claim'] return { - id: Claim.search_count(cr, uid, [('ref', '=',('stock.picking.out,' + str(ids[0])))], context=context) + id: Claim.search_count(cr, uid, [('ref', '=',('stock.picking,' + str(ids[0])))], context=context) for id in ids } @@ -15,16 +15,3 @@ class stock_picking(osv.osv): 'claim_count_out': fields.function(_claim_count_out, string='Claims', type='integer'), } -# Because of the way inheritance works in the ORM (bug), and the way stock.picking.out -# is defined (inherit from stock.picking, dispatch read to stock.picking), it is necessary -# to add the field claim_count_out to this class, even though the _claim_count_out method -# in stock_picking_out will not be called (but its existence will be checked). -class stock_picking_out(osv.osv): - _inherit = 'stock.picking.out' - - def _claim_count_out(self, cr, uid, ids, field_name, arg, context=None): - return super(stock_picking_out, self)._claim_count_out(cr, uid, ids, field_name, arg, context=context) - - _columns = { - 'claim_count_out': fields.function(_claim_count_out, string='Claims', type='integer'), - } diff --git a/addons/crm/crm.py b/addons/crm/crm.py index dc4aadf0547..b114a6e24fe 100644 --- a/addons/crm/crm.py +++ b/addons/crm/crm.py @@ -28,11 +28,11 @@ from openerp.osv import fields from openerp.osv import osv AVAILABLE_PRIORITIES = [ - ('1', 'Highest'), - ('2', 'High'), - ('3', 'Normal'), - ('4', 'Low'), - ('5', 'Lowest'), + ('0', 'Very Low'), + ('1', 'Low'), + ('2', 'Normal'), + ('3', 'High'), + ('4', 'Very High'), ] class crm_case_channel(osv.osv): diff --git a/addons/crm/crm_lead.py b/addons/crm/crm_lead.py index db1c1cd6320..6be094c2227 100644 --- a/addons/crm/crm_lead.py +++ b/addons/crm/crm_lead.py @@ -459,21 +459,6 @@ class crm_lead(format_address, osv.osv): self.write(cr, uid, [case.id], data, context=context) return True - def set_priority(self, cr, uid, ids, priority, context=None): - """ Set lead priority - """ - return self.write(cr, uid, ids, {'priority': priority}, context=context) - - def set_high_priority(self, cr, uid, ids, context=None): - """ Set lead priority to high - """ - return self.set_priority(cr, uid, ids, '1', context=context) - - def set_normal_priority(self, cr, uid, ids, context=None): - """ Set lead priority to normal - """ - return self.set_priority(cr, uid, ids, '3', context=context) - def _merge_get_result_type(self, cr, uid, opps, context=None): """ Define the type of the result of the merge. If at least one of the diff --git a/addons/crm/crm_lead_demo.xml b/addons/crm/crm_lead_demo.xml index 0187f14555f..64ee8f7b870 100644 --- a/addons/crm/crm_lead_demo.xml +++ b/addons/crm/crm_lead_demo.xml @@ -156,7 +156,7 @@ Contact: +1 813 494 5005 - 3 + 2 @@ -174,7 +174,7 @@ Contact: +1 813 494 5005 - 5 + 0 @@ -193,7 +193,7 @@ Contact: +1 813 494 5005 - 4 + 1 @@ -253,7 +253,7 @@ Andrew - 3 + 2 @@ -331,7 +331,7 @@ Andrew - 3 + 2 Send Catalogue by Email @@ -404,7 +404,7 @@ Andrew - 4 + 1 Send price list regarding our interventions @@ -431,7 +431,7 @@ Andrew - 4 + 1 Call to define real needs about training @@ -492,7 +492,7 @@ Andrew - 3 + 2 @@ -510,7 +510,7 @@ Andrew - 3 + 1 @@ -525,7 +525,7 @@ Andrew - 5 + 0 @@ -543,7 +543,7 @@ Andrew - 5 + 0 @@ -588,7 +588,7 @@ Andrew - 3 + 2 Send Catalogue by Email diff --git a/addons/crm/crm_lead_view.xml b/addons/crm/crm_lead_view.xml index 5a7aac6e569..3481e29baf5 100644 --- a/addons/crm/crm_lead_view.xml +++ b/addons/crm/crm_lead_view.xml @@ -156,7 +156,7 @@ - +
- 7 - 7 - + +
+ +
- + diff --git a/addons/crm/crm_phonecall.py b/addons/crm/crm_phonecall.py index 5b06493c60e..89a1f799b2b 100644 --- a/addons/crm/crm_phonecall.py +++ b/addons/crm/crm_phonecall.py @@ -62,7 +62,7 @@ class crm_phonecall(osv.osv): ('object_id.model', '=', 'crm.phonecall')]"), 'partner_phone': fields.char('Phone', size=32), 'partner_mobile': fields.char('Mobile', size=32), - 'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'), + 'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority'), 'date_closed': fields.datetime('Closed', readonly=True), 'date': fields.datetime('Date'), 'opportunity_id': fields.many2one ('crm.lead', 'Lead/Opportunity'), @@ -75,7 +75,7 @@ class crm_phonecall(osv.osv): _defaults = { 'date': fields.datetime.now, - 'priority': crm.AVAILABLE_PRIORITIES[2][0], + 'priority': '1', 'state': _get_default_state, 'user_id': lambda self, cr, uid, ctx: uid, 'active': 1 diff --git a/addons/crm/crm_phonecall_demo.xml b/addons/crm/crm_phonecall_demo.xml index c6026c8d894..8d41c868c27 100644 --- a/addons/crm/crm_phonecall_demo.xml +++ b/addons/crm/crm_phonecall_demo.xml @@ -6,7 +6,7 @@ - + Left the message done @@ -19,7 +19,7 @@ - + Need more information on the proposed deal done @@ -44,7 +44,7 @@ - + Wanted information about pricing of laptops done @@ -58,7 +58,7 @@ - + More information on the proposed deal pending @@ -69,7 +69,7 @@ - + Proposal for discount offer open diff --git a/addons/crm/crm_phonecall_view.xml b/addons/crm/crm_phonecall_view.xml index bd611ff7da7..f51cd847c6b 100644 --- a/addons/crm/crm_phonecall_view.xml +++ b/addons/crm/crm_phonecall_view.xml @@ -103,7 +103,7 @@ - + diff --git a/addons/crm/report/crm_phonecall_report.py b/addons/crm/report/crm_phonecall_report.py index 6a3e3bf208b..7365e224b22 100644 --- a/addons/crm/report/crm_phonecall_report.py +++ b/addons/crm/report/crm_phonecall_report.py @@ -42,7 +42,7 @@ class crm_phonecall_report(osv.osv): _columns = { 'user_id':fields.many2one('res.users', 'User', readonly=True), 'section_id':fields.many2one('crm.case.section', 'Section', readonly=True), - 'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'), + 'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority'), 'nbr': fields.integer('# of Cases', readonly=True), 'state': fields.selection(AVAILABLE_STATES, 'Status', size=16, readonly=True), 'create_date': fields.datetime('Create Date', readonly=True, select=True), diff --git a/addons/crm_claim/crm_claim.py b/addons/crm_claim/crm_claim.py index 4d44b90c2f2..641c490cabb 100644 --- a/addons/crm_claim/crm_claim.py +++ b/addons/crm_claim/crm_claim.py @@ -88,7 +88,7 @@ class crm_claim(osv.osv): 'categ_id': fields.many2one('crm.case.categ', 'Category', \ domain="[('section_id','=',section_id),\ ('object_id.model', '=', 'crm.claim')]"), - 'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'), + 'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority'), 'type_action': fields.selection([('correction','Corrective Action'),('prevention','Preventive Action')], 'Action Type'), 'user_id': fields.many2one('res.users', 'Responsible'), 'user_fault': fields.char('Trouble Responsible', size=64), @@ -111,7 +111,7 @@ class crm_claim(osv.osv): 'section_id': lambda s, cr, uid, c: s._get_default_section_id(cr, uid, c), 'date': fields.datetime.now, 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.case', context=c), - 'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0], + 'priority': '1', 'active': lambda *a: 1, 'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c) } diff --git a/addons/crm_claim/crm_claim_demo.xml b/addons/crm_claim/crm_claim_demo.xml index f7675599561..ec06d3f6577 100644 --- a/addons/crm_claim/crm_claim_demo.xml +++ b/addons/crm_claim/crm_claim_demo.xml @@ -9,7 +9,7 @@ - + @@ -21,7 +21,7 @@ - + @@ -46,7 +46,7 @@ - + @@ -58,7 +58,7 @@ - + @@ -69,7 +69,7 @@ - + @@ -82,7 +82,7 @@ - + diff --git a/addons/crm_claim/crm_claim_view.xml b/addons/crm_claim/crm_claim_view.xml index e7724cb3b6d..b6d43c4b140 100644 --- a/addons/crm_claim/crm_claim_view.xml +++ b/addons/crm_claim/crm_claim_view.xml @@ -107,7 +107,7 @@ - + diff --git a/addons/crm_claim/report/crm_claim_report.py b/addons/crm_claim/report/crm_claim_report.py index d389f690fb4..9628165d27f 100644 --- a/addons/crm_claim/report/crm_claim_report.py +++ b/addons/crm_claim/report/crm_claim_report.py @@ -23,11 +23,9 @@ from openerp.osv import fields,osv from openerp import tools AVAILABLE_PRIORITIES = [ - ('5', 'Lowest'), - ('4', 'Low'), - ('3', 'Normal'), - ('2', 'High'), - ('1', 'Highest') + ('0', 'Low'), + ('1', 'Normal'), + ('2', 'High') ] diff --git a/addons/crm_helpdesk/crm_helpdesk.py b/addons/crm_helpdesk/crm_helpdesk.py index c1cd6d2ff91..faa3ae01041 100644 --- a/addons/crm_helpdesk/crm_helpdesk.py +++ b/addons/crm_helpdesk/crm_helpdesk.py @@ -59,7 +59,7 @@ class crm_helpdesk(osv.osv): 'channel_id': fields.many2one('crm.case.channel', 'Channel', help="Communication channel."), 'planned_revenue': fields.float('Planned Revenue'), 'planned_cost': fields.float('Planned Costs'), - 'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'), + 'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority'), 'probability': fields.float('Probability (%)'), 'categ_id': fields.many2one('crm.case.categ', 'Category', \ domain="['|',('section_id','=',False),('section_id','=',section_id),\ @@ -83,7 +83,7 @@ class crm_helpdesk(osv.osv): 'state': lambda *a: 'draft', 'date': fields.datetime.now, 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.helpdesk', context=c), - 'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0], + 'priority': '1', } def on_change_partner_id(self, cr, uid, ids, partner_id, context=None): diff --git a/addons/crm_helpdesk/crm_helpdesk_demo.xml b/addons/crm_helpdesk/crm_helpdesk_demo.xml index c76949f78f8..eed8f73af1f 100644 --- a/addons/crm_helpdesk/crm_helpdesk_demo.xml +++ b/addons/crm_helpdesk/crm_helpdesk_demo.xml @@ -5,7 +5,7 @@ - 3 + 1 draft @@ -17,7 +17,7 @@ - 3 + 1 draft @@ -42,7 +42,7 @@ - 3 + 1 draft How to create a new module diff --git a/addons/crm_helpdesk/crm_helpdesk_view.xml b/addons/crm_helpdesk/crm_helpdesk_view.xml index 79615715f5f..464e33973b6 100644 --- a/addons/crm_helpdesk/crm_helpdesk_view.xml +++ b/addons/crm_helpdesk/crm_helpdesk_view.xml @@ -51,7 +51,7 @@ - + diff --git a/addons/delivery/__init__.py b/addons/delivery/__init__.py index d277419434a..35705c10cb6 100644 --- a/addons/delivery/__init__.py +++ b/addons/delivery/__init__.py @@ -21,7 +21,6 @@ import delivery import partner -import report import sale import stock diff --git a/addons/delivery/__openerp__.py b/addons/delivery/__openerp__.py index 1ee6bf413ec..ab00fa9087e 100644 --- a/addons/delivery/__openerp__.py +++ b/addons/delivery/__openerp__.py @@ -35,10 +35,10 @@ invoices from picking, OpenERP is able to add and compute the shipping line. 'depends': ['sale_stock'], 'data': [ 'security/ir.model.access.csv', - 'delivery_report.xml', 'delivery_view.xml', 'partner_view.xml', - 'delivery_data.xml' + 'delivery_data.xml', + 'views/report_shipping.xml', ], 'demo': ['delivery_demo.xml'], 'test': ['test/delivery_cost.yml'], diff --git a/addons/delivery/delivery_demo.xml b/addons/delivery/delivery_demo.xml index f090947d57f..ae711083b73 100644 --- a/addons/delivery/delivery_demo.xml +++ b/addons/delivery/delivery_demo.xml @@ -22,7 +22,6 @@ Delivery service - make_to_order 10.0 10.0 @@ -53,12 +52,6 @@ - - - - - - @@ -94,5 +87,11 @@ + + + property_delivery_carrier + + + diff --git a/addons/delivery/delivery_report.xml b/addons/delivery/delivery_report.xml deleted file mode 100644 index 3cebbba4eac..00000000000 --- a/addons/delivery/delivery_report.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - diff --git a/addons/delivery/delivery_view.xml b/addons/delivery/delivery_view.xml index 743391d1522..31c0e08b093 100644 --- a/addons/delivery/delivery_view.xml +++ b/addons/delivery/delivery_view.xml @@ -27,15 +27,13 @@ - + + + + - - - - - + @@ -102,7 +101,7 @@ UPS Express, UPS Standard) with a set of pricing rules attached to each method.

- These methods allows to automaticaly compute the delivery price + These methods allow to automatically compute the delivery price according to your settings; on the sales order (based on the quotation) or the invoice (based on the delivery orders).

@@ -220,48 +219,41 @@
- delivery.stock.picking_withcarrier.out.form.view - stock.picking.out - - - - - - - - - - - - - - - - stock.picking_withweight.internal.form.view + delivery.stock.picking_withcarrier.form.view stock.picking - - - + Picking to be invoiced - stock.picking.out + stock.picking ir.actions.act_window form tree,form [('invoice_state','=','2binvoiced'),('state','=','done'),('type','=','out')] {'default_invoice_state': '2binvoiced', 'default_type': 'out', 'contact_display': 'partner'} - + @@ -315,28 +307,5 @@
- - stock.picking.out.form - stock.picking.out - - - - - - - - - - - -

- When you sell this service, nothing special will be triggered - to deliver the customer, as you set the procurement method as - 'Make to Stock'. -

-

- When you sell this product, OpenERP will use the available - inventory for the delivery order. -

- If there are not enough quantities available, the delivery order - will wait for new products. To fulfill the inventory, you should - create others rules like orderpoints. -

-

- When you sell this product, a delivery order will be created. - OpenERP will consider that the required quantities are always - available as it's a consumable (as a result of this, the quantity - on hand may become negative). -

-
-
-
-
- diff --git a/addons/procurement/procurement_workflow.xml b/addons/procurement/procurement_workflow.xml deleted file mode 100644 index d4068a6eada..00000000000 --- a/addons/procurement/procurement_workflow.xml +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - procurement.order.basic - procurement.order - True - - - - - True - draft - - - - cancel - function - action_cancel() - True - - - - confirm - function - action_confirm() - - - - confirm_wait - function - write({'state':'exception'}) - - - - confirm_mts - - - - confirm_mto - - - - make_to_stock - function - action_move_assigned() - - - - - ready - function - action_ready() - - - - wait_done - function - write({'state':'waiting'}) - - - - - True - done - function - action_done() - - - - - - button_confirm - - - - - button_wait_done - True - - - - - check_move_done() - stock.move - [move_id.id] - - - - - - button_check - test_cancel() - - - - - button_check - check_conditions_confirm2wait() - - - - - procure_method=='make_to_order' - - - - - procure_method=='make_to_stock' - - - - - button_cancel - - - - - button_cancel - - - - - button_restart - - - - - button_cancel - - - - - button_restart - - - - - button_cancel - - - - - check_make_to_stock() - - - - - - - not check_produce() and not check_buy() and not check_move() - - - - - - True - - - - - - - - action_check_finished() - stock.move - move_id and [move_id.id] or [] - - - - - check_move_cancel() - - - - diff --git a/addons/procurement/schedulers.py b/addons/procurement/schedulers.py deleted file mode 100644 index b86a799e19c..00000000000 --- a/addons/procurement/schedulers.py +++ /dev/null @@ -1,257 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2010 Tiny SPRL (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## - -from datetime import datetime -from dateutil.relativedelta import relativedelta - -import openerp -from openerp.osv import osv -from openerp.osv import fields -from openerp.tools.translate import _ -from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT -from openerp import tools - -class procurement_order(osv.osv): - _inherit = 'procurement.order' - - def run_scheduler(self, cr, uid, automatic=False, use_new_cursor=False, skip_exception=False, context=None): - ''' Runs through scheduler. - @param use_new_cursor: False or the dbname - ''' - if use_new_cursor: - use_new_cursor = cr.dbname - self._procure_confirm(cr, uid, use_new_cursor=use_new_cursor, skip_exception=skip_exception, context=context) - self._procure_orderpoint_confirm(cr, uid, automatic=automatic,\ - use_new_cursor=use_new_cursor, context=context) - - def _procure_confirm(self, cr, uid, ids=None, use_new_cursor=False, skip_exception=False, context=None): - ''' - Call the scheduler to check the procurement order - - @param self: The object pointer - @param cr: The current row, from the database cursor, - @param uid: The current user ID for security checks - @param ids: List of selected IDs - @param use_new_cursor: False or the dbname - @param skip_exception: boolean - @param context: A standard dictionary for contextual values - @return: Dictionary of values - ''' - if context is None: - context = {} - try: - if use_new_cursor: - cr = openerp.registry(use_new_cursor).cursor() - - procurement_obj = self.pool.get('procurement.order') - if not skip_exception: - if not ids: - ids = procurement_obj.search(cr, uid, [('state', '=', 'exception')], order="date_planned") - self.signal_button_restart(cr, uid, ids) - if use_new_cursor: - cr.commit() - company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id - maxdate = (datetime.today() + relativedelta(days=company.schedule_range)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT) - offset = 0 - while True: - ids = procurement_obj.search(cr, uid, [('state', '=', 'confirmed'), ('procure_method', '=', 'make_to_order')], offset=offset, limit=500, order='priority, date_planned', context=context) - for proc in procurement_obj.browse(cr, uid, ids, context=context): - if maxdate >= proc.date_planned: - self.signal_button_check(cr, uid, [proc.id]) - else: - offset += 1 - - if use_new_cursor: - cr.commit() - if not ids: - break - offset = 0 - ids = [] - while True: - report_ids = [] - ids = procurement_obj.search(cr, uid, [('state', '=', 'confirmed'), ('procure_method', '=', 'make_to_stock')], offset=offset) - for proc in procurement_obj.browse(cr, uid, ids): - if maxdate >= proc.date_planned: - self.signal_button_check(cr, uid, [proc.id]) - report_ids.append(proc.id) - - if use_new_cursor: - cr.commit() - offset += len(ids) - if not ids: break - - if use_new_cursor: - cr.commit() - finally: - if use_new_cursor: - try: - cr.close() - except Exception: - pass - return {} - - def _prepare_automatic_op_procurement(self, cr, uid, product, warehouse, location_id, context=None): - return {'name': _('Automatic OP: %s') % (product.name,), - 'origin': _('SCHEDULER'), - 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT), - 'product_id': product.id, - 'product_qty': -product.virtual_available, - 'product_uom': product.uom_id.id, - 'location_id': location_id, - 'company_id': warehouse.company_id.id, - 'procure_method': 'make_to_order',} - - def create_automatic_op(self, cr, uid, context=None): - """ - Create procurement of virtual stock < 0 - - @param self: The object pointer - @param cr: The current row, from the database cursor, - @param uid: The current user ID for security checks - @param context: A standard dictionary for contextual values - @return: Dictionary of values - """ - if context is None: - context = {} - product_obj = self.pool.get('product.product') - proc_obj = self.pool.get('procurement.order') - warehouse_obj = self.pool.get('stock.warehouse') - - warehouse_ids = warehouse_obj.search(cr, uid, [], context=context) - products_ids = product_obj.search(cr, uid, [], order='id', context=context) - - for warehouse in warehouse_obj.browse(cr, uid, warehouse_ids, context=context): - context['warehouse'] = warehouse - # Here we check products availability. - # We use the method 'read' for performance reasons, because using the method 'browse' may crash the server. - for product_read in product_obj.read(cr, uid, products_ids, ['virtual_available'], context=context): - if product_read['virtual_available'] >= 0.0: - continue - - product = product_obj.browse(cr, uid, [product_read['id']], context=context)[0] - if product.supply_method == 'buy': - location_id = warehouse.lot_input_id.id - elif product.supply_method == 'produce': - location_id = warehouse.lot_stock_id.id - else: - continue - proc_id = proc_obj.create(cr, uid, - self._prepare_automatic_op_procurement(cr, uid, product, warehouse, location_id, context=context), - context=context) - self.signal_button_confirm(cr, uid, [proc_id]) - self.signal_button_check(cr, uid, [proc_id]) - return True - - def _get_orderpoint_date_planned(self, cr, uid, orderpoint, start_date, context=None): - date_planned = start_date + \ - relativedelta(days=orderpoint.product_id.seller_delay or 0.0) - return date_planned.strftime(DEFAULT_SERVER_DATE_FORMAT) - - def _prepare_orderpoint_procurement(self, cr, uid, orderpoint, product_qty, context=None): - return {'name': orderpoint.name, - 'date_planned': self._get_orderpoint_date_planned(cr, uid, orderpoint, datetime.today(), context=context), - 'product_id': orderpoint.product_id.id, - 'product_qty': product_qty, - 'company_id': orderpoint.company_id.id, - 'product_uom': orderpoint.product_uom.id, - 'location_id': orderpoint.location_id.id, - 'procure_method': 'make_to_order', - 'origin': orderpoint.name} - - def _product_virtual_get(self, cr, uid, order_point): - location_obj = self.pool.get('stock.location') - return location_obj._product_virtual_get(cr, uid, - order_point.location_id.id, [order_point.product_id.id], - {'uom': order_point.product_uom.id})[order_point.product_id.id] - - def _procure_orderpoint_confirm(self, cr, uid, automatic=False,\ - use_new_cursor=False, context=None, user_id=False): - ''' - Create procurement based on Orderpoint - use_new_cursor: False or the dbname - - @param self: The object pointer - @param cr: The current row, from the database cursor, - @param user_id: The current user ID for security checks - @param context: A standard dictionary for contextual values - @param param: False or the dbname - @return: Dictionary of values - """ - ''' - if context is None: - context = {} - if use_new_cursor: - cr = openerp.registry(use_new_cursor).cursor() - orderpoint_obj = self.pool.get('stock.warehouse.orderpoint') - - procurement_obj = self.pool.get('procurement.order') - offset = 0 - ids = [1] - if automatic: - self.create_automatic_op(cr, uid, context=context) - while ids: - ids = orderpoint_obj.search(cr, uid, [], offset=offset, limit=100) - for op in orderpoint_obj.browse(cr, uid, ids, context=context): - prods = self._product_virtual_get(cr, uid, op) - if prods is None: - continue - if prods < op.product_min_qty: - qty = max(op.product_min_qty, op.product_max_qty)-prods - - reste = qty % op.qty_multiple - if reste > 0: - qty += op.qty_multiple - reste - - if qty <= 0: - continue - if op.product_id.type not in ('consu'): - if op.procurement_draft_ids: - # Check draft procurement related to this order point - pro_ids = [x.id for x in op.procurement_draft_ids] - procure_datas = procurement_obj.read( - cr, uid, pro_ids, ['id', 'product_qty'], context=context) - to_generate = qty - for proc_data in procure_datas: - if to_generate >= proc_data['product_qty']: - self.signal_button_confirm(cr, uid, [proc_data['id']]) - procurement_obj.write(cr, uid, [proc_data['id']], {'origin': op.name}, context=context) - to_generate -= proc_data['product_qty'] - if not to_generate: - break - qty = to_generate - - if qty: - proc_id = procurement_obj.create(cr, uid, - self._prepare_orderpoint_procurement(cr, uid, op, qty, context=context), - context=context) - self.signal_button_confirm(cr, uid, [proc_id]) - self.signal_button_check(cr, uid, [proc_id]) - orderpoint_obj.write(cr, uid, [op.id], - {'procurement_id': proc_id}, context=context) - offset += len(ids) - if use_new_cursor: - cr.commit() - if use_new_cursor: - cr.commit() - cr.close() - return {} - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/procurement/security/ir.model.access.csv b/addons/procurement/security/ir.model.access.csv index 0d5f22895e4..c1c5c46cca3 100644 --- a/addons/procurement/security/ir.model.access.csv +++ b/addons/procurement/security/ir.model.access.csv @@ -1,9 +1,4 @@ id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink -access_procurement,procurement.order,model_procurement_order,base.group_user,1,0,0,0 -access_procurement_stock_user,procurement.order stock.user,model_procurement_order,stock.group_stock_user,1,1,1,1 -access_stock_warehouse_orderpoint,stock.warehouse.orderpoint,model_stock_warehouse_orderpoint,stock.group_stock_user,1,0,0,0 -access_stock_warehouse_orderpoint_system,stock.warehouse.orderpoint system,model_stock_warehouse_orderpoint,stock.group_stock_manager,1,1,1,1 -access_mrp_property_group,mrp.property.group,model_mrp_property_group,stock.group_stock_manager,1,1,1,1 -access_mrp_property,mrp.property,model_mrp_property,stock.group_stock_manager,1,1,1,1 -access_mrp_property_group,mrp.property.group,model_mrp_property_group,base.group_user,1,0,0,0 -access_mrp_property,mrp.property,model_mrp_property,base.group_user,1,0,0,0 +access_procurement,procurement.order,model_procurement_order,base.group_user,1,1,1,0 +access_procurement_group,procurement.group,model_procurement_group,base.group_user,1,1,1,0 +access_procurement_rule,procurement.rule,model_procurement_rule,base.group_user,1,1,1,0 diff --git a/addons/procurement/security/procurement_security.xml b/addons/procurement/security/procurement_security.xml index 2362db4c355..c19852d2f60 100644 --- a/addons/procurement/security/procurement_security.xml +++ b/addons/procurement/security/procurement_security.xml @@ -9,12 +9,12 @@ ['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)]
- - stock_warehouse.orderpoint multi-company - - - ['|',('company_id','child_of',[user.company_id.id]),('company_id','=',False)] - + + product_pulled_flow multi-company + + + ['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])] + diff --git a/addons/procurement/test/procurement.yml b/addons/procurement/test/procurement.yml index 17c2cdbc6d0..353bcaff3e8 100644 --- a/addons/procurement/test/procurement.yml +++ b/addons/procurement/test/procurement.yml @@ -1,89 +1,22 @@ - - For test the procurement process, First I have to apply a minimum stock rule on product + I create a procurement - - I create minimum stock rule for product. -- - !record {model: stock.warehouse.orderpoint, id: stock_warehouse_orderpoint_op0}: + !record {model: procurement.order, id: procurement_order0}: company_id: base.main_company - location_id: stock.stock_location_stock - logic: max - name: OP/00008 + name: Procurement Test product_id: product.product_product_32 - product_max_qty: 15.0 - product_min_qty: 5.0 + product_qty: 15.0 product_uom: product.product_uom_unit - qty_multiple: 1 - warehouse_id: stock.warehouse0 -- - Check product quantity and update it, if needed for apply a minimum stock rule. -- - !python {model: product.product}: | - product = self.browse(cr, uid, ref('product.product_product_32')) - if product.virtual_available < 5.0: - change_qty = self.pool.get('stock.change.product.qty') - id = change_qty.create(cr, uid, {'location_id' : ref('stock.stock_location_stock'), 'new_quantity': 4, 'product_id': product.id}) - change_qty.change_product_qty(cr, uid, [id], {'active_model':'product.product', 'active_id': product.id, 'active_ids':[product.id]}) - assert product.qty_available == 4,"Product quantity is not updated." - assert product.virtual_available < 5.0,'Virtual stock have more quantities.' + product_uos_qty: 15.0 + product_uos: product.product_uom_unit - I run the scheduler. - !python {model: procurement.order}: | self.run_scheduler(cr, uid) - - I check that procurement order is based on minimum stock rule. + I check that procurement order is in exception, as at first there isn't any suitable rule - !python {model: procurement.order}: | - proc_ids = self.search(cr, uid, [('product_id','=', ref('product.product_product_32'))]) - assert proc_ids, 'No Procurement created.' - proc_order = self.browse(cr, uid, proc_ids)[0] - assert proc_order.product_qty == 11.0,"Procurement product quantity is not corresponded." -- - I check product quantity. -- - !python {model: product.product}: | - product = self.browse(cr, uid, ref('product.product_product_32')) - assert product.virtual_available == 15.0,"After run the scheduler product's virtual stock is not updated." -- - For test the Procurement Request wizard, Again I have to update product quantity. -- - !python {model: product.product}: | - mk_procure = self.pool.get('make.procurement') - procur_order = self.pool.get('procurement.order') - product = self.browse(cr, uid, ref('product.product_product_32')) - - context.update({'active_model': 'product.product','active_id':ref('product.product_product_32')}) - values = {'warehouse_id': ref('base.main_company'), 'uom_id': ref('product.product_uom_unit'), 'qty': 5} - id = mk_procure.create(cr, uid, values, context) - procurement = mk_procure.make_procurement(cr, uid, [id], context) - assert product.virtual_available == 20.0, 'Virtual stock should be updated' - - proc_id = procurement.get('res_id') - for procurement in procur_order.browse(cr, uid, [proc_id]): - if procurement.state == 'confirmed': - assert procurement.state == 'confirmed',"Procurement state should be 'Confirmed'." - assert procurement.product_id.id == ref('product.product_product_32'),"Product is not correspond." - assert procurement.product_qty == 5,"Product Quantity is not correspond." - assert procurement.product_uom.id == ref('product.product_uom_unit'),"Product's UOM is not correspond." - context.update({'proc': proc_id}) -- - I run the scheduler. -- - !python {model: procurement.order}: | - self.run_scheduler(cr, uid) -- - I check the current state of procurement. -- - !python {model: procurement.order}: | - proc_id = context.get('proc') - proc = self.browse(cr, uid, [proc_id])[0] - assert proc.state == 'ready' or 'exception',"Procurement should be in Ready or Exception state" -#- -# I compute minimum stock. -# [Note. Commented out because it spawns a thread that may query the db after tests have been reverted.] -#- -# !python {model: procurement.orderpoint.compute}: | -# proc_id = context.get('proc') -# context.update({'active_model': 'procurement.order', 'active_id': proc_id}) -# id = self.create(cr, uid, {'automatic': True}, context) -# self.procure_calculation(cr, uid, [id], context) + proc_order = self.browse(cr, uid, ref('procurement_order0'), context=context) + assert proc_order.state == 'exception' diff --git a/addons/procurement/wizard/__init__.py b/addons/procurement/wizard/__init__.py index ae70ffbf941..5edd432ddff 100644 --- a/addons/procurement/wizard/__init__.py +++ b/addons/procurement/wizard/__init__.py @@ -19,9 +19,6 @@ # ############################################################################## -import orderpoint_procurement -import mrp_procurement import schedulers_all -import make_procurement_product # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/procurement/wizard/mrp_procurement.py b/addons/procurement/wizard/mrp_procurement.py deleted file mode 100644 index fd5a9b530b6..00000000000 --- a/addons/procurement/wizard/mrp_procurement.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2010 Tiny SPRL (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## - -import threading -from openerp.osv import fields, osv - -class procurement_compute(osv.osv_memory): - _name = 'procurement.order.compute' - _description = 'Compute Procurement' - - def _procure_calculation_procure(self, cr, uid, ids, context=None): - try: - proc_obj = self.pool.get('procurement.order') - proc_obj._procure_confirm(cr, uid, use_new_cursor=cr.dbname, context=context) - finally: - pass - return {} - - def procure_calculation(self, cr, uid, ids, context=None): - """ - @param self: The object pointer. - @param cr: A database cursor - @param uid: ID of the user currently logged in - @param ids: List of IDs selected - @param context: A standard dictionary - """ - threaded_calculation = threading.Thread(target=self._procure_calculation_procure, args=(cr, uid, ids, context)) - threaded_calculation.start() - return {} - - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: - diff --git a/addons/procurement/wizard/mrp_procurement_view.xml b/addons/procurement/wizard/mrp_procurement_view.xml deleted file mode 100644 index 89ba76d291b..00000000000 --- a/addons/procurement/wizard/mrp_procurement_view.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - Compute Procurements - procurement.order.compute - -
- - -
-
-
-
-
- -
-
diff --git a/addons/procurement/wizard/schedulers_all.py b/addons/procurement/wizard/schedulers_all.py index c0f1cfcc2df..5c712b3af38 100644 --- a/addons/procurement/wizard/schedulers_all.py +++ b/addons/procurement/wizard/schedulers_all.py @@ -21,20 +21,12 @@ import threading -from openerp.osv import fields, osv +from openerp.osv import osv class procurement_compute_all(osv.osv_memory): _name = 'procurement.order.compute.all' _description = 'Compute all schedulers' - _columns = { - 'automatic': fields.boolean('Automatic orderpoint',help='Triggers an automatic procurement for all products that have a virtual stock under 0. You should probably not use this option, we suggest using a MTO configuration on products.'), - } - - _defaults = { - 'automatic': lambda *a: False, - } - def _procure_calculation_all(self, cr, uid, ids, context=None): """ @param self: The object pointer. @@ -46,9 +38,7 @@ class procurement_compute_all(osv.osv_memory): proc_obj = self.pool.get('procurement.order') #As this function is in a new thread, i need to open a new cursor, because the old one may be closed new_cr = self.pool.cursor() - for proc in self.browse(new_cr, uid, ids, context=context): - proc_obj.run_scheduler(new_cr, uid, automatic=proc.automatic, use_new_cursor=new_cr.dbname,\ - context=context) + proc_obj.run_scheduler(new_cr, uid, use_new_cursor=new_cr.dbname, context=context) #close the new cursor new_cr.close() return {} diff --git a/addons/procurement/wizard/schedulers_all_view.xml b/addons/procurement/wizard/schedulers_all_view.xml index 321f05bb223..311cf6d5c6a 100644 --- a/addons/procurement/wizard/schedulers_all_view.xml +++ b/addons/procurement/wizard/schedulers_all_view.xml @@ -9,9 +9,9 @@ procurement.order.compute.all
- - - +

+ Compute all procurements in the background. +

+ +
+
+ + + Compute Price Wizard + ir.actions.act_window + wizard.price + form + form + + new + + + + diff --git a/addons/product_extended/security/ir.model.access.csv b/addons/product_extended/security/ir.model.access.csv new file mode 100644 index 00000000000..8678ab0d737 --- /dev/null +++ b/addons/product_extended/security/ir.model.access.csv @@ -0,0 +1,3 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_wizard_price_all,wizard.price all,model_wizard_price,,1,1,1,1 + diff --git a/addons/product_extended/wizard/__init__.py b/addons/product_extended/wizard/__init__.py new file mode 100644 index 00000000000..d89612cccd7 --- /dev/null +++ b/addons/product_extended/wizard/__init__.py @@ -0,0 +1,25 @@ +# -*- encoding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved +# $Id$ +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +import wizard_price + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: + diff --git a/addons/product_extended/wizard/wizard_price.py b/addons/product_extended/wizard/wizard_price.py new file mode 100644 index 00000000000..ddbeff9b9d0 --- /dev/null +++ b/addons/product_extended/wizard/wizard_price.py @@ -0,0 +1,58 @@ +# -*- encoding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# Copyright (C) 2010-2011 OpenERP S.A. (). +# $Id$ +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## + +from openerp.osv import fields, osv + + +class wizard_price(osv.osv): + _name = "wizard.price" + _description = "Compute price wizard" + _columns = { + 'info_field': fields.text('Info', readonly=True), + 'real_time_accounting': fields.boolean("Generate accounting entries when real-time"), + 'recursive': fields.boolean("Change prices of child BoMs too"), + } + + def default_get(self, cr, uid, fields, context=None): + res = super(wizard_price, self).default_get(cr, uid, fields, context=context) + product_pool = self.pool.get('product.product') + product_obj = product_pool.browse(cr, uid, context.get('active_id', False)) + if context is None: + context = {} + rec_id = context and context.get('active_id', False) + assert rec_id, _('Active ID is not set in Context.') + res['info_field'] = str(product_pool.compute_price(cr, uid, [product_obj.id], test=True, context=context)) + return res + + def compute_from_bom(self, cr, uid, ids, context=None): + assert len(ids) == 1 + if context is None: + context = {} + rec_id = context and context.get('active_id', False) + assert rec_id, _('Active ID is not set in Context.') + prod_obj = self.pool.get('product.product') + res = self.browse(cr, uid, ids, context=context) + prod = prod_obj.browse(cr, uid, rec_id, context=context) + prod_obj.compute_price(cr, uid, [prod.id], real_time_accounting=res[0].real_time_accounting, recursive=res[0].recursive, test=False, context=context) + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/product_margin/product_margin.py b/addons/product_margin/product_margin.py index c344abb3410..c7f3219b1be 100644 --- a/addons/product_margin/product_margin.py +++ b/addons/product_margin/product_margin.py @@ -51,36 +51,45 @@ class product_product(osv.osv): states = ('open', 'paid') elif invoice_state == 'draft_open_paid': states = ('draft', 'open', 'paid') + if "force_company" in context: + company_id = context['force_company'] + else: + company_id = self.pool.get("res.users").browse(cr, uid, uid, context=context).company_id.id + #Cost price is calculated afterwards as it is a property sqlstr="""select - sum(l.price_unit * l.quantity)/sum(nullif(l.quantity,0)) as avg_unit_price, - sum(l.quantity) as num_qty, + sum(l.price_unit * l.quantity)/sum(nullif(l.quantity * pu.factor / pu2.factor,0)) as avg_unit_price, + sum(l.quantity * pu.factor / pu2.factor) as num_qty, sum(l.quantity * (l.price_subtotal/(nullif(l.quantity,0)))) as total, - sum(l.quantity * pt.list_price) as sale_expected, - sum(l.quantity * pt.standard_price) as normal_cost + sum(l.quantity * pu.factor * pt.list_price / pu2.factor) as sale_expected from account_invoice_line l left join account_invoice i on (l.invoice_id = i.id) left join product_product product on (product.id=l.product_id) - left join product_template pt on (pt.id=product.product_tmpl_id) - where l.product_id = %s and i.state in %s and i.type IN %s and (i.date_invoice IS NULL or (i.date_invoice>=%s and i.date_invoice<=%s)) + left join product_template pt on (pt.id = l.product_id) + left join product_uom pu on (pt.uom_id = pu.id) + left join product_uom pu2 on (l.uos_id = pu2.id) + where l.product_id = %s and i.state in %s and i.type IN %s and (i.date_invoice IS NULL or (i.date_invoice>=%s and i.date_invoice<=%s and i.company_id=%s)) """ invoice_types = ('out_invoice', 'in_refund') - cr.execute(sqlstr, (val.id, states, invoice_types, date_from, date_to)) + cr.execute(sqlstr, (val.id, states, invoice_types, date_from, date_to, company_id)) result = cr.fetchall()[0] res[val.id]['sale_avg_price'] = result[0] and result[0] or 0.0 res[val.id]['sale_num_invoiced'] = result[1] and result[1] or 0.0 res[val.id]['turnover'] = result[2] and result[2] or 0.0 res[val.id]['sale_expected'] = result[3] and result[3] or 0.0 res[val.id]['sales_gap'] = res[val.id]['sale_expected']-res[val.id]['turnover'] - + prod_obj = self.pool.get("product.product") + ctx = context.copy() + ctx['force_company'] = company_id + prod = prod_obj.browse(cr, uid, val.id, context=ctx) invoice_types = ('in_invoice', 'out_refund') - cr.execute(sqlstr, (val.id, states, invoice_types, date_from, date_to)) + cr.execute(sqlstr, (val.id, states, invoice_types, date_from, date_to, company_id)) result = cr.fetchall()[0] res[val.id]['purchase_avg_price'] = result[0] and result[0] or 0.0 res[val.id]['purchase_num_invoiced'] = result[1] and result[1] or 0.0 res[val.id]['total_cost'] = result[2] and result[2] or 0.0 - res[val.id]['normal_cost'] = result[4] and result[4] or 0.0 - res[val.id]['purchase_gap'] = res[val.id]['normal_cost']-res[val.id]['total_cost'] + res[val.id]['normal_cost'] = prod.standard_price * res[val.id]['purchase_num_invoiced'] + res[val.id]['purchase_gap'] = res[val.id]['normal_cost'] - res[val.id]['total_cost'] if 'total_margin' in field_names: res[val.id]['total_margin'] = res[val.id]['turnover'] - res[val.id]['total_cost'] diff --git a/addons/project/project.py b/addons/project/project.py index e074d241cef..883db8fd0be 100644 --- a/addons/project/project.py +++ b/addons/project/project.py @@ -565,6 +565,7 @@ class task(osv.osv): }, 'kanban_state': { 'project.mt_task_blocked': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'blocked', + 'project.mt_task_ready': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'done', }, } @@ -740,18 +741,18 @@ class task(osv.osv): 'active': fields.function(_is_template, store=True, string='Not a Template Task', type='boolean', help="This field is computed automatically and have the same behavior than the boolean 'active' field: if the task is linked to a template or unactivated project, it will be hidden unless specifically asked."), 'name': fields.char('Task Summary', track_visibility='onchange', size=128, required=True, select=True), 'description': fields.text('Description'), - 'priority': fields.selection([('4','Very Low'), ('3','Low'), ('2','Medium'), ('1','Important'), ('0','Very important')], 'Priority', select=True), + 'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority', select=True), 'sequence': fields.integer('Sequence', select=True, help="Gives the sequence order when displaying a list of tasks."), 'stage_id': fields.many2one('project.task.type', 'Stage', track_visibility='onchange', select=True, domain="[('project_ids', '=', project_id)]"), 'categ_ids': fields.many2many('project.category', string='Tags'), - 'kanban_state': fields.selection([('normal', 'Normal'),('blocked', 'Blocked'),('done', 'Ready for next stage')], 'Kanban State', + 'kanban_state': fields.selection([('normal', 'In Progress'),('blocked', 'Blocked'),('done', 'Ready for next stage')], 'Kanban State', track_visibility='onchange', help="A task's kanban state indicates special situations affecting it:\n" " * Normal is the default situation\n" " * Blocked indicates something is preventing the progress of this task\n" " * Ready for next stage indicates the task is ready to be pulled to the next stage", - readonly=True, required=False), + required=False), 'create_date': fields.datetime('Create Date', readonly=True, select=True), 'write_date': fields.datetime('Last Modification Date', readonly=True, select=True), #not displayed in the view but it might be useful with base_action_rule module (and it needs to be defined first for that) 'date_start': fields.datetime('Starting Date',select=True), @@ -799,7 +800,7 @@ class task(osv.osv): 'project_id': _get_default_project_id, 'date_last_stage_update': fields.datetime.now, 'kanban_state': 'normal', - 'priority': '2', + 'priority': '1', 'progress': 0, 'sequence': 10, 'active': True, @@ -808,17 +809,7 @@ class task(osv.osv): 'partner_id': lambda self, cr, uid, ctx=None: self._get_default_partner(cr, uid, context=ctx), } _order = "priority, sequence, date_start, name, id" - - def set_high_priority(self, cr, uid, ids, *args): - """Set task priority to high - """ - return self.write(cr, uid, ids, {'priority' : '0'}) - - def set_normal_priority(self, cr, uid, ids, *args): - """Set task priority to normal - """ - return self.write(cr, uid, ids, {'priority' : '2'}) - + def _check_recursion(self, cr, uid, ids, context=None): for id in ids: visited_branch = set() @@ -1003,16 +994,6 @@ class task(osv.osv): def set_remaining_time_10(self, cr, uid, ids, context=None): return self.set_remaining_time(cr, uid, ids, 10.0, context) - def set_kanban_state_blocked(self, cr, uid, ids, context=None): - return self.write(cr, uid, ids, {'kanban_state': 'blocked'}, context=context) - - def set_kanban_state_normal(self, cr, uid, ids, context=None): - return self.write(cr, uid, ids, {'kanban_state': 'normal'}, context=context) - - def set_kanban_state_done(self, cr, uid, ids, context=None): - self.write(cr, uid, ids, {'kanban_state': 'done'}, context=context) - return False - def _store_history(self, cr, uid, ids, context=None): for task in self.browse(cr, uid, ids, context=context): self.pool.get('project.task.history').create(cr, uid, { diff --git a/addons/project/project_data.xml b/addons/project/project_data.xml index 95a76d8988e..f98ee9aaea6 100644 --- a/addons/project/project_data.xml +++ b/addons/project/project_data.xml @@ -93,6 +93,12 @@ Task blocked
+ + Task Ready for Next Stage + project.task + + Task Ready for Next Stage + Stage Changed project.task diff --git a/addons/project/project_demo.xml b/addons/project/project_demo.xml index ff225c46e10..54f78ba8c8b 100644 --- a/addons/project/project_demo.xml +++ b/addons/project/project_demo.xml @@ -110,7 +110,7 @@ - 4 + 0 Prepare Requirements Document @@ -120,7 +120,7 @@ - 4 + 0 Make SRS @@ -129,7 +129,7 @@ - 4 + 0 Budget Planning @@ -140,7 +140,7 @@ - 4 + 0 Develop module for Sale Management Use the account_budget module diff --git a/addons/project/project_view.xml b/addons/project/project_view.xml index 5bd669cb14f..b6a839edcf6 100644 --- a/addons/project/project_view.xml +++ b/addons/project/project_view.xml @@ -377,12 +377,11 @@ options="{'fold_field': 'fold'}"/> +
+ +

- -

@@ -444,7 +443,7 @@ - + @@ -515,16 +514,6 @@ oe_kanban_text_red -
- - - - - 7 - 7 - - -
+
+ +
+ + +
+
diff --git a/addons/project/report/project_report.py b/addons/project/report/project_report.py index 5a473469b2d..e3f2cd6668b 100644 --- a/addons/project/report/project_report.py +++ b/addons/project/report/project_report.py @@ -48,7 +48,7 @@ class report_project_task_user(osv.osv): help="Number of Days to Open the task"), 'delay_endings_days': fields.float('Overpassed Deadline', digits=(16,2), readonly=True), 'nbr': fields.integer('# of tasks', readonly=True), - 'priority': fields.selection([('4', 'Very Low'), ('3', 'Low'), ('2', 'Medium'), ('1', 'Urgent'), ('0', 'Very urgent')], + 'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], string='Priority', readonly=True), 'state': fields.selection([('draft', 'Draft'), ('open', 'In Progress'), ('pending', 'Pending'), ('cancelled', 'Cancelled'), ('done', 'Done')],'Status', readonly=True), 'company_id': fields.many2one('res.company', 'Company', readonly=True), diff --git a/addons/project_issue/project_issue.py b/addons/project_issue/project_issue.py index e07d4dbe957..6c06f14d5fa 100644 --- a/addons/project_issue/project_issue.py +++ b/addons/project_issue/project_issue.py @@ -57,6 +57,7 @@ class project_issue(osv.Model): }, 'kanban_state': { 'project_issue.mt_issue_blocked': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'blocked', + 'project_issue.mt_issue_ready': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'done', }, } @@ -250,7 +251,7 @@ class project_issue(osv.Model): " * Normal is the default situation\n" " * Blocked indicates something is preventing the progress of this issue\n" " * Ready for next stage indicates the issue is ready to be pulled to the next stage", - readonly=True, required=False), + required=False), 'email_from': fields.char('Email', size=128, help="These people will receive email.", select=1), 'email_cc': fields.char('Watchers Emails', size=256, help="These email addresses will be added to the CC field of all inbound and outbound emails for this record before being sent. Separate multiple email addresses with a comma"), 'date_open': fields.datetime('Opened', readonly=True,select=True), @@ -260,7 +261,7 @@ class project_issue(osv.Model): 'date_last_stage_update': fields.datetime('Last Stage Update', select=True), 'channel_id': fields.many2one('crm.case.channel', 'Channel', help="Communication channel."), 'categ_ids': fields.many2many('project.category', string='Tags'), - 'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority', select=True), + 'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority', select=True), 'version_id': fields.many2one('project.issue.version', 'Version'), 'stage_id': fields.many2one ('project.task.type', 'Stage', track_visibility='onchange', select=True, @@ -295,7 +296,7 @@ class project_issue(osv.Model): 'active': 1, 'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c), 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.helpdesk', context=c), - 'priority': crm.AVAILABLE_PRIORITIES[2][0], + 'priority': '1', 'kanban_state': 'normal', 'date_last_stage_update': fields.datetime.now, 'user_id': lambda obj, cr, uid, context: uid, @@ -305,19 +306,6 @@ class project_issue(osv.Model): 'stage_id': _read_group_stage_ids } - def set_priority(self, cr, uid, ids, priority, *args): - return self.write(cr, uid, ids, {'priority' : priority}) - - def set_high_priority(self, cr, uid, ids, *args): - """Set lead priority to high - """ - return self.set_priority(cr, uid, ids, '1') - - def set_normal_priority(self, cr, uid, ids, *args): - """Set lead priority to normal - """ - return self.set_priority(cr, uid, ids, '3') - def copy(self, cr, uid, id, default=None, context=None): issue = self.read(cr, uid, id, ['name'], context=context) if not default: @@ -375,15 +363,6 @@ class project_issue(osv.Model): # Stage management # ------------------------------------------------------- - def set_kanban_state_blocked(self, cr, uid, ids, context=None): - return self.write(cr, uid, ids, {'kanban_state': 'blocked'}, context=context) - - def set_kanban_state_normal(self, cr, uid, ids, context=None): - return self.write(cr, uid, ids, {'kanban_state': 'normal'}, context=context) - - def set_kanban_state_done(self, cr, uid, ids, context=None): - return self.write(cr, uid, ids, {'kanban_state': 'done'}, context=context) - def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None): """ Override of the base.stage method Parameter of the stage search taken from the issue: diff --git a/addons/project_issue/project_issue_data.xml b/addons/project_issue/project_issue_data.xml index d60106dffd2..fced1bd8c72 100644 --- a/addons/project_issue/project_issue_data.xml +++ b/addons/project_issue/project_issue_data.xml @@ -48,6 +48,12 @@ Access all issues from the top Project menu, and access the issues of a specific Issue blocked
+ + Issue Ready for Next Stage + project.issue + + Issue Ready for Next Stage + Stage Changed project.issue diff --git a/addons/project_issue/project_issue_demo.xml b/addons/project_issue/project_issue_demo.xml index e16b8702551..e19141aab59 100644 --- a/addons/project_issue/project_issue_demo.xml +++ b/addons/project_issue/project_issue_demo.xml @@ -35,7 +35,7 @@ - 5 + 0 @@ -51,7 +51,7 @@ - 3 + 1 @@ -64,7 +64,7 @@ - 4 + 0 @@ -79,7 +79,7 @@ - 3 + 1 @@ -92,7 +92,7 @@ - 3 + 1 @@ -105,7 +105,7 @@ - 3 + 1 @@ -172,7 +172,7 @@ - 4 + 0 @@ -199,7 +199,7 @@ - 3 + 1 @@ -213,7 +213,7 @@ - 3 + 1 @@ -226,7 +226,7 @@ - 4 + 0 diff --git a/addons/project_issue/project_issue_view.xml b/addons/project_issue/project_issue_view.xml index 247acbb696f..4e53c056772 100644 --- a/addons/project_issue/project_issue_view.xml +++ b/addons/project_issue/project_issue_view.xml @@ -52,13 +52,12 @@ options="{'fold_field': 'fold'}"/> +
+ +
+ + + + + Purchase Order - Send by Email + ${object.validator.email or ''} + ${object.company_id.name} Order (Ref ${object.name or 'n/a' }) + ${object.partner_id.id} + + + + PO_${(object.name or '').replace('/','_')} + ${object.partner_id.lang} + + +

Hello ${object.partner_id.name},

+ +

Here is a ${object.state in ('draft', 'sent') and 'request for quotation' or 'purchase order confirmation'} from ${object.company_id.name}:

+

  REFERENCES
  Order number: ${object.name}
diff --git a/addons/purchase/purchase.py b/addons/purchase/purchase.py index 457523d6d97..6ff6feae376 100644 --- a/addons/purchase/purchase.py +++ b/addons/purchase/purchase.py @@ -19,13 +19,12 @@ # ############################################################################## -import time import pytz from openerp import SUPERUSER_ID, workflow from datetime import datetime from dateutil.relativedelta import relativedelta from operator import attrgetter - +from openerp.tools.safe_eval import safe_eval as eval from openerp.osv import fields, osv from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp @@ -102,13 +101,13 @@ class purchase_order(osv.osv): for id in ids: res[id] = [0.0,0.0] cr.execute('''SELECT - p.purchase_id,sum(m.product_qty), m.state + p.order_id, sum(m.product_qty), m.state FROM stock_move m LEFT JOIN - stock_picking p on (p.id=m.picking_id) + purchase_order_line p on (p.id=m.purchase_line_id) WHERE - p.purchase_id IN %s GROUP BY m.state, p.purchase_id''',(tuple(ids),)) + p.order_id IN %s GROUP BY m.state, p.order_id''',(tuple(ids),)) for oid,nbr,state in cr.fetchall(): if state=='cancel': continue @@ -147,6 +146,26 @@ class purchase_order(osv.osv): limit=1) return res and res[0] or False + def _get_picking_in(self, cr, uid, context=None): + obj_data = self.pool.get('ir.model.data') + return obj_data.get_object_reference(cr, uid, 'stock','picking_type_in') and obj_data.get_object_reference(cr, uid, 'stock','picking_type_in')[1] or False + + def _get_picking_ids(self, cr, uid, ids, field_names, args, context=None): + res = {} + for po_id in ids: + res[po_id] = [] + query = """ + SELECT picking_id, po.id FROM stock_picking p, stock_move m, purchase_order_line pol, purchase_order po + WHERE po.id in %s and po.id = pol.order_id and pol.id = m.purchase_line_id and m.picking_id = p.id + GROUP BY picking_id, po.id + + """ + cr.execute(query, (tuple(ids), )) + picks = cr.fetchall() + for pick_id, po_id in picks: + res[po_id].append(pick_id) + return res + def _count_all(self, cr, uid, ids, field_name, arg, context=None): return { purchase.id: { @@ -158,9 +177,10 @@ class purchase_order(osv.osv): STATE_SELECTION = [ ('draft', 'Draft PO'), - ('sent', 'RFQ Sent'), + ('sent', 'RFQ'), + ('bid', 'Bid Received'), ('confirmed', 'Waiting Approval'), - ('approved', 'Purchase Order'), + ('approved', 'Purchase Confirmed'), ('except_picking', 'Shipping Exception'), ('except_invoice', 'Invoice Exception'), ('done', 'Done'), @@ -179,7 +199,7 @@ class purchase_order(osv.osv): help="Reference of the document that generated this purchase order request; a sales order or an internal procurement request." ), 'partner_ref': fields.char('Supplier Reference', states={'confirmed':[('readonly',True)], 'approved':[('readonly',True)],'done':[('readonly',True)]}, size=64, - help="Reference of the sales order or quotation sent by your supplier. It's mainly used to do the matching when you receive the products as this reference is usually written on the delivery order sent by your supplier."), + help="Reference of the sales order or bid sent by your supplier. It's mainly used to do the matching when you receive the products as this reference is usually written on the delivery order sent by your supplier."), 'date_order':fields.date('Order Date', required=True, states={'confirmed':[('readonly',True)], 'approved':[('readonly',True)]}, select=True, help="Date on which this document has been created."), 'date_approve':fields.date('Date Approved', readonly=1, select=True, help="Date on which purchase order has been approved"), 'partner_id':fields.many2one('res.partner', 'Supplier', required=True, states={'confirmed':[('readonly',True)], 'approved':[('readonly',True)],'done':[('readonly',True)]}, @@ -189,16 +209,15 @@ class purchase_order(osv.osv): help="Put an address if you want to deliver directly from the supplier to the customer. " \ "Otherwise, keep empty to deliver to your own company." ), - 'warehouse_id': fields.many2one('stock.warehouse', 'Destination Warehouse'), 'location_id': fields.many2one('stock.location', 'Destination', required=True, domain=[('usage','<>','view')], states={'confirmed':[('readonly',True)], 'approved':[('readonly',True)],'done':[('readonly',True)]} ), 'pricelist_id':fields.many2one('product.pricelist', 'Pricelist', required=True, states={'confirmed':[('readonly',True)], 'approved':[('readonly',True)],'done':[('readonly',True)]}, help="The pricelist sets the currency used for this purchase order. It also computes the supplier price for the selected products/quantities."), 'currency_id': fields.many2one('res.currency','Currency', readonly=True, required=True,states={'draft': [('readonly', False)],'sent': [('readonly', False)]}), - 'state': fields.selection(STATE_SELECTION, 'Status', readonly=True, help="The status of the purchase order or the quotation request. A quotation is a purchase order in a 'Draft' status. Then the order has to be confirmed by the user, the status switch to 'Confirmed'. Then the supplier must confirm the order to change the status to 'Approved'. When the purchase order is paid and received, the status becomes 'Done'. If a cancel action occurs in the invoice or in the reception of goods, the status becomes in exception.", select=True), + 'state': fields.selection(STATE_SELECTION, 'Status', readonly=True, help="The status of the purchase order or the quotation request. A request for quotation is a purchase order in a 'Draft' status. Then the order has to be confirmed by the user, the status switch to 'Confirmed'. Then the supplier must confirm the order to change the status to 'Approved'. When the purchase order is paid and received, the status becomes 'Done'. If a cancel action occurs in the invoice or in the reception of goods, the status becomes in exception.", select=True), 'order_line': fields.one2many('purchase.order.line', 'order_id', 'Order Lines', states={'approved':[('readonly',True)],'done':[('readonly',True)]}), 'validator' : fields.many2one('res.users', 'Validated by', readonly=True), 'notes': fields.text('Terms and Conditions'), 'invoice_ids': fields.many2many('account.invoice', 'purchase_invoice_rel', 'purchase_id', 'invoice_id', 'Invoices', help="Invoices generated for a purchase order"), - 'picking_ids': fields.one2many('stock.picking.in', 'purchase_id', 'Picking List', readonly=True, help="This is the list of incoming shipments that have been generated for this purchase order."), + 'picking_ids': fields.function(_get_picking_ids, method=True, type='one2many', relation='stock.picking', string='Picking List', help="This is the list of reception operations that have been generated for this purchase order."), 'shipped':fields.boolean('Received', readonly=True, select=True, help="It indicates that a picking has been done"), 'shipped_rate': fields.function(_shipped_rate, string='Received Ratio', type='float'), 'invoiced': fields.function(_invoiced, string='Invoice Received', type='boolean', help="It indicates that an invoice has been paid"), @@ -214,24 +233,30 @@ class purchase_order(osv.osv): 'purchase.order.line': (_get_order, ['date_planned'], 10), } ), - 'amount_untaxed': fields.function(_amount_all, digits_compute= dp.get_precision('Account'), string='Untaxed Amount', + 'amount_untaxed': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Untaxed Amount', store={ 'purchase.order.line': (_get_order, None, 10), }, multi="sums", help="The amount without tax", track_visibility='always'), - 'amount_tax': fields.function(_amount_all, digits_compute= dp.get_precision('Account'), string='Taxes', + 'amount_tax': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Taxes', store={ 'purchase.order.line': (_get_order, None, 10), }, multi="sums", help="The tax amount"), - 'amount_total': fields.function(_amount_all, digits_compute= dp.get_precision('Account'), string='Total', + 'amount_total': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Total', store={ 'purchase.order.line': (_get_order, None, 10), - }, multi="sums",help="The total amount"), + }, multi="sums", help="The total amount"), 'fiscal_position': fields.many2one('account.fiscal.position', 'Fiscal Position'), 'payment_term_id': fields.many2one('account.payment.term', 'Payment Term'), - 'product_id': fields.related('order_line','product_id', type='many2one', relation='product.product', string='Product'), - 'create_uid': fields.many2one('res.users', 'Responsible'), - 'company_id': fields.many2one('res.company','Company',required=True,select=1, states={'confirmed':[('readonly',True)], 'approved':[('readonly',True)]}), + 'incoterm_id': fields.many2one('stock.incoterms', 'Incoterm', help="International Commercial Terms are a series of predefined commercial terms used in international transactions."), + 'product_id': fields.related('order_line', 'product_id', type='many2one', relation='product.product', string='Product'), + 'create_uid': fields.many2one('res.users', 'Responsible'), + 'company_id': fields.many2one('res.company', 'Company', required=True, select=1, states={'confirmed': [('readonly', True)], 'approved': [('readonly', True)]}), 'journal_id': fields.many2one('account.journal', 'Journal'), + 'bid_date': fields.date('Bid Received On', readonly=True, help="Date on which the bid was received"), + 'bid_validity': fields.date('Bid Valid Until', help="Date on which the bid expired"), + 'picking_type_id': fields.many2one('stock.picking.type', 'Deliver To', help="This will determine picking type of incoming shipment", required=True, + states={'confirmed': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)]}), + 'related_location_id': fields.related('picking_type_id', 'default_location_dest_id', type='many2one', relation='stock.location', string="Related location", store=True), 'shipment_count': fields.function(_count_all, type='integer', string='Incoming Shipments', multi=True), 'invoice_count': fields.function(_count_all, type='integer', string='Invoices', multi=True) } @@ -243,9 +268,10 @@ class purchase_order(osv.osv): 'invoice_method': 'order', 'invoiced': 0, 'pricelist_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').browse(cr, uid, context['partner_id']).property_product_pricelist_purchase.id, - 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'purchase.order', context=c), + 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'purchase.order', context=c), 'journal_id': _get_journal, - 'currency_id': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id + 'currency_id': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id, + 'picking_type_id': _get_picking_in, } _sql_constraints = [ ('name_uniq', 'unique(name, company_id)', 'Order Reference must be unique per Company!'), @@ -279,6 +305,20 @@ class purchase_order(osv.osv): return super(purchase_order, self).unlink(cr, uid, unlink_ids, context=context) + def set_order_line_status(self, cr, uid, ids, status, context=None): + line = self.pool.get('purchase.order.line') + order_line_ids = [] + proc_obj = self.pool.get('procurement.order') + for order in self.browse(cr, uid, ids, context=context): + order_line_ids += [po_line.id for po_line in order.order_line] + if order_line_ids: + line.write(cr, uid, order_line_ids, {'state': status}, context=context) + if order_line_ids and status == 'cancel': + procs = proc_obj.search(cr, uid, [('purchase_line_id', 'in', order_line_ids)], context=context) + if procs: + proc_obj.write(cr, uid, procs, {'state': 'exception'}, context=context) + return True + def button_dummy(self, cr, uid, ids, context=None): return True @@ -287,22 +327,26 @@ class purchase_order(osv.osv): return {} return {'value': {'currency_id': self.pool.get('product.pricelist').browse(cr, uid, pricelist_id, context=context).currency_id.id}} + #Destination address is used when dropshipping def onchange_dest_address_id(self, cr, uid, ids, address_id): if not address_id: return {} address = self.pool.get('res.partner') - values = {'warehouse_id': False} + values = {} supplier = address.browse(cr, uid, address_id) if supplier: location_id = supplier.property_stock_customer.id values.update({'location_id': location_id}) return {'value':values} - def onchange_warehouse_id(self, cr, uid, ids, warehouse_id): - if not warehouse_id: - return {} - warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id) - return {'value':{'location_id': warehouse.lot_input_id.id, 'dest_address_id': False}} + def onchange_picking_type_id(self, cr, uid, ids, picking_type_id, context=None): + value = {} + if picking_type_id: + picktype = self.pool.get("stock.picking.type").browse(cr, uid, picking_type_id, context=context) + if picktype.default_location_dest_id: + value.update({'location_id': picktype.default_location_dest_id.id}) + value.update({'related_location_id': picktype.default_location_dest_id and picktype.default_location_dest_id.id or False}) + return {'value': value} def onchange_partner_id(self, cr, uid, ids, partner_id): partner = self.pool.get('res.partner') @@ -374,54 +418,48 @@ class purchase_order(osv.osv): def view_picking(self, cr, uid, ids, context=None): ''' - This function returns an action that display existing pîcking orders of given purchase order ids. + This function returns an action that display existing picking orders of given purchase order ids. ''' + if context is None: + context = {} mod_obj = self.pool.get('ir.model.data') + dummy, action_id = tuple(mod_obj.get_object_reference(cr, uid, 'stock', 'action_picking_tree')) + action = self.pool.get('ir.actions.act_window').read(cr, uid, action_id, context=context) + pick_ids = [] for po in self.browse(cr, uid, ids, context=context): pick_ids += [picking.id for picking in po.picking_ids] - action_model, action_id = tuple(mod_obj.get_object_reference(cr, uid, 'stock', 'action_picking_tree4')) - action = self.pool[action_model].read(cr, uid, action_id, context=context) - ctx = eval(action['context']) - ctx.update({ - 'search_default_purchase_id': ids[0] - }) - if pick_ids and len(pick_ids) == 1: - form_view_ids = [view_id for view_id, view in action['views'] if view == 'form'] - view_id = form_view_ids and form_view_ids[0] or False - action.update({ - 'views': [], - 'view_mode': 'form', - 'view_id': view_id, - 'res_id': pick_ids[0] - }) - - action.update({ - 'context': ctx, - }) + #override the context to get rid of the default filtering on picking type + action['context'] = {} + #choose the view_mode accordingly + if len(pick_ids) > 1: + action['domain'] = "[('id','in',[" + ','.join(map(str, pick_ids)) + "])]" + else: + res = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_form') + action['views'] = [(res and res[1] or False, 'form')] + action['res_id'] = pick_ids and pick_ids[0] or False return action def wkf_approve_order(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'approved', 'date_approve': fields.date.context_today(self,cr,uid,context=context)}) return True - def print_confirm(self,cr,uid,ids,context=None): - print "Confirmed" - - def print_double(self,cr,uid,ids,context=None): - print "double Approval" - - def print_router(self,cr,uid,ids,context=None): - print "Routed" + def wkf_bid_received(self, cr, uid, ids, context=None): + return self.write(cr, uid, ids, {'state':'bid', 'bid_date': fields.date.context_today(self,cr,uid,context=context)}) def wkf_send_rfq(self, cr, uid, ids, context=None): ''' This function opens a window to compose an email, with the edi purchase template message loaded by default ''' + if not context: + context= {} ir_model_data = self.pool.get('ir.model.data') try: - template_id = ir_model_data.get_object_reference(cr, uid, 'purchase', 'email_template_edi_purchase')[1] + if context.get('send_rfq', False): + template_id = ir_model_data.get_object_reference(cr, uid, 'purchase', 'email_template_edi_purchase')[1] + else: + template_id = ir_model_data.get_object_reference(cr, uid, 'purchase', 'email_template_edi_purchase_done')[1] except ValueError: template_id = False try: @@ -456,7 +494,6 @@ class purchase_order(osv.osv): self.signal_send_rfq(cr, uid, ids) return self.pool['report'].get_action(cr, uid, ids, 'purchase.report_purchasequotation', context=context) - #TODO: implement messages system def wkf_confirm_order(self, cr, uid, ids, context=None): todo = [] for po in self.browse(cr, uid, ids, context=context): @@ -464,8 +501,7 @@ class purchase_order(osv.osv): raise osv.except_osv(_('Error!'),_('You cannot confirm a purchase order without any purchase order line.')) for line in po.order_line: if line.state=='draft': - todo.append(line.id) - + todo.append(line.id) self.pool.get('purchase.order.line').action_confirm(cr, uid, todo, context) for id in ids: self.write(cr, uid, [id], {'state' : 'confirmed', 'validator' : uid}) @@ -544,12 +580,17 @@ class purchase_order(osv.osv): if not len(ids): return False self.write(cr, uid, ids, {'state':'draft','shipped':0}) + self.set_order_line_status(cr, uid, ids, 'draft', context=context) for p_id in ids: # Deleting the existing instance of workflow for PO self.delete_workflow(cr, uid, [p_id]) # TODO is it necessary to interleave the calls? self.create_workflow(cr, uid, [p_id]) return True + def wkf_po_done(self, cr, uid, ids, context=None): + self.write(cr, uid, ids, {'state': 'done'}, context=context) + self.set_order_line_status(cr, uid, ids, 'done', context=context) + def action_invoice_create(self, cr, uid, ids, context=None): """Generates invoice for given ids of purchase orders and links that invoice ID to purchase order. :param ids: list of ids of purchase orders. @@ -594,7 +635,7 @@ class purchase_order(osv.osv): return res def invoice_done(self, cr, uid, ids, context=None): - self.write(cr, uid, ids, {'state':'approved'}, context=context) + self.write(cr, uid, ids, {'state': 'approved'}, context=context) return True def has_stockable_product(self, cr, uid, ids, *args): @@ -607,90 +648,86 @@ class purchase_order(osv.osv): def action_cancel(self, cr, uid, ids, context=None): for purchase in self.browse(cr, uid, ids, context=context): for pick in purchase.picking_ids: - if pick.state not in ('draft','cancel'): + if pick.state not in ('draft', 'cancel'): raise osv.except_osv( - _('Unable to cancel this purchase order.'), + _('Unable to cancel the purchase order %s.') % (purchase.name), _('First cancel all receptions related to this purchase order.')) self.pool.get('stock.picking') \ .signal_button_cancel(cr, uid, map(attrgetter('id'), purchase.picking_ids)) for inv in purchase.invoice_ids: - if inv and inv.state not in ('cancel','draft'): + if inv and inv.state not in ('cancel', 'draft'): raise osv.except_osv( _('Unable to cancel this purchase order.'), _('You must first cancel all invoices related to this purchase order.')) self.pool.get('account.invoice') \ .signal_invoice_cancel(cr, uid, map(attrgetter('id'), purchase.invoice_ids)) - self.write(cr,uid,ids,{'state':'cancel'}) - + self.write(cr, uid, ids, {'state': 'cancel'}) + self.set_order_line_status(cr, uid, ids, 'cancel', context=context) self.signal_purchase_cancel(cr, uid, ids) return True - def date_to_datetime(self, cr, uid, userdate, context=None): - """ Convert date values expressed in user's timezone to - server-side UTC timestamp, assuming a default arbitrary - time of 12:00 AM - because a time is needed. - - :param str userdate: date string in in user time zone - :return: UTC datetime string for server-side use - """ - # TODO: move to fields.datetime in server after 7.0 - user_date = datetime.strptime(userdate, DEFAULT_SERVER_DATE_FORMAT) - if context and context.get('tz'): - tz_name = context['tz'] - else: - tz_name = self.pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] - if tz_name: - utc = pytz.timezone('UTC') - context_tz = pytz.timezone(tz_name) - user_datetime = user_date + relativedelta(hours=12.0) - local_timestamp = context_tz.localize(user_datetime, is_dst=False) - user_datetime = local_timestamp.astimezone(utc) - return user_datetime.strftime(DEFAULT_SERVER_DATETIME_FORMAT) - return user_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT) - - def _prepare_order_picking(self, cr, uid, order, context=None): - return { - 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.in'), - 'origin': order.name + ((order.origin and (':' + order.origin)) or ''), - 'date': self.date_to_datetime(cr, uid, order.date_order, context), - 'partner_id': order.partner_id.id, - 'invoice_state': '2binvoiced' if order.invoice_method == 'picking' else 'none', - 'type': 'in', - 'purchase_id': order.id, - 'company_id': order.company_id.id, - 'move_lines' : [], - } - - def _prepare_order_line_move(self, cr, uid, order, order_line, picking_id, context=None): - ''' prepare the stock move data from the PO line ''' - return { + def _prepare_order_line_move(self, cr, uid, order, order_line, picking_id, group_id, context=None): + ''' prepare the stock move data from the PO line. This function returns a list of dictionary ready to be used in stock.move's create()''' + product_uom = self.pool.get('product.uom') + price_unit = order_line.price_unit + if order_line.product_uom.id != order_line.product_id.uom_id.id: + price_unit *= order_line.product_uom.factor + if order.currency_id.id != order.company_id.currency_id.id: + #we don't round the price_unit, as we may want to store the standard price with more digits than allowed by the currency + price_unit = self.pool.get('res.currency').compute(cr, uid, order.currency_id.id, order.company_id.currency_id.id, price_unit, round=False, context=context) + res = [] + move_template = { 'name': order_line.name or '', 'product_id': order_line.product_id.id, - 'product_qty': order_line.product_qty, - 'product_uos_qty': order_line.product_qty, 'product_uom': order_line.product_uom.id, 'product_uos': order_line.product_uom.id, - 'date': self.date_to_datetime(cr, uid, order.date_order, context), - 'date_expected': self.date_to_datetime(cr, uid, order_line.date_planned, context), + 'date': fields.date.date_to_datetime(self, cr, uid, order.date_order, context), + 'date_expected': fields.date.date_to_datetime(self, cr, uid, order_line.date_planned, context), 'location_id': order.partner_id.property_stock_supplier.id, 'location_dest_id': order.location_id.id, 'picking_id': picking_id, 'partner_id': order.dest_address_id.id or order.partner_id.id, - 'move_dest_id': order_line.move_dest_id.id, + 'move_dest_id': False, 'state': 'draft', - 'type':'in', 'purchase_line_id': order_line.id, 'company_id': order.company_id.id, - 'price_unit': order_line.price_unit + 'price_unit': price_unit, + 'picking_type_id': order.picking_type_id.id, + 'group_id': group_id, + 'procurement_id': False, + 'origin': order.name, + 'route_ids': order.picking_type_id.warehouse_id and [(6, 0, [x.id for x in order.picking_type_id.warehouse_id.route_ids])] or [], + 'warehouse_id':order.picking_type_id.warehouse_id.id, } - def _create_pickings(self, cr, uid, order, order_lines, picking_id=False, context=None): - """Creates pickings and appropriate stock moves for given order lines, then - confirms the moves, makes them available, and confirms the picking. + diff_quantity = order_line.product_qty + for procurement in order_line.procurement_ids: + procurement_qty = product_uom._compute_qty(cr, uid, procurement.product_uom.id, procurement.product_qty, to_uom_id=order_line.product_uom.id) + tmp = move_template.copy() + tmp.update({ + 'product_uom_qty': min(procurement_qty, diff_quantity), + 'product_uos_qty': min(procurement_qty, diff_quantity), + 'move_dest_id': procurement.move_dest_id.id, # blabla + 'group_id': procurement.group_id.id or group_id, # blabla to check ca devrait etre bon et groupé dans le meme picking qd meme + 'procurement_id': procurement.id, + }) + diff_quantity -= min(procurement_qty, diff_quantity) + res.append(tmp) + #if the order line has a bigger quantity than the procurement it was for (manually changed or minimal quantity), then + #split the future stock move in two because the route followed may be different. + if diff_quantity > 0: + move_template['product_uom_qty'] = diff_quantity + move_template['product_uos_qty'] = diff_quantity + res.append(move_template) + return res - If ``picking_id`` is provided, the stock moves will be added to it, otherwise - a standard outgoing picking will be created to wrap the stock moves, as returned - by :meth:`~._prepare_order_picking`. + def _create_stock_moves(self, cr, uid, order, order_lines, picking_id=False, context=None): + """Creates appropriate stock moves for given order lines, whose can optionally create a + picking if none is given or no suitable is found, then confirms the moves, makes them + available, and confirms the pickings. + + If ``picking_id`` is provided, the stock moves will be added to it, otherwise a standard + incoming picking will be created to wrap the stock moves (default behavior of the stock.move) Modules that wish to customize the procurements or partition the stock moves over multiple stock pickings may override this method and call ``super()`` with @@ -701,39 +738,69 @@ class purchase_order(osv.osv): and moves should be created. :param int picking_id: optional ID of a stock picking to which the created stock moves will be added. A new picking will be created if omitted. - :return: list of IDs of pickings used/created for the given order lines (usually just one) + :return: None """ - stock_picking = self.pool.get('stock.picking') - if not picking_id: - picking_id = stock_picking.create(cr, uid, self._prepare_order_picking(cr, uid, order, context=context)) - todo_moves = [] stock_move = self.pool.get('stock.move') + todo_moves = [] + new_group = self.pool.get("procurement.group").create(cr, uid, {'name': order.name, 'partner_id': order.partner_id.id}, context=context) + for order_line in order_lines: if not order_line.product_id: continue + if order_line.product_id.type in ('product', 'consu'): - move = stock_move.create(cr, uid, self._prepare_order_line_move(cr, uid, order, order_line, picking_id, context=context)) - if order_line.move_dest_id and order_line.move_dest_id.state != 'done': - order_line.move_dest_id.write({'location_id': order.location_id.id}) - todo_moves.append(move) - stock_move.action_confirm(cr, uid, todo_moves) + for vals in self._prepare_order_line_move(cr, uid, order, order_line, picking_id, new_group, context=context): + move = stock_move.create(cr, uid, vals, context=context) + todo_moves.append(move) + + todo_moves = stock_move.action_confirm(cr, uid, todo_moves) stock_move.force_assign(cr, uid, todo_moves) - stock_picking.signal_button_confirm(cr, uid, [picking_id]) - return [picking_id] + + def test_moves_done(self, cr, uid, ids, context=None): + '''PO is done at the delivery side if all the incoming shipments are done''' + for purchase in self.browse(cr, uid, ids, context=context): + for picking in purchase.picking_ids: + if picking.state != 'done': + return False + return True + + def test_moves_except(self, cr, uid, ids, context=None): + ''' PO is in exception at the delivery side if one of the picking is canceled + and the other pickings are completed (done or canceled) + ''' + at_least_one_canceled = False + alldoneorcancel = True + for purchase in self.browse(cr, uid, ids, context=context): + for picking in purchase.picking_ids: + if picking.state == 'cancel': + at_least_one_canceled = True + if picking.state not in ['done', 'cancel']: + alldoneorcancel = False + return at_least_one_canceled and alldoneorcancel + + def move_lines_get(self, cr, uid, ids, *args): + res = [] + for order in self.browse(cr, uid, ids, context={}): + for line in order.order_line: + res += [x.id for x in line.move_ids] + return res def action_picking_create(self, cr, uid, ids, context=None): - picking_ids = [] for order in self.browse(cr, uid, ids): - picking_ids.extend(self._create_pickings(cr, uid, order, order.order_line, None, context=context)) - - # Must return one unique picking ID: the one to connect in the subflow of the purchase order. - # In case of multiple (split) pickings, we should return the ID of the critical one, i.e. the - # one that should trigger the advancement of the purchase workflow. - # By default we will consider the first one as most important, but this behavior can be overridden. - return picking_ids[0] if picking_ids else False + picking_id = self.pool.get('stock.picking').create(cr, uid, {'picking_type_id': order.picking_type_id.id, 'partner_id': order.dest_address_id.id or order.partner_id.id}, context=context) + self._create_stock_moves(cr, uid, order, order.order_line, picking_id, context=context) def picking_done(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'shipped':1,'state':'approved'}, context=context) + # Do check on related procurements: + proc_obj = self.pool.get("procurement.order") + po_lines = [] + for po in self.browse(cr, uid, ids, context=context): + po_lines += [x.id for x in po.order_line] + if po_lines: + procs = proc_obj.search(cr, uid, [('purchase_line_id', 'in', po_lines)], context=context) + if procs: + proc_obj.check(cr, uid, procs, context=context) self.message_post(cr, uid, ids, body=_("Products received"), context=context) return True @@ -745,7 +812,7 @@ class purchase_order(osv.osv): 'shipped':False, 'invoiced':False, 'invoice_ids': [], - 'picking_ids': [], + 'origin': '', 'partner_ref': '', 'name': self.pool.get('ir.sequence').get(cr, uid, 'purchase.order'), }) @@ -775,7 +842,7 @@ class purchase_order(osv.osv): list_key = [] for field in fields: field_val = getattr(br, field) - if field in ('product_id', 'move_dest_id', 'account_analytic_id'): + if field in ('product_id', 'account_analytic_id'): if not field_val: field_val = False if isinstance(field_val, browse_record): @@ -792,21 +859,22 @@ class purchase_order(osv.osv): context = {} # Compute what the new orders should contain - new_orders = {} + order_lines_to_move = [] for porder in [order for order in self.browse(cr, uid, ids, context=context) if order.state == 'draft']: order_key = make_key(porder, ('partner_id', 'location_id', 'pricelist_id')) new_order = new_orders.setdefault(order_key, ({}, [])) new_order[1].append(porder.id) order_infos = new_order[0] + if not order_infos: order_infos.update({ 'origin': porder.origin, 'date_order': porder.date_order, 'partner_id': porder.partner_id.id, 'dest_address_id': porder.dest_address_id.id, - 'warehouse_id': porder.warehouse_id.id, + 'picking_type_id': porder.picking_type_id.id, 'location_id': porder.location_id.id, 'pricelist_id': porder.pricelist_id.id, 'state': 'draft', @@ -823,21 +891,7 @@ class purchase_order(osv.osv): order_infos['origin'] = (order_infos['origin'] or '') + ' ' + porder.origin for order_line in porder.order_line: - line_key = make_key(order_line, ('name', 'date_planned', 'taxes_id', 'price_unit', 'product_id', 'move_dest_id', 'account_analytic_id')) - o_line = order_infos['order_line'].setdefault(line_key, {}) - if o_line: - # merge the line with an existing line - o_line['product_qty'] += order_line.product_qty * order_line.product_uom.factor / o_line['uom_factor'] - else: - # append a new "standalone" line - for field in ('product_qty', 'product_uom'): - field_val = getattr(order_line, field) - if isinstance(field_val, browse_record): - field_val = field_val.id - o_line[field] = field_val - o_line['uom_factor'] = order_line.product_uom and order_line.product_uom.factor or 1.0 - - + order_lines_to_move += [order_line.id] allorders = [] orders_info = {} @@ -851,7 +905,7 @@ class purchase_order(osv.osv): for key, value in order_data['order_line'].iteritems(): del value['uom_factor'] value.update(dict(key)) - order_data['order_line'] = [(0, 0, value) for value in order_data['order_line'].itervalues()] + order_data['order_line'] = [(6, 0, order_lines_to_move)] # create the new order context.update({'mail_create_nolog': True}) @@ -863,7 +917,8 @@ class purchase_order(osv.osv): # make triggers pointing to the old orders point to the new order for old_id in old_ids: self.redirect_workflow(cr, uid, [(old_id, neworder_id)]) - self.signal_purchase_cancel(cr, uid, [old_id]) # TODO Is it necessary to interleave the calls? + self.signal_purchase_cancel(cr, uid, [old_id]) + return orders_info @@ -894,7 +949,6 @@ class purchase_order_line(osv.osv): 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True), 'product_id': fields.many2one('product.product', 'Product', domain=[('purchase_ok','=',True)], change_default=True), 'move_ids': fields.one2many('stock.move', 'purchase_line_id', 'Reservation', readonly=True, ondelete='set null'), - 'move_dest_id': fields.many2one('stock.move', 'Reservation Destination', ondelete='set null'), 'price_unit': fields.float('Unit Price', required=True, digits_compute= dp.get_precision('Product Price')), 'price_subtotal': fields.function(_amount_line, string='Subtotal', digits_compute= dp.get_precision('Account')), 'order_id': fields.many2one('purchase.order', 'Order Reference', select=True, required=True, ondelete='cascade'), @@ -909,7 +963,7 @@ class purchase_order_line(osv.osv): 'invoiced': fields.boolean('Invoiced', readonly=True), 'partner_id': fields.related('order_id','partner_id',string='Partner',readonly=True,type="many2one", relation="res.partner", store=True), 'date_order': fields.related('order_id','date_order',string='Order Date',readonly=True,type="date"), - + 'procurement_ids': fields.one2many('procurement.order', 'purchase_line_id', string='Associated procurements'), } _defaults = { 'product_uom' : _get_uom_id, @@ -924,21 +978,19 @@ class purchase_order_line(osv.osv): def copy_data(self, cr, uid, id, default=None, context=None): if not default: default = {} - default.update({'state':'draft', 'move_ids':[],'invoiced':0,'invoice_lines':[]}) + default.update({'state':'draft', 'move_ids':[], 'invoiced':0, 'invoice_lines':[], 'procurement_ids': False}) return super(purchase_order_line, self).copy_data(cr, uid, id, default, context) def unlink(self, cr, uid, ids, context=None): - procurement_ids_to_cancel = [] - for line in self.browse(cr, uid, ids, context=context): - if line.move_dest_id: - procurement_ids_to_cancel.extend(procurement.id for procurement in line.move_dest_id.procurements) + procurement_obj = self.pool.get('procurement.order') + procurement_ids_to_cancel = procurement_obj.search(cr, uid, [('purchase_line_id', 'in', ids)], context=context) if procurement_ids_to_cancel: - self.pool['procurement.order'].action_cancel(cr, uid, procurement_ids_to_cancel) + self.pool['procurement.order'].cancel(cr, uid, procurement_ids_to_cancel) return super(purchase_order_line, self).unlink(cr, uid, ids, context=context) def onchange_product_uom(self, cr, uid, ids, pricelist_id, product_id, qty, uom_id, partner_id, date_order=False, fiscal_position_id=False, date_planned=False, - name=False, price_unit=False, context=None): + name=False, price_unit=False, state='draft', context=None): """ onchange handler of product_uom. """ @@ -949,7 +1001,7 @@ class purchase_order_line(osv.osv): context = dict(context, purchase_uom_check=True) return self.onchange_product_id(cr, uid, ids, pricelist_id, product_id, qty, uom_id, partner_id, date_order=date_order, fiscal_position_id=fiscal_position_id, date_planned=date_planned, - name=name, price_unit=price_unit, context=context) + name=name, price_unit=price_unit, state=state, context=context) def _get_date_planned(self, cr, uid, supplier_info, date_order_str, context=None): """Return the datetime value to use as Schedule Date (``date_planned``) for @@ -966,6 +1018,12 @@ class purchase_order_line(osv.osv): supplier_delay = int(supplier_info.delay) if supplier_info else 0 return datetime.strptime(date_order_str, DEFAULT_SERVER_DATE_FORMAT) + relativedelta(days=supplier_delay) + def action_cancel(self, cr, uid, ids, context=None): + self.write(cr, uid, ids, {'state': 'cancel'}, context=context) + for po_line in self.browse(cr, uid, ids, context=context): + if all([l.state == 'cancel' for l in po_line.order_id.order_line]): + self.pool.get('purchase.order').action_cancel(cr, uid, [po_line.order_id.id], context=context) + def _check_product_uom_group(self, cr, uid, context=None): group_uom = self.pool.get('ir.model.data').get_object(cr, uid, 'product', 'group_uom') res = [user for user in group_uom.users if user.id == uid] @@ -974,7 +1032,7 @@ class purchase_order_line(osv.osv): def onchange_product_id(self, cr, uid, ids, pricelist_id, product_id, qty, uom_id, partner_id, date_order=False, fiscal_position_id=False, date_planned=False, - name=False, price_unit=False, context=None): + name=False, price_unit=False, state='draft', context=None): """ onchange handler of product_id. """ @@ -1047,12 +1105,14 @@ class purchase_order_line(osv.osv): if qty: res['value'].update({'product_qty': qty}) - # - determine price_unit and taxes_id - if pricelist_id: - price = product_pricelist.price_get(cr, uid, [pricelist_id], - product.id, qty or 1.0, partner_id or False, {'uom': uom_id, 'date': date_order})[pricelist_id] - else: - price = product.standard_price + price = price_unit + if state not in ('sent','bid'): + # - determine price_unit and taxes_id + if pricelist_id: + price = product_pricelist.price_get(cr, uid, [pricelist_id], + product.id, qty or 1.0, partner_id or False, {'uom': uom_id, 'date': date_order})[pricelist_id] + else: + price = product.standard_price taxes = account_tax.browse(cr, uid, map(lambda x: x.id, product.supplier_taxes_id)) fpos = fiscal_position_id and account_fiscal_position.browse(cr, uid, fiscal_position_id, context=context) or False @@ -1062,29 +1122,50 @@ class purchase_order_line(osv.osv): return res product_id_change = onchange_product_id - product_uom_change = onchange_product_uom + product_uom_change = onchange_product_uom def action_confirm(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'confirmed'}, context=context) return True +class procurement_rule(osv.osv): + _inherit = 'procurement.rule' + + def _get_action(self, cr, uid, context=None): + return [('buy', _('Buy'))] + super(procurement_rule, self)._get_action(cr, uid, context=context) + class procurement_order(osv.osv): _inherit = 'procurement.order' _columns = { - 'purchase_id': fields.many2one('purchase.order', 'Purchase Order'), + 'purchase_line_id': fields.many2one('purchase.order.line', 'Purchase Order Line'), + 'purchase_id': fields.related('purchase_line_id', 'order_id', type='many2one', relation='purchase.order', string='Purchase Order'), } - def check_buy(self, cr, uid, ids, context=None): - ''' return True if the supply method of the mto product is 'buy' - ''' - user = self.pool.get('res.users').browse(cr, uid, uid, context=context) - for procurement in self.browse(cr, uid, ids, context=context): - if procurement.product_id.supply_method <> 'buy': - return False - return True + def propagate_cancel(self, cr, uid, procurement, context=None): + if procurement.rule_id.action == 'buy' and procurement.purchase_line_id: + purchase_line_obj = self.pool.get('purchase.order.line') + if procurement.purchase_line_id.product_qty > procurement.product_qty and procurement.purchase_line_id.order_id.state == 'draft': + purchase_line_obj.write(cr, uid, [procurement.purchase_line_id.id], {'product_qty': procurement.purchase_line_id.product_qty - procurement.product_qty}, context=context) + else: + purchase_line_obj.action_cancel(cr, uid, [procurement.purchase_line_id.id], context=context) + return super(procurement_order, self).propagate_cancel(cr, uid, procurement, context=context) - def check_supplier_info(self, cr, uid, ids, context=None): + def _run(self, cr, uid, procurement, context=None): + if procurement.rule_id and procurement.rule_id.action == 'buy': + #make a purchase order for the procurement + return self.make_po(cr, uid, [procurement.id], context=context)[procurement.id] + return super(procurement_order, self)._run(cr, uid, procurement, context=context) + + def _check(self, cr, uid, procurement, context=None): + if procurement.purchase_line_id and procurement.purchase_line_id.order_id.shipped: # TOCHECK: does it work for several deliveries? + return True + return super(procurement_order, self)._check(cr, uid, procurement, context=context) + + def _check_supplier_info(self, cr, uid, ids, context=None): + ''' Check the supplier info field of a product and write an error message on the procurement if needed. + Returns True if all needed information is there, False if some configuration mistake is detected. + ''' partner_obj = self.pool.get('res.partner') user = self.pool.get('res.users').browse(cr, uid, uid, context=context) for procurement in self.browse(cr, uid, ids, context=context): @@ -1109,15 +1190,6 @@ class procurement_order(osv.osv): return True - - def action_po_assign(self, cr, uid, ids, context=None): - """ This is action which call from workflow to assign purchase order to procurements - @return: True - """ - res = self.make_po(cr, uid, ids, context=context) - res = res.values() - return len(res) and res[0] or 0 #TO CHECK: why workflow is generated error if return not integer value - def create_procurement_purchase_order(self, cr, uid, procurement, po_vals, line_vals, context=None): """Create the purchase order from the procurement, using the provided field values, after adding the given purchase @@ -1161,112 +1233,114 @@ class procurement_order(osv.osv): seller_delay = int(procurement.product_id.seller_delay) return schedule_date - relativedelta(days=seller_delay) - def _get_warehouse(self, procurement, user_company): - """ - Return the warehouse containing the procurment stock location (or one of it ancestors) - If none match, returns then first warehouse of the company - """ - # TODO refactor the domain once we implement the "parent_of" domain operator - # NOTE This method has been copied in the `purchase_requisition` module to ensure - # retro-compatibility. This code duplication will be deleted in next stable version. - # Do not forget to update both version in case of modification. - company_id = (procurement.company_id or user_company).id - domains = [ - [ - '&', ('company_id', '=', company_id), - '|', '&', ('lot_stock_id.parent_left', '<', procurement.location_id.parent_left), - ('lot_stock_id.parent_right', '>', procurement.location_id.parent_right), - ('lot_stock_id', '=', procurement.location_id.id) - ], - [('company_id', '=', company_id)] - ] + def _get_product_supplier(self, cr, uid, procurement, context=None): + ''' returns the main supplier of the procurement's product given as argument''' + return procurement.product_id.seller_id - cr, uid = procurement._cr, procurement._uid - context = procurement._context - Warehouse = self.pool['stock.warehouse'] - for domain in domains: - ids = Warehouse.search(cr, uid, domain, context=context) - if ids: - return ids[0] - return False - - def make_po(self, cr, uid, ids, context=None): - """ Make purchase order from procurement - @return: New created Purchase Orders procurement wise - """ - res = {} + def _get_po_line_values_from_proc(self, cr, uid, procurement, partner, company, schedule_date, context=None): if context is None: context = {} - company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id - partner_obj = self.pool.get('res.partner') uom_obj = self.pool.get('product.uom') pricelist_obj = self.pool.get('product.pricelist') prod_obj = self.pool.get('product.product') acc_pos_obj = self.pool.get('account.fiscal.position') + + seller_qty = procurement.product_id.seller_qty + pricelist_id = partner.property_product_pricelist_purchase.id + uom_id = procurement.product_id.uom_po_id.id + qty = uom_obj._compute_qty(cr, uid, procurement.product_uom.id, procurement.product_qty, uom_id) + if seller_qty: + qty = max(qty, seller_qty) + price = pricelist_obj.price_get(cr, uid, [pricelist_id], procurement.product_id.id, qty, partner.id, {'uom': uom_id})[pricelist_id] + + #Passing partner_id to context for purchase order line integrity of Line name + new_context = context.copy() + new_context.update({'lang': partner.lang, 'partner_id': partner.id}) + product = prod_obj.browse(cr, uid, procurement.product_id.id, context=new_context) + taxes_ids = procurement.product_id.supplier_taxes_id + taxes = acc_pos_obj.map_tax(cr, uid, partner.property_account_position, taxes_ids) + name = product.partner_ref + if product.description_purchase: + name += '\n' + product.description_purchase + + return { + 'name': name, + 'product_qty': qty, + 'product_id': procurement.product_id.id, + 'product_uom': uom_id, + 'price_unit': price or 0.0, + 'date_planned': schedule_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + 'taxes_id': [(6, 0, taxes)], + } + + def make_po(self, cr, uid, ids, context=None): + """ Resolve the purchase from procurement, which may result in a new PO creation, a new PO line creation or a quantity change on existing PO line. + Note that some operations (as the PO creation) are made as SUPERUSER because the current user may not have rights to do it (mto product launched by a sale for example) + + @return: dictionary giving for each procurement its related resolving PO line. + """ + res = {} + company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id + po_obj = self.pool.get('purchase.order') + po_line_obj = self.pool.get('purchase.order.line') seq_obj = self.pool.get('ir.sequence') + pass_ids = [] + linked_po_ids = [] + sum_po_line_ids = [] for procurement in self.browse(cr, uid, ids, context=context): - res_id = procurement.move_id.id - partner = procurement.product_id.seller_id # Taken Main Supplier of Product of Procurement. - seller_qty = procurement.product_id.seller_qty - partner_id = partner.id - address_id = partner_obj.address_get(cr, uid, [partner_id], ['delivery'])['delivery'] - pricelist_id = partner.property_product_pricelist_purchase.id - uom_id = procurement.product_id.uom_po_id.id - - qty = uom_obj._compute_qty(cr, uid, procurement.product_uom.id, procurement.product_qty, uom_id) - if seller_qty: - qty = max(qty,seller_qty) - - price = pricelist_obj.price_get(cr, uid, [pricelist_id], procurement.product_id.id, qty, partner_id, {'uom': uom_id})[pricelist_id] - - schedule_date = self._get_purchase_schedule_date(cr, uid, procurement, company, context=context) - purchase_date = self._get_purchase_order_date(cr, uid, procurement, company, schedule_date, context=context) - - #Passing partner_id to context for purchase order line integrity of Line name - new_context = context.copy() - new_context.update({'lang': partner.lang, 'partner_id': partner_id}) - - product = prod_obj.browse(cr, uid, procurement.product_id.id, context=new_context) - taxes_ids = procurement.product_id.supplier_taxes_id - taxes = acc_pos_obj.map_tax(cr, uid, partner.property_account_position, taxes_ids) - - name = product.partner_ref - if product.description_purchase: - name += '\n'+ product.description_purchase - line_vals = { - 'name': name, - 'product_qty': qty, - 'product_id': procurement.product_id.id, - 'product_uom': uom_id, - 'price_unit': price or 0.0, - 'date_planned': schedule_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT), - 'move_dest_id': res_id, - 'taxes_id': [(6,0,taxes)], - } - name = seq_obj.get(cr, uid, 'purchase.order') or _('PO: %s') % procurement.name - po_vals = { - 'name': name, - 'origin': procurement.origin, - 'partner_id': partner_id, - 'location_id': procurement.location_id.id, - 'warehouse_id': self._get_warehouse(procurement, company), - 'pricelist_id': pricelist_id, - 'date_order': purchase_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT), - 'company_id': procurement.company_id.id, - 'fiscal_position': partner.property_account_position and partner.property_account_position.id or False, - 'payment_term_id': partner.property_supplier_payment_term.id or False, - } - res[procurement.id] = self.create_procurement_purchase_order(cr, uid, procurement, po_vals, line_vals, context=new_context) - self.write(cr, uid, [procurement.id], {'state': 'running', 'purchase_id': res[procurement.id]}) - self.message_post(cr, uid, ids, body=_("Draft Purchase Order created"), context=context) + partner = self._get_product_supplier(cr, uid, procurement, context=context) + if not partner: + self.message_post(cr, uid, [procurement.id], _('There is no supplier associated to product %s') % (procurement.product_id.name)) + res[procurement.id] = False + else: + schedule_date = self._get_purchase_schedule_date(cr, uid, procurement, company, context=context) + line_vals = self._get_po_line_values_from_proc(cr, uid, procurement, partner, company, schedule_date, context=context) + #look for any other draft PO for the same supplier, to attach the new line on instead of creating a new draft one + available_draft_po_ids = po_obj.search(cr, uid, [ + ('partner_id', '=', partner.id), ('state', '=', 'draft'), ('picking_type_id', '=', procurement.rule_id.picking_type_id.id), + ('location_id', '=', procurement.location_id.id), ('company_id', '=', procurement.company_id.id), ('dest_address_id', '=', procurement.partner_dest_id.id)], context=context) + if available_draft_po_ids: + po_id = available_draft_po_ids[0] + #look for any other PO line in the selected PO with same product and UoM to sum quantities instead of creating a new po line + available_po_line_ids = po_line_obj.search(cr, uid, [('order_id', '=', po_id), ('product_id', '=', line_vals['product_id']), ('product_uom', '=', line_vals['product_uom'])], context=context) + if available_po_line_ids: + po_line = po_line_obj.browse(cr, uid, available_po_line_ids[0], context=context) + po_line_obj.write(cr, SUPERUSER_ID, po_line.id, {'product_qty': po_line.product_qty + line_vals['product_qty']}, context=context) + po_line_id = po_line.id + sum_po_line_ids.append(procurement.id) + else: + line_vals.update(order_id=po_id) + po_line_id = po_line_obj.create(cr, SUPERUSER_ID, line_vals, context=context) + linked_po_ids.append(procurement.id) + else: + purchase_date = self._get_purchase_order_date(cr, uid, procurement, company, schedule_date, context=context) + name = seq_obj.get(cr, uid, 'purchase.order') or _('PO: %s') % procurement.name + po_vals = { + 'name': name, + 'origin': procurement.origin, + 'partner_id': partner.id, + 'location_id': procurement.location_id.id, + 'picking_type_id': procurement.rule_id.picking_type_id.id, + 'pricelist_id': partner.property_product_pricelist_purchase.id, + 'date_order': purchase_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + 'company_id': procurement.company_id.id, + 'fiscal_position': partner.property_account_position and partner.property_account_position.id or False, + 'payment_term_id': partner.property_supplier_payment_term.id or False, + 'dest_address_id': procurement.partner_dest_id.id, + } + po_id = self.create_procurement_purchase_order(cr, SUPERUSER_ID, procurement, po_vals, line_vals, context=context) + po_line_id = po_obj.browse(cr, uid, po_id, context=context).order_line[0].id + pass_ids.append(procurement.id) + res[procurement.id] = po_line_id + self.write(cr, uid, [procurement.id], {'purchase_line_id': po_line_id}, context=context) + if pass_ids: + self.message_post(cr, uid, pass_ids, body=_("Draft Purchase Order created"), context=context) + if linked_po_ids: + self.message_post(cr, uid, linked_po_ids, body=_("Purchase line created and linked to an existing Purchase Order"), context=context) + if sum_po_line_ids: + self.message_post(cr, uid, sum_po_line_ids, body=_("Quantity added in existing Purchase Order Line"), context=context) return res - def _product_virtual_get(self, cr, uid, order_point): - procurement = order_point.procurement_id - if procurement and procurement.state != 'exception' and procurement.purchase_id and procurement.purchase_id.state in ('draft', 'confirmed'): - return None - return super(procurement_order, self)._product_virtual_get(cr, uid, order_point) - class mail_mail(osv.Model): _name = 'mail.mail' @@ -1274,7 +1348,9 @@ class mail_mail(osv.Model): def _postprocess_sent_message(self, cr, uid, mail, context=None, mail_sent=True): if mail_sent and mail.model == 'purchase.order': - self.pool.get('purchase.order').signal_send_rfq(cr, uid, [mail.res_id]) + obj = self.pool.get('purchase.order').browse(cr, uid, mail.res_id, context=context) + if obj.state == 'draft': + self.pool.get('purchase.order').signal_send_rfq(cr, uid, [mail.res_id]) return super(mail_mail, self)._postprocess_sent_message(cr, uid, mail=mail, context=context, mail_sent=mail_sent) @@ -1364,4 +1440,15 @@ class account_invoice_line(osv.Model): readonly=True), } +class product_product(osv.osv): + _inherit = "product.product" + + def _get_buy_route(self, cr, uid, context=None): + buy_route = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'purchase', 'route_warehouse0_buy')[1] + return [buy_route] + + _defaults = { + 'route_ids': _get_buy_route, + } + # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/purchase/purchase_data.xml b/addons/purchase/purchase_data.xml index afd9560e350..3c70629b675 100644 --- a/addons/purchase/purchase_data.xml +++ b/addons/purchase/purchase_data.xml @@ -42,12 +42,6 @@ - - @@ -66,5 +60,14 @@ purchase.order + + + + Buy + 5 + + diff --git a/addons/purchase/purchase_data.yml b/addons/purchase/purchase_data.yml new file mode 100644 index 00000000000..a122c932b24 --- /dev/null +++ b/addons/purchase/purchase_data.yml @@ -0,0 +1,10 @@ +- + !python {model: ir.values, id: purchase_default_set}: | + whr = self.pool.get('stock.warehouse').browse(cr, uid, ref('stock.warehouse0'), context=context) + self.set_default(cr, uid, 'purchase.order', 'picking_type_id', whr.in_type_id.id, for_all_users=True, company_id=True, condition=False) +- + !python {model: stock.warehouse}: | + #enable purchase on main warehouse + main_warehouse = self.browse(cr, uid, ref('stock.warehouse0'), context=context) + self.write(cr, uid, main_warehouse.id, {'buy_to_resupply': True}, context=context) + diff --git a/addons/purchase/purchase_demo.xml b/addons/purchase/purchase_demo.xml index c68ee8775bb..55d58669fd4 100644 --- a/addons/purchase/purchase_demo.xml +++ b/addons/purchase/purchase_demo.xml @@ -11,12 +11,35 @@ - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/addons/purchase/purchase_stock_demo.yml b/addons/purchase/purchase_stock_demo.yml new file mode 100644 index 00000000000..a483c8301c6 --- /dev/null +++ b/addons/purchase/purchase_stock_demo.yml @@ -0,0 +1,12 @@ +- + !python {model: stock.warehouse}: | + pull_obj = self.pool.get('procurement.rule') + wh_to_assign = ['stock_warehouse_shop0'] + for wh_ref in wh_to_assign: + warehouse = self.browse(cr, uid, ref('stock.' + wh_ref), context=context) + #Force the rewriting of route and rule + self.write(cr, uid, warehouse.id, {'buy_to_resupply': True}, context=context) + + + + diff --git a/addons/purchase/purchase_view.xml b/addons/purchase/purchase_view.xml index 8ac885830e2..499308e0096 100644 --- a/addons/purchase/purchase_view.xml +++ b/addons/purchase/purchase_view.xml @@ -87,8 +87,6 @@ - @@ -164,28 +162,29 @@

-

-

@@ -199,25 +198,31 @@ - - + + + + - + - + - - + + + @@ -233,12 +238,20 @@
- + + + + + + + + + - + @@ -334,11 +347,11 @@ - Quotations + Requests for Quotation ir.actions.act_window purchase.order {} - [('state','in',('draft','sent','cancel', 'confirmed'))] + [('state','in',('draft','sent','bid','cancel', 'confirmed'))] tree,form,graph,calendar @@ -364,7 +377,7 @@ purchase.order tree,form,graph,calendar {} - [('state','not in',('draft','sent','confirmed'))] + [('state','not in',('draft','sent','bid', 'confirmed'))]

@@ -387,11 +400,11 @@ - +

- - + +
@@ -405,7 +418,7 @@ - + @@ -434,6 +447,7 @@
+ purchase.order.line.form2 purchase.order.line @@ -485,9 +499,10 @@ + - - + + @@ -512,6 +527,7 @@

+ tree @@ -537,7 +553,7 @@ procurement.order - + @@ -561,28 +577,6 @@ - - product.normal.form.procurement.help.inherit - product.product - - - -

- When you sell this service to a customer, a draft purchase order - will be created in order to subcontract the job - to - . -

-

- When you sell this product, OpenERP will trigger a draft - purchase order to buy the required quantities to the supplier. - The delivery order will be ready after having received the - products. -

-
-
-
- product.search.purchase.form product.product diff --git a/addons/purchase/purchase_workflow.xml b/addons/purchase/purchase_workflow.xml index ec4632c45a9..810c0a74064 100644 --- a/addons/purchase/purchase_workflow.xml +++ b/addons/purchase/purchase_workflow.xml @@ -19,6 +19,12 @@ function write({'state':'sent'}) + + + bid + function + wkf_bid_received() + confirmed @@ -31,7 +37,7 @@ cancel function True - write({'state':'cancel'}) + action_cancel() @@ -73,21 +79,22 @@ picking - subflow - + function action_picking_create() + + + picking_done picking_done() function - subflow.delivery_done done - write({'state':'done'}) + wkf_po_done() function True AND @@ -103,16 +110,26 @@ send_rfq - - + + purchase_confirm + + + + bid_received + purchase_cancel + + + + purchase_cancel + @@ -172,7 +189,7 @@ - subflow.cancel + picking_cancel @@ -182,7 +199,8 @@ - subflow.done + picking_done + @@ -203,32 +221,5 @@ invoiced - - - - buy - subflow - - action_po_assign() - - - - - - check_buy() and check_supplier_info() - - - - - - subflow.delivery_done - - - - - - subflow.cancel - - diff --git a/addons/purchase/report/purchase_report.py b/addons/purchase/report/purchase_report.py index ada1d83cdaf..2483f79410c 100644 --- a/addons/purchase/report/purchase_report.py +++ b/addons/purchase/report/purchase_report.py @@ -40,7 +40,7 @@ class purchase_report(osv.osv): ('done', 'Done'), ('cancel', 'Cancelled')],'Order Status', readonly=True), 'product_id':fields.many2one('product.product', 'Product', readonly=True), - 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', readonly=True), + 'picking_type_id': fields.many2one('stock.warehouse', 'Warehouse', readonly=True), 'location_id': fields.many2one('stock.location', 'Destination', readonly=True), 'partner_id':fields.many2one('res.partner', 'Supplier', readonly=True), 'pricelist_id':fields.many2one('product.pricelist', 'Pricelist', readonly=True), @@ -75,7 +75,7 @@ class purchase_report(osv.osv): s.dest_address_id, s.pricelist_id, s.validator, - s.warehouse_id as warehouse_id, + s.picking_type_id as picking_type_id, s.partner_id as partner_id, s.create_uid as user_id, s.company_id as company_id, @@ -88,13 +88,14 @@ class purchase_report(osv.osv): extract(epoch from age(l.date_planned,s.date_order))/(24*60*60)::decimal(16,2) as delay_pass, count(*) as nbr, sum(l.price_unit*l.product_qty)::decimal(16,2) as price_total, - avg(100.0 * (l.price_unit*l.product_qty) / NULLIF(t.standard_price*l.product_qty/u.factor*u2.factor, 0.0))::decimal(16,2) as negociation, - sum(t.standard_price*l.product_qty/u.factor*u2.factor)::decimal(16,2) as price_standard, + avg(100.0 * (l.price_unit*l.product_qty) / NULLIF(ip.value_float*l.product_qty/u.factor*u2.factor, 0.0))::decimal(16,2) as negociation, + sum(ip.value_float*l.product_qty/u.factor*u2.factor)::decimal(16,2) as price_standard, (sum(l.product_qty*l.price_unit)/NULLIF(sum(l.product_qty/u.factor*u2.factor),0.0))::decimal(16,2) as price_average from purchase_order_line l join purchase_order s on (l.order_id=s.id) left join product_product p on (l.product_id=p.id) left join product_template t on (p.product_tmpl_id=t.id) + LEFT JOIN ir_property ip ON (ip.name='standard_price' AND ip.res_id=CONCAT('product.template,',t.id) AND ip.company_id=s.company_id) left join product_uom u on (u.id=l.product_uom) left join product_uom u2 on (u2.id=t.uom_id) group by @@ -115,7 +116,7 @@ class purchase_report(osv.osv): t.categ_id, s.date_order, s.state, - s.warehouse_id, + s.picking_type_id, u.uom_type, u.category_id, t.uom_id, diff --git a/addons/purchase/report/purchase_report_view.xml b/addons/purchase/report/purchase_report_view.xml index 50b22f40a05..fc171e42efa 100644 --- a/addons/purchase/report/purchase_report_view.xml +++ b/addons/purchase/report/purchase_report_view.xml @@ -30,7 +30,7 @@ - + @@ -43,7 +43,7 @@ - + @@ -70,7 +70,7 @@ groups="purchase.group_purchase_manager"/> - + diff --git a/addons/purchase/res_config.py b/addons/purchase/res_config.py index 0d293631a1a..50525b165b6 100644 --- a/addons/purchase/res_config.py +++ b/addons/purchase/res_config.py @@ -39,8 +39,8 @@ class purchase_config_settings(osv.osv_memory): 'group_uom':fields.boolean("Manage different units of measure for products", implied_group='product.group_uom', help="""Allows you to select and maintain different units of measure for products."""), - 'group_costing_method':fields.boolean("Compute product cost price based on average cost", - implied_group='product.group_costing_method', + 'group_costing_method':fields.boolean("Use 'Real Price' or 'Average' costing methods.", + implied_group='stock_account.group_inventory_valuation', help="""Allows you to compute product cost price based on average cost."""), 'module_warning': fields.boolean("Alerts by products or supplier", help='Allow to configure notification on products and trigger them when a user wants to purchase a given product or a given supplier.\n' @@ -49,16 +49,23 @@ class purchase_config_settings(osv.osv_memory): 'module_purchase_double_validation': fields.boolean("Force two levels of approvals", help='Provide a double validation mechanism for purchases exceeding minimum amount.\n' '-This installs the module purchase_double_validation.'), - 'module_purchase_requisition': fields.boolean("Manage purchase requisitions", - help='Purchase Requisitions are used when you want to request quotations from several suppliers for a given set of products.\n' - 'You can configure per product if you directly do a Request for Quotation ' - 'to one supplier or if you want a purchase requisition to negotiate with several suppliers.'), + 'module_purchase_requisition': fields.boolean("Manage calls for bids", + help="""Calls for bids are used when you want to generate requests for quotations to several suppliers for a given set of products. + You can configure per product if you directly do a Request for Quotation + to one supplier or if you want a Call for Bids to compare offers from several suppliers."""), + 'group_advance_purchase_requisition': fields.boolean("Choose from several bids in a call for bids", + implied_group='purchase.group_advance_bidding', + help="""In the process of a public bidding, you can compare the bid lines and choose for each requested product from which bid you + buy which quantity"""), 'module_purchase_analytic_plans': fields.boolean('Use multiple analytic accounts on purchase orders', help='Allows the user to maintain several analysis plans. These let you split lines on a purchase order between several accounts and analytic plans.\n' '-This installs the module purchase_analytic_plans.'), 'group_analytic_account_for_purchases': fields.boolean('Analytic accounting for purchases', implied_group='purchase.group_analytic_accounting', help="Allows you to specify an analytic account on purchase orders."), + 'module_stock_dropshipping': fields.boolean("Manage dropshipping", + help='\nCreates the dropship route and add more complex tests' + '-This installs the module stock_dropshipping.'), } _defaults = { diff --git a/addons/purchase/res_config_view.xml b/addons/purchase/res_config_view.xml index 276dc892392..4eaba80c306 100644 --- a/addons/purchase/res_config_view.xml +++ b/addons/purchase/res_config_view.xml @@ -66,6 +66,10 @@
+
+ +
+ + +
diff --git a/addons/purchase/security/ir.model.access.csv b/addons/purchase/security/ir.model.access.csv index 3c8d072c536..2b8f68c64e0 100644 --- a/addons/purchase/security/ir.model.access.csv +++ b/addons/purchase/security/ir.model.access.csv @@ -39,10 +39,6 @@ access_account_move,account.move,account.model_account_move,group_purchase_user, access_account_move_line,account.move.line,account.model_account_move_line,group_purchase_user,1,0,0,0 access_account_analytic_line,account.analytic.line,account.model_account_analytic_line,group_purchase_user,1,0,0,0 access_account_move_reconcile,account.move.reconcile,account.model_account_move_reconcile,group_purchase_user,1,0,0,0 -access_report_stock_move,report.stock.move.manager,stock.model_report_stock_move,group_purchase_manager,1,0,0,0 -access_report_stock_move_user,report.stock.move.user,stock.model_report_stock_move,group_purchase_user,1,0,0,0 -access_stock_production_lot_user,stock.production.lot user,stock.model_stock_production_lot,group_purchase_user,1,1,1,0 -access_stock_production_lot_revision,stock.production.lot.revision,stock.model_stock_production_lot_revision,group_purchase_user,1,1,1,0 access_res_partner_purchase_manager,res.partner.purchase.manager,base.model_res_partner,group_purchase_manager,1,1,1,0 access_product_uom_categ_purchase_manager,product.uom.categ purchase_manager,product.model_product_uom_categ,purchase.group_purchase_manager,1,1,1,1 access_product_uom_purchase_manager,product.uom purchase_manager,product.model_product_uom,purchase.group_purchase_manager,1,1,1,1 @@ -61,7 +57,8 @@ access_product_pricelist_version_purchase_manager,product.pricelist.version purc access_product_pricelist_item_purchase_manager,product.pricelist.item purchase_manager,product.model_product_pricelist_item,purchase.group_purchase_manager,1,1,1,1 access_account_account_purchase_manager,account.account purchase manager,account.model_account_account,purchase.group_purchase_manager,1,0,0,0 access_account_journal_purchase_manager,account.journal purchase manager,account.model_account_journal,purchase.group_purchase_manager,1,0,0,0 -access_stock_tracking_purchase_user,stock.tracking purchase.user,stock.model_stock_tracking,purchase.group_purchase_user,1,1,1,0 access_stock_location_purchase_manager,stock.location purchase manager,stock.model_stock_location,purchase.group_purchase_manager,1,0,0,0 -access_stock_warehouse_orderpoint_manager,stock.warehouse.orderpoint,procurement.model_stock_warehouse_orderpoint,purchase.group_purchase_manager,1,0,0,0 -access_stock_warehouse_orderpoint_manager,stock.warehouse.orderpoint,procurement.model_stock_warehouse_orderpoint,group_purchase_user,1,0,0,0 +access_stock_warehouse_orderpoint_manager,stock.warehouse.orderpoint,stock.model_stock_warehouse_orderpoint,purchase.group_purchase_manager,1,0,0,0 +access_stock_warehouse_orderpoint_manager,stock.warehouse.orderpoint,stock.model_stock_warehouse_orderpoint,group_purchase_user,1,0,0,0 +access_product_price_history_purchase_user,prices.history purchase user,product.model_product_price_history,purchase.group_purchase_user,1,0,0,0 +access_product_price_history_purchase_manager,prices.history purchase manager,product.model_product_price_history,purchase.group_purchase_manager,1,1,1,1 diff --git a/addons/purchase/security/purchase_security.xml b/addons/purchase/security/purchase_security.xml index 4e1cf8b6107..d8b2d320fb1 100644 --- a/addons/purchase/security/purchase_security.xml +++ b/addons/purchase/security/purchase_security.xml @@ -21,6 +21,11 @@
+ + Advance bidding process + + + diff --git a/addons/purchase/stock.py b/addons/purchase/stock.py index 2d5dea89d35..69d970b7be6 100644 --- a/addons/purchase/stock.py +++ b/addons/purchase/stock.py @@ -20,6 +20,7 @@ ############################################################################## from openerp.osv import fields, osv +from openerp.tools.translate import _ class stock_move(osv.osv): _inherit = 'stock.move' @@ -29,116 +30,145 @@ class stock_move(osv.osv): readonly=True), } + def write(self, cr, uid, ids, vals, context=None): + if isinstance(ids, (int, long)): + ids = [ids] + res = super(stock_move, self).write(cr, uid, ids, vals, context=context) + from openerp import workflow + if vals.get('state') in ['done', 'cancel']: + for move in self.browse(cr, uid, ids, context=context): + if move.purchase_line_id and move.purchase_line_id.order_id: + order_id = move.purchase_line_id.order_id.id + if self.pool.get('purchase.order').test_moves_done(cr, uid, [order_id], context=context): + workflow.trg_validate(uid, 'purchase.order', order_id, 'picking_done', cr) + if self.pool.get('purchase.order').test_moves_except(cr, uid, [order_id], context=context): + workflow.trg_validate(uid, 'purchase.order', order_id, 'picking_cancel', cr) + return res + + def copy(self, cr, uid, id, default=None, context=None): + if not default: + default = {} + if not default.get('split_from'): + #we don't want to propagate the link to the purchase order line except in case of move split + default.update({ + 'purchase_line_id': False, + }) + return super(stock_move, self).copy(cr, uid, id, default, context) -# -# Inherit of picking to add the link to the PO -# class stock_picking(osv.osv): _inherit = 'stock.picking' + + def _get_to_invoice(self, cr, uid, ids, name, args, context=None): + res = {} + for picking in self.browse(cr, uid, ids, context=context): + res[picking.id] = False + for move in picking.move_lines: + if move.purchase_line_id and move.purchase_line_id.order_id.invoice_method == 'picking': + if not move.move_orig_ids: + res[picking.id] = True + return res + + def _get_picking_to_recompute(self, cr, uid, ids, context=None): + picking_ids = set() + for move in self.pool.get('stock.move').browse(cr, uid, ids, context=context): + if move.picking_id and move.purchase_line_id: + picking_ids.add(move.picking_id.id) + return list(picking_ids) + _columns = { - 'purchase_id': fields.many2one('purchase.order', 'Purchase Order', - ondelete='set null', select=True), + 'reception_to_invoice': fields.function(_get_to_invoice, type='boolean', string='Invoiceable on incoming shipment?', + help='Does the picking contains some moves related to a purchase order invoiceable on the reception?', + store={ + 'stock.move': (_get_picking_to_recompute, ['purchase_line_id', 'picking_id'], 10), + }), } + +class stock_warehouse(osv.osv): + _inherit = 'stock.warehouse' + _columns = { + 'buy_to_resupply': fields.boolean('Purchase to resupply this warehouse', + help="When products are bought, they can be delivered to this warehouse"), + 'buy_pull_id': fields.many2one('procurement.rule', 'BUY rule'), + } _defaults = { - 'purchase_id': False, + 'buy_to_resupply': True, } - def _get_partner_to_invoice(self, cr, uid, picking, context=None): - """ Inherit the original function of the 'stock' module - We select the partner of the sale order as the partner of the customer invoice - """ - if picking.purchase_id: - return picking.purchase_id.partner_id - return super(stock_picking, self)._get_partner_to_invoice(cr, uid, picking, context=context) + def _get_buy_pull_rule(self, cr, uid, warehouse, context=None): + route_obj = self.pool.get('stock.location.route') + data_obj = self.pool.get('ir.model.data') + try: + buy_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_buy')[1] + except: + buy_route_id = route_obj.search(cr, uid, [('name', 'like', _('Buy'))], context=context) + buy_route_id = buy_route_id and buy_route_id[0] or False + if not buy_route_id: + raise osv.except_osv(_('Error!'), _('Can\'t find any generic Buy route.')) - def _prepare_invoice(self, cr, uid, picking, partner, inv_type, journal_id, context=None): - """ Inherit the original function of the 'stock' module in order to override some - values if the picking has been generated by a purchase order - """ - invoice_vals = super(stock_picking, self)._prepare_invoice(cr, uid, picking, partner, inv_type, journal_id, context=context) - if picking.purchase_id: - invoice_vals['fiscal_position'] = picking.purchase_id.fiscal_position.id - invoice_vals['payment_term'] = picking.purchase_id.payment_term_id.id - # Fill the date_due on the invoice, for usability purposes. - # Note that when an invoice with a payment term is validated, the - # date_due is always recomputed from the invoice date and the payment - # term. - if picking.purchase_id.payment_term_id and context.get('date_inv'): - invoice_vals['date_due'] = self.pool.get('account.invoice').onchange_payment_term_date_invoice(cr, uid, [], picking.purchase_id.payment_term_id.id, context.get('date_inv'))['value'].get('date_due') - return invoice_vals + return { + 'name': self._format_routename(cr, uid, warehouse, _(' Buy'), context=context), + 'location_id': warehouse.in_type_id.default_location_dest_id.id, + 'route_id': buy_route_id, + 'action': 'buy', + 'picking_type_id': warehouse.in_type_id.id, + 'propagate': False, + 'warehouse_id': warehouse.id, + } - def get_currency_id(self, cursor, user, picking): - if picking.purchase_id: - return picking.purchase_id.currency_id.id - else: - return super(stock_picking, self).get_currency_id(cursor, user, picking) + def create_routes(self, cr, uid, ids, warehouse, context=None): + pull_obj = self.pool.get('procurement.rule') + res = super(stock_warehouse, self).create_routes(cr, uid, ids, warehouse, context=context) + if warehouse.buy_to_resupply: + buy_pull_vals = self._get_buy_pull_rule(cr, uid, warehouse, context=context) + buy_pull_id = pull_obj.create(cr, uid, buy_pull_vals, context=context) + res['buy_pull_id'] = buy_pull_id + return res - def _get_comment_invoice(self, cursor, user, picking): - if picking.purchase_id and picking.purchase_id.notes: - if picking.note: - return picking.note + '\n' + picking.purchase_id.notes + def write(self, cr, uid, ids, vals, context=None): + pull_obj = self.pool.get('procurement.rule') + if isinstance(ids, (int, long)): + ids = [ids] + + if 'buy_to_resupply' in vals: + if vals.get("buy_to_resupply"): + for warehouse in self.browse(cr, uid, ids, context=context): + if not warehouse.buy_pull_id: + buy_pull_vals = self._get_buy_pull_rule(cr, uid, warehouse, context=context) + buy_pull_id = pull_obj.create(cr, uid, buy_pull_vals, context=context) + vals['buy_pull_id'] = buy_pull_id else: - return picking.purchase_id.notes - return super(stock_picking, self)._get_comment_invoice(cursor, user, picking) + for warehouse in self.browse(cr, uid, ids, context=context): + if warehouse.buy_pull_id: + buy_pull_id = pull_obj.unlink(cr, uid, warehouse.buy_pull_id.id, context=context) + return super(stock_warehouse, self).write(cr, uid, ids, vals, context=None) - def _get_price_unit_invoice(self, cursor, user, move_line, type): - if move_line.purchase_line_id: - if move_line.purchase_line_id.order_id.invoice_method == 'picking': - return move_line.price_unit - else: - return move_line.purchase_line_id.price_unit - return super(stock_picking, self)._get_price_unit_invoice(cursor, user, move_line, type) + def get_all_routes_for_wh(self, cr, uid, warehouse, context=None): + all_routes = super(stock_warehouse, self).get_all_routes_for_wh(cr, uid, warehouse, context=context) + if warehouse.buy_to_resupply and warehouse.buy_pull_id and warehouse.buy_pull_id.route_id: + all_routes += [warehouse.buy_pull_id.route_id.id] + return all_routes - def _get_discount_invoice(self, cursor, user, move_line): - if move_line.purchase_line_id: - return 0.0 - return super(stock_picking, self)._get_discount_invoice(cursor, user, move_line) + def _get_all_products_to_resupply(self, cr, uid, warehouse, context=None): + res = super(stock_warehouse, self)._get_all_products_to_resupply(cr, uid, warehouse, context=context) + if warehouse.buy_pull_id and warehouse.buy_pull_id.route_id: + for product_id in res: + for route in self.pool.get('product.product').browse(cr, uid, product_id, context=context).route_ids: + if route.id == warehouse.buy_pull_id.route_id.id: + res.remove(product_id) + break + return res - def _get_taxes_invoice(self, cursor, user, move_line, type): - if move_line.purchase_line_id: - return [x.id for x in move_line.purchase_line_id.taxes_id] - return super(stock_picking, self)._get_taxes_invoice(cursor, user, move_line, type) + def _handle_renaming(self, cr, uid, warehouse, name, code, context=None): + res = super(stock_warehouse, self)._handle_renaming(cr, uid, warehouse, name, code, context=context) + pull_obj = self.pool.get('procurement.rule') + #change the buy pull rule name + if warehouse.buy_pull_id: + pull_obj.write(cr, uid, warehouse.buy_pull_id.id, {'name': warehouse.buy_pull_id.name.replace(warehouse.name, name, 1)}, context=context) + return res - def _get_account_analytic_invoice(self, cursor, user, picking, move_line): - if picking.purchase_id and move_line.purchase_line_id: - return move_line.purchase_line_id.account_analytic_id.id - return super(stock_picking, self)._get_account_analytic_invoice(cursor, user, picking, move_line) - - def _invoice_line_hook(self, cursor, user, move_line, invoice_line_id): - if move_line.purchase_line_id: - invoice_line_obj = self.pool.get('account.invoice.line') - purchase_line_obj = self.pool.get('purchase.order.line') - purchase_line_obj.write(cursor, user, [move_line.purchase_line_id.id], { - 'invoice_lines': [(4, invoice_line_id)], - }) - return super(stock_picking, self)._invoice_line_hook(cursor, user, move_line, invoice_line_id) - - def _invoice_hook(self, cursor, user, picking, invoice_id): - purchase_obj = self.pool.get('purchase.order') - if picking.purchase_id: - purchase_obj.write(cursor, user, [picking.purchase_id.id], {'invoice_ids': [(4, invoice_id)]}) - return super(stock_picking, self)._invoice_hook(cursor, user, picking, invoice_id) - -class stock_partial_picking(osv.osv_memory): - _inherit = 'stock.partial.picking' - - # Overridden to inject the purchase price as true 'cost price' when processing - # incoming pickings. - def _product_cost_for_average_update(self, cr, uid, move): - if move.picking_id.purchase_id: - return {'cost': move.purchase_line_id.price_unit, - 'currency': move.picking_id.purchase_id.currency_id.id} - return super(stock_partial_picking, self)._product_cost_for_average_update(cr, uid, move) - -# Redefinition of the new field in order to update the model stock.picking.in in the orm -# FIXME: this is a temporary workaround because of a framework bug (ref: lp996816). It should be removed as soon as -# the bug is fixed -class stock_picking_in(osv.osv): - _inherit = 'stock.picking.in' - _columns = { - 'purchase_id': fields.many2one('purchase.order', 'Purchase Order', - ondelete='set null', select=True), - 'warehouse_id': fields.related('purchase_id', 'warehouse_id', type='many2one', relation='stock.warehouse', string='Destination Warehouse', readonly=True), - } -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: + def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None): + res = super(stock_warehouse, self).change_route(cr, uid, ids, warehouse, new_reception_step=new_reception_step, new_delivery_step=new_delivery_step, context=context) + if warehouse.in_type_id.default_location_dest_id != warehouse.buy_pull_id.location_id: + self.pool.get('procurement.rule').write(cr, uid, warehouse.buy_pull_id.id, {'location_id': warehouse.in_type_id.default_location_dest_id.id}, context=context) + return res diff --git a/addons/purchase/stock_view.xml b/addons/purchase/stock_view.xml index 33972c90fb6..2a514535714 100644 --- a/addons/purchase/stock_view.xml +++ b/addons/purchase/stock_view.xml @@ -12,27 +12,13 @@
- - Incoming Picking Inherited - stock.picking.in - - - - - - - - - - - stock.picking.in.search.inherit - stock.picking.in - + stock.picking + - + @@ -62,16 +48,26 @@
+ + + Stock Warehouse Inherited + stock.warehouse + + + + + + + - + On Incoming Shipments - stock.picking.in + stock.picking ir.actions.act_window form tree,form,calendar - [('type','=','in'),('purchase_id.invoice_method','=','picking')] - {"default_type": "in", "contact_display": "partner_address", "search_default_done": 1, "search_default_to_invoice": 1} - + {"default_type": "in", "contact_display": "partner_address", "search_default_done": 1, "search_default_reception_to_invoice": 1} +

Click to create a new incoming shipment. @@ -84,8 +80,8 @@ - diff --git a/addons/purchase/test/average_price.yml b/addons/purchase/test/average_price.yml new file mode 100644 index 00000000000..5d5d6e33943 --- /dev/null +++ b/addons/purchase/test/average_price.yml @@ -0,0 +1,135 @@ +- + Set a product as using average price. +- + !record {model: product.product, id: product_average_icecream}: + default_code: AVG + name: Average Ice Cream + type: product + categ_id: product.product_category_1 + uom_id: product.product_uom_kgm + uom_po_id: product.product_uom_kgm + valuation: real_time + cost_method: average + property_stock_account_input: account.o_expense + property_stock_account_output: account.o_income + description: Average Ice Cream can be mass-produced and thus is widely available in developed parts of the world. Ice cream can be purchased in large cartons (vats and squrounds) from supermarkets and grocery stores, in smaller quantities from ice cream shops, convenience stores, and milk bars, and in individual servings from small carts or vans at public events. +- + I create a draft Purchase Order for first incoming shipment for 10 pieces at 60€ +- + !record {model: purchase.order, id: purchase_order_average1}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_average_icecream + product_qty: 10.0 + product_uom: product.product_uom_kgm + price_unit: 60.0 + name: 'Average Ice Cream' +- + I confirm the first purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_average1} +- + I check the "Approved" status of purchase order 1 +- + !assert {model: purchase.order, id: purchase_order_average1}: + - state == 'approved' +- + Process the reception of purchase order 1 +- + !python {model: stock.picking}: | + pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_average1")).picking_ids + self.do_transfer(cr, uid, [pick_ids[0].id]) +- + Check the standard price of the product (average icecream). +- + !python {model: product.product}: | + product = self.browse(cr, uid, ref("product_average_icecream")) + assert product.qty_available == 10.0, 'Wrong quantity in stock after first reception' + assert product.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€ +- + !record {model: purchase.order, id: purchase_order_average2}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_average_icecream + product_qty: 30.0 + product_uom: product.product_uom_kgm + price_unit: 80.0 + name: 'Average Ice Cream' +- + I confirm the second purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_average2} +- + Process the reception of purchase order 2 +- + !python {model: stock.picking}: | + pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_average2")).picking_ids + self.do_transfer(cr, uid, [pick_ids[0].id]) +- + Check the standard price +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_average_icecream")).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 +- + !record {model: stock.picking, id: outgoing_average_shipment}: + picking_type_id: stock.picking_type_out +- + Create move for picking +- + !record {model: stock.move, id: outgoing_shipment_average_icecream}: + picking_id: outgoing_average_shipment + product_id: product_average_icecream + product_uom: product.product_uom_kgm + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers + product_uom_qty: 20.0 +- + I assign this outgoing shipment and process the delivery +- + !python {model: stock.picking}: | + self.action_assign(cr, uid, [ref("outgoing_average_shipment")]) + self.do_transfer(cr, uid, [ref("outgoing_average_shipment")]) +- + Check the standard price (60 * 10 + 30 * 80) / 40 = 75.0 did not change +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_average_icecream")).standard_price == 75.0, 'Standard price should not have changed with outgoing picking!' + assert self.browse(cr, uid, ref("product_average_icecream")).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 +- + !record {model: purchase.order, id: purchase_order_average3}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_average_icecream + product_qty: 500.0 + product_uom: product.product_uom_gram + price_unit: 0.2 + name: 'Average Ice Cream' +- + I confirm the first purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_average3} +- + Process the reception of purchase order 3 in grams +- + !python {model: stock.picking}: | + pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_average3")).picking_ids + self.do_transfer(cr, uid, [pick_ids[0].id]) +- + Check price is (75.0*20 + 200*0.5) / 20.5 = 78.04878 +- + !python {model: product.product}: | + product = self.browse(cr, uid, ref("product_average_icecream")) + assert product.qty_available == 20.5, 'Reception of purchase order in grams leads to wrong quantity in stock' + assert round(self.browse(cr, uid, ref("product_average_icecream")).standard_price, 2) == 78.05, 'Standard price as average price of third reception with other UoM incorrect! Got %s instead of 78.05' % (round(self.browse(cr, uid, ref("product_average_icecream")).standard_price, 2),) diff --git a/addons/purchase/test/costmethodchange.yml b/addons/purchase/test/costmethodchange.yml new file mode 100644 index 00000000000..f6b79587985 --- /dev/null +++ b/addons/purchase/test/costmethodchange.yml @@ -0,0 +1,142 @@ +- + Set a product as using average price. +- + !record {model: product.product, id: product_variable_icecream}: + default_code: AVG + name: Variable Ice Cream + type: product + categ_id: product.product_category_1 + uom_id: product.product_uom_kgm + uom_po_id: product.product_uom_kgm + procure_method: make_to_stock + valuation: real_time + cost_method: average + property_stock_account_input: account.o_expense + property_stock_account_output: account.o_income + description: Average Ice Cream can be mass-produced and thus is widely available in developed parts of the world. Ice cream can be purchased in large cartons (vats and squrounds) from supermarkets and grocery stores, in smaller quantities from ice cream shops, convenience stores, and milk bars, and in individual servings from small carts or vans at public events. +- + I create a draft Purchase Order for first incoming shipment for 10 pieces at 60€ +- + !record {model: purchase.order, id: purchase_order_variable1}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_variable_icecream + product_qty: 10.0 + product_uom: product.product_uom_categ_kgm + price_unit: 60.0 + name: 'Average Ice Cream' +- + I create a draft Purchase Order for second incoming shipment for 30 pieces at 80€ +- + !record {model: purchase.order, id: purchase_order_variable2}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_variable_icecream + product_qty: 30.0 + product_uom: product.product_uom_categ_kgm + price_unit: 80.0 + name: 'Average Ice Cream' +- + I confirm the first purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_variable1} +- + I confirm the second purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_variable2} +- + I check the "Approved" status of purchase order 1 +- + !assert {model: purchase.order, id: purchase_order_variable1}: + - state == 'approved' +- + Process the reception of purchase order 1 +- + !python {model: stock.partial.picking}: | + pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_variable1")).picking_ids + partial_id = self.create(cr, uid, {}, context={'active_model': 'stock.picking','active_ids': [pick_ids[0].id]}) + self.do_transfer(cr, uid, [partial_id]) +- + Check the standard price of the product (variable icecream). +- + !python {model: product.product}: | + product = self.browse(cr, uid, ref("product_variable_icecream")) + assert product.qty_available == 10.0, 'Wrong quantity in stock after first reception' + assert product.standard_price == 60.0, 'Standard price should be the price of the first reception!' +- + Process the reception of purchase order 2 +- + !python {model: stock.partial.picking}: | + pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_variable2")).picking_ids + partial_id = self.create(cr, uid, {}, context={'active_model': 'stock.picking','active_ids': [pick_ids[0].id]}) + self.do_transfer(cr, uid, [partial_id]) +- + Check the standard price and change the product's cost method towards fifo +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_variable_icecream")).standard_price == 75.0, 'After second reception, we should have an average price of 75.0 on the product' + self.write(cr, uid, [ref("product_variable_icecream")], {'cost_method': 'real'}, context=context) +- + Create picking to send some goods +- + !record {model: stock.picking, id: outgoing_variable_shipment}: + type: out +- + Create move for picking +- + !record {model: stock.move, id: outgoing_shipment_variable_icecream}: + picking_id: outgoing_variable_shipment + product_id: product_variable_icecream + product_uom: product.product_uom_kgm + product_qty: 20.0 + type: out +- + I confirm outgoing shipment of 20 kg of Variable Ice Cream. +- + !workflow {model: stock.picking, action: button_confirm, ref: outgoing_variable_shipment} +- + Process the delivery of the outgoing shipment +- + !python {model: stock.partial.picking}: | + partial_id = self.create(cr, uid, {}, context={'active_model': 'stock.picking','active_ids': [ref("outgoing_variable_shipment")], 'default_type':'out'}) + self.do_transfer(cr, uid, [partial_id]) +- + Check the standard price (60 * 10 + 30 * 80) / 40 = 75.0 did not change +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_variable_icecream")).standard_price == 75.0, 'Standard price should not have changed with outgoing picking!' + assert self.browse(cr, uid, ref("product_variable_icecream")).qty_available == 20.0, 'Pieces were not picked correctly as the quantity on hand is wrong' +- + I create a draft Purchase Order for third incoming shipment for 20 pieces at 60 euro +- + !record {model: purchase.order, id: purchase_order_variable3}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_variable_icecream + product_qty: 20.0 + product_uom: product.product_uom_categ_kgm + price_unit: 60.0 + name: 'Variable Ice Cream' +- + I confirm this third purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_variable3} +- + Process the reception of purchase order 3 +- + !python {model: stock.partial.picking}: | + pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_variable3")).picking_ids + partial_id = self.create(cr, uid, {}, context={'active_model': 'stock.picking','active_ids': [pick_ids[0].id]}) + self.do_transfer(cr, uid, [partial_id]) +- + Change the cost method back to average and check price on product changed back to 70.0 = (20*60 + 10*60 + 30*80) / 60 +- + !python {model: product.product}: | + self.write(cr, uid, [ref("product_variable_icecream")], {'cost_method': 'average'}, context=context) + assert self.browse(cr, uid, ref("product_variable_icecream")).standard_price == 70.0, 'After third reception and changing to average again, we should have an average price of 70.0 on the product' diff --git a/addons/purchase/test/fifo_price.yml b/addons/purchase/test/fifo_price.yml new file mode 100644 index 00000000000..07bcd4f3070 --- /dev/null +++ b/addons/purchase/test/fifo_price.yml @@ -0,0 +1,385 @@ +- + Set a product as using fifo price +- + !record {model: product.product, id: product_fifo_icecream}: + default_code: FIFO + name: FIFO Ice Cream + type: product + categ_id: product.product_category_1 + list_price: 100.0 + standard_price: 70.0 + uom_id: product.product_uom_kgm + uom_po_id: product.product_uom_kgm + cost_method: real + valuation: real_time + property_stock_account_input: account.o_expense + property_stock_account_output: account.o_income + description: FIFO Ice Cream can be mass-produced and thus is widely available in developed parts of the world. Ice cream can be purchased in large cartons (vats and squrounds) from supermarkets and grocery stores, in smaller quantities from ice cream shops, convenience stores, and milk bars, and in individual servings from small carts or vans at public events. +- + I create a draft Purchase Order for first in move for 10 kg at 50 euro +- + !record {model: purchase.order, id: purchase_order_fifo1}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_fifo_icecream + product_qty: 10.0 + product_uom: product.product_uom_kgm + price_unit: 50.0 + name: 'FIFO Ice Cream' +- + I confirm the first purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_fifo1} +- + I check the "Approved" status of purchase order 1 +- + !assert {model: purchase.order, id: purchase_order_fifo1}: + - state == 'approved' +- + Process the reception of purchase order 1 and set date +- + !python {model: stock.picking}: | + picking_obj = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_fifo1")).picking_ids[0] + picking_obj.do_transfer(context=context) +- + Check the standard price of the product (fifo icecream), that should have not changed because the standard price is supposed to be updated only when goods are going out of the stock +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_fifo_icecream")).standard_price == 70.0, 'Standard price should not have changed!' +- + I create a draft Purchase Order for second shipment for 30 kg at 80 euro +- + !record {model: purchase.order, id: purchase_order_fifo2}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_fifo_icecream + product_qty: 30.0 + product_uom: product.product_uom_kgm + price_unit: 80.0 + name: 'FIFO Ice Cream' +- + I confirm the second purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_fifo2} +- + Process the reception of purchase order 2 +- + !python {model: stock.picking}: | + picking_obj = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_fifo2")).picking_ids[0] + picking_obj.do_transfer(context=context) +- + Check the standard price of the product, that should have not changed because the standard price is supposed to be updated only when goods are going out of the stock +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_fifo_icecream")).standard_price == 70.0, 'Standard price as fifo price of second reception incorrect!' +- + Let us send some goods +- + !record {model: stock.picking, id: outgoing_fifo_shipment}: + picking_type_id: stock.picking_type_out +- + Picking needs movement from stock +- + !record {model: stock.move, id: outgoing_shipment_fifo_icecream}: + picking_id: outgoing_fifo_shipment + product_id: product_fifo_icecream + product_uom: product.product_uom_kgm + product_uom_qty: 20.0 + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers + picking_type_id: stock.picking_type_out +- + I assign this outgoing shipment +- + !python {model: stock.picking}: | + self.action_assign(cr, uid, [ref("outgoing_fifo_shipment")]) +- + Process the delivery of the outgoing shipment +- + !python {model: stock.picking}: | + pick_obj = self.pool.get('stock.picking').browse(cr, uid, ref("outgoing_fifo_shipment")) + pick_obj.do_transfer(context=context) +- + Check product standard price changed to 65.0 (because last outgoing shipment was made of 10 kg at 50€ and 10 kg at 80€) +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_fifo_icecream")).standard_price == 65.0, "Product price not updated accordingly. %s found instead of 65" %(self.browse(cr, uid, ref("product_fifo_icecream")).standard_price,) +- + Do a delivery of an extra 500 g (delivery order) +- + !record {model: stock.picking, id: outgoing_fifo_shipment_uom}: + picking_type_id: stock.picking_type_out +- + Picking needs movement from stock +- + !record {model: stock.move, id: outgoing_shipment_fifo_icecream_gram}: + picking_id: outgoing_fifo_shipment_uom + product_id: product_fifo_icecream + product_uom: product.product_uom_gram + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers + product_uom_qty: 500.0 + picking_type_id: stock.picking_type_out +- + I assign this outgoing shipment +- + !python {model: stock.picking}: | + self.action_assign(cr, uid, [ref("outgoing_fifo_shipment_uom")]) +- + Process the delivery of the outgoing shipment +- + !python {model: stock.picking}: | + pick_obj = self.pool.get('stock.picking').browse(cr, uid, ref("outgoing_fifo_shipment_uom")) + pick_obj.do_transfer(context=context) +- + Check product price changed to 80.0 (because last outgoing shipment was made of 0.5 kg at 80€) +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_fifo_icecream")).standard_price == 80.0, "Product price not updated accordingly. %s found instead of 80" %(self.browse(cr, uid, ref("product_fifo_icecream")).standard_price,) +- + We will temporarily change the currency rate on the sixth of June to have the same results all year +- + !record {model: res.currency.rate, id: base.rateUSDbis}: + rate: 1.2834 + currency_id: base.USD + name: !eval time.strftime('%Y-06-06') +- + Create new pricelist in usd +- + !record {model: product.pricelist, id: supplier_pricelist_usd}: + name: Supplier Pricelist + type: purchase + currency_id: base.USD + version_id: + - name: v1.0 + items_id: + - name: First version + sequence: 1 + price_min_margin: 2 + price_max_margin: 5 + product_id: product_fifo_icecream + base: -2 +- + Purchase order in usd +- + I create a draft Purchase Order for 30000 g at 0.150 USD/g and 10 kg at 150 USD/kg +- + !record {model: purchase.order, id: purchase_order_fifo_usd}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: supplier_pricelist_usd + order_line: + - product_id: product_fifo_icecream + product_qty: 30000 + product_uom: product.product_uom_gram + price_unit: 0.150 + name: 'FIFO Ice Cream' + - product_id: product_fifo_icecream + product_qty: 10.0 + product_uom: product.product_uom_kgm + price_unit: 150.0 +- + I confirm the purchase order in USD +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_fifo_usd} +- + Process the reception of purchase order with usd +- + !python {model: stock.picking}: | + pick_obj = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_fifo_usd")).picking_ids[0] + pick_obj.do_transfer(context=context) +- + We create delivery order of 49.5 kg +- + !record {model: stock.picking, id: outgoing_fifo_shipment_cur}: + picking_type_id: stock.picking_type_out +- + Picking needs movement from stock +- + !record {model: stock.move, id: outgoing_shipment_fifo_icecream_cur}: + picking_id: outgoing_fifo_shipment_cur + product_id: product_fifo_icecream + product_uom: product.product_uom_kgm + product_uom_qty: 49.5 + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers + picking_type_id: stock.picking_type_out +- + I assign this outgoing shipment +- + !python {model: stock.picking}: | + self.action_assign(cr, uid, [ref("outgoing_fifo_shipment_cur")]) +- + Process the delivery of the outgoing shipment +- + !python {model: stock.picking}: | + picking_obj = self.pool.get('stock.picking').browse(cr, uid, ref("outgoing_fifo_shipment_cur")) + picking_obj.do_transfer(context=context) +- + Check rounded price is 102 euro (because last outgoing shipment was made of 19.5kg at 80€ and 30kg at $150 (rate=1.2834) +- + !python {model: product.product}: | + assert round(self.browse(cr, uid, ref("product_fifo_icecream")).standard_price) == 102, "Product price not updated accordingly. %s found instead of 102 (rounded values)" %(round(self.browse(cr, uid, ref("product_fifo_icecream")).standard_price),) +- + Do a delivery of an extra 10 kg +- + !record {model: stock.picking, id: outgoing_fifo_shipment_ret}: + picking_type_id: stock.picking_type_out +- + Picking needs movement from stock +- + !record {model: stock.move, id: outgoing_shipment_fifo_icecream_ret}: + picking_id: outgoing_fifo_shipment_ret + product_id: product_fifo_icecream + product_uom: product.product_uom_kgm + product_uom_qty: 10.0 + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers + picking_type_id: stock.picking_type_out +- + I assign this outgoing shipment +- + !python {model: stock.picking}: | + self.action_assign(cr, uid, [ref("outgoing_fifo_shipment_ret")]) +- + Process the delivery of the outgoing shipment +- + !python {model: stock.picking}: | + picking_obj = self.pool.get('stock.picking').browse(cr, uid, ref("outgoing_fifo_shipment_ret")) + picking_obj.do_transfer(context=context) +- + Check rounded price is 150.0 / 1.2834 +- + !python {model: product.product}: | + product = self.browse(cr, uid, ref("product_fifo_icecream")) + assert round(product.standard_price) == round(150.0 / 1.2834), "Product price not updated accordingly. %s found instead of %s" %(product.standard_price, round(150.0/1.2834)) + assert product.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 +- + !record {model: product.product, id: product_fifo_negative}: + default_code: NEG + name: FIFO Negative + type: product + categ_id: product.product_category_1 + list_price: 100.0 + standard_price: 70.0 + uom_id: product.product_uom_kgm + uom_po_id: product.product_uom_kgm + cost_method: real + valuation: real_time + property_stock_account_input: account.o_expense + property_stock_account_output: account.o_income + description: +- + Create outpicking. We create delivery order of 100 kg. +- + !record {model: stock.picking, id: outgoing_fifo_shipment_neg}: + picking_type_id: stock.picking_type_out +- + Picking needs movement from stock +- + !record {model: stock.move, id: outgoing_shipment_fifo_icecream_neg}: + picking_id: outgoing_fifo_shipment_neg + product_id: product_fifo_negative + product_uom: product.product_uom_kgm + product_uom_qty: 100.0 + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers + picking_type_id: stock.picking_type_out +- + Process the delivery of the first outgoing shipment +- + !python {model: stock.picking}: | + picking_obj = self.browse(cr, uid, ref("outgoing_fifo_shipment_neg")) + picking_obj.do_transfer(context=context) +- + The behavior of fifo/lifo is not garantee if the quants are created at the same second, so i just wait one second +- + !python {model: stock.picking}: | + import time + time.sleep(1) +- + Let us create another out of 400 kg +- + !record {model: stock.picking, id: outgoing_fifo_shipment_neg2}: + picking_type_id: stock.picking_type_out +- + Picking needs movement from stock +- + !record {model: stock.move, id: outgoing_shipment_fifo_icecream_neg2}: + picking_id: outgoing_fifo_shipment_neg2 + product_id: product_fifo_negative + product_uom: product.product_uom_kgm + product_uom_qty: 400.0 + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers + picking_type_id: stock.picking_type_out +- + Process the delivery of the outgoing shipments +- + !python {model: stock.picking}: | + picking_obj1 = self.browse(cr, uid, ref("outgoing_fifo_shipment_neg2")) + picking_obj1.do_transfer(context=context) + +- + Receive purchase order with 50 kg FIFO Ice Cream at 50 euro/kg +- + !record {model: purchase.order, id: purchase_order_fifo_neg}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_fifo_negative + product_qty: 50.0 + product_uom: product.product_uom_kgm + price_unit: 50.0 + name: 'FIFO Ice Cream' +- + I confirm the first purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_fifo_neg} +- + Process the reception of purchase order 1 +- + !python {model: stock.picking}: | + picking_obj = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_fifo_neg")).picking_ids[0] + picking_obj.do_transfer(context=context) +- + Assert price on product is still the old price as the out move has not been received fully yet +- + !python {model: product.product}: | + + assert self.browse(cr, uid, ref("product_fifo_negative")).standard_price == 70, 'The product price should not have been updated' +- + Receive purchase order with 60 kg FIFO Ice Cream at 80 euro/kg +- + !record {model: purchase.order, id: purchase_order_fifo_neg2}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_fifo_negative + product_qty: 60.0 + product_uom: product.product_uom_kgm + price_unit: 80 + name: 'FIFO Ice Cream' +- + I confirm the second negative purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_fifo_neg2} +- + Process the reception of purchase order 2 +- + !python {model: stock.picking}: | + picking_obj = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_fifo_neg2")).picking_ids[0] + picking_obj.do_transfer(context=context) +- + The price of the product should have changed back to 65.0 +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_fifo_negative")).standard_price == 65.0, "Product price not updated accordingly. %s found instead of 65" %(self.browse(cr, uid, ref("product_fifo_negative")).standard_price,) diff --git a/addons/purchase/test/fifo_returns.yml b/addons/purchase/test/fifo_returns.yml new file mode 100644 index 00000000000..50cddf25675 --- /dev/null +++ b/addons/purchase/test/fifo_returns.yml @@ -0,0 +1,80 @@ +- + Set a product as using fifo price +- + !record {model: product.product, id: product_fiforet_icecream}: + default_code: FIFO + name: FIFO Ice Cream + type: product + standard_price: 0.0 + categ_id: product.product_category_1 + uom_id: product.product_uom_kgm + uom_po_id: product.product_uom_kgm + cost_method: real + valuation: real_time + property_stock_account_input: account.o_expense + property_stock_account_output: account.o_income + description: FIFO Ice Cream can be mass-produced and thus is widely available in developed parts of the world. Ice cream can be purchased in large cartons (vats and squrounds) from supermarkets and grocery stores, in smaller quantities from ice cream shops, convenience stores, and milk bars, and in individual servings from small carts or vans at public events. +- + I create a draft Purchase Order for first in move for 10 kg at 50 euro +- + !record {model: purchase.order, id: purchase_order_fiforet1}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_fiforet_icecream + product_qty: 10.0 + product_uom: product.product_uom_kgm + price_unit: 50.0 + name: 'FIFO Ice Cream' +- + I create a draft Purchase Order for second shipment for 30 kg at 80 euro +- + !record {model: purchase.order, id: purchase_order_fiforet2}: + partner_id: base.res_partner_3 + location_id: stock.stock_location_stock + pricelist_id: 1 + order_line: + - product_id: product_fiforet_icecream + product_qty: 30.0 + product_uom: product.product_uom_kgm + price_unit: 80.0 + name: 'FIFO Ice Cream' +- + I confirm the first purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_fiforet1} +- + Process the reception of purchase order 1 +- + !python {model: stock.picking}: | + picking_obj = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_fiforet1")).picking_ids[0] + self.do_transfer(cr,uid,[picking_obj.id], context=context) +- + Check the standard price of the product (fifo icecream) +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_fiforet_icecream")).standard_price == 0.0, 'Standard price should not have changed!' +- + I confirm the second purchase order +- + !workflow {model: purchase.order, action: purchase_confirm, ref: purchase_order_fiforet2} +- + Process the reception of purchase order 2 +- + !python {model: stock.picking}: | + picking_obj = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_fiforet2")).picking_ids[0] + self.do_transfer(cr,uid,[picking_obj.id], context=context) +- + Return the goods of purchase order 2 +- + !python {model: stock.return.picking}: | + pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_fiforet2")).picking_ids + return_id = self.create(cr, uid, {}, context={'active_model':'stock.picking', 'active_id': pick_ids[0].id}) + return_picking_id, dummy = self._create_returns(cr, uid, [return_id], context={'active_id': pick_ids[0].id}) + self.pool.get('stock.picking').do_transfer(cr, uid, [return_picking_id]) +- + Check the standard price of the product changed to 80.0 as we returned the quants of purchase order 2 +- + !python {model: product.product}: | + assert self.browse(cr, uid, ref("product_fiforet_icecream")).standard_price == 80.0, 'Standard price should have changed to 80.0! %s found instead' % (self.browse(cr, uid, ref("product_fiforet_icecream")).standard_price,) diff --git a/addons/purchase/test/process/generate_invoice_from_reception.yml b/addons/purchase/test/process/generate_invoice_from_reception.yml index 565f52f258f..6e3a7d3d8e0 100644 --- a/addons/purchase/test/process/generate_invoice_from_reception.yml +++ b/addons/purchase/test/process/generate_invoice_from_reception.yml @@ -16,9 +16,9 @@ - Now I create an invoice for order on reception. - - !python {model: stock.picking}: | - pick_ids = self.search(cr, uid, [('purchase_id','=',ref('purchase_order_2'))]) - self.action_invoice_create(cr, uid, pick_ids, ref('account.expenses_journal')) + !python {model: purchase.order}: | + pick_ids = [self.browse(cr, uid, ref("purchase_order_2")).id] + self.action_invoice_create(cr, uid, pick_ids) - I check that the invoice of order. - diff --git a/addons/purchase/test/process/merge_order.yml b/addons/purchase/test/process/merge_order.yml index dcf2616e79e..ff977033ee7 100644 --- a/addons/purchase/test/process/merge_order.yml +++ b/addons/purchase/test/process/merge_order.yml @@ -8,10 +8,10 @@ - !python {model: purchase.order}: | context.update({"mail_create_nolog" : True }) - new_id = self.do_merge(cr, uid, [ref('purchase_order_4'), ref('purchase_order_7')], context=context) order3 = self.browse(cr, uid, ref('purchase_order_4')) order7 = self.browse(cr, uid, ref('purchase_order_7')) total_qty = sum([x.product_qty for x in order3.order_line] + [x.product_qty for x in order7.order_line]) + new_id = self.do_merge(cr, uid, [ref('purchase_order_4'), ref('purchase_order_7')], context=context) assert order3.state == 'cancel', "Merged order should be canceled" assert order7.state == 'cancel', "Merged order should be canceled" @@ -25,14 +25,12 @@ product_uom.append(line.product_uom.id) res.update({'product_ids': product_id,'product_uom':product_uom}) return res - for order in self.browse(cr, uid, new_id.keys()): total_new_qty = [x.product_qty for x in order.order_line] total_new_qty = sum(total_new_qty) assert total_new_qty == total_qty,"product quantities are not correspond" assert order.partner_id == order3.partner_id ,"partner is not correspond" - assert order.warehouse_id == order3.warehouse_id or order7.warehouse_id,"Warehouse is not correspond" assert order.state == 'draft',"New created order state should be in draft" assert order.pricelist_id == order3.pricelist_id,"Price list is not correspond" assert order.date_order == order3.date_order ,"Date of order is not correspond" diff --git a/addons/purchase/test/process/rfq2order2done.yml b/addons/purchase/test/process/rfq2order2done.yml index ff9158b3c09..54de507286c 100644 --- a/addons/purchase/test/process/rfq2order2done.yml +++ b/addons/purchase/test/process/rfq2order2done.yml @@ -45,10 +45,9 @@ - Reception is ready for process so now done the reception. - - !python {model: stock.partial.picking}: | - pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_1")).picking_ids - partial_id = self.create(cr, uid, {},context={'active_model': 'stock.picking','active_ids': [pick_ids[0].id]}) - self.do_partial(cr, uid, [partial_id]) + !python {model: stock.picking}: | + pick_ids = self.pool.get('purchase.order').browse(cr, uid, ref("purchase_order_1")).picking_ids[0] + pick_ids.do_transfer(context=context) - I check that purchase order is shipped. - diff --git a/addons/purchase/test/process/run_scheduler.yml b/addons/purchase/test/process/run_scheduler.yml index 8ac84a37125..d4c1da13cd7 100644 --- a/addons/purchase/test/process/run_scheduler.yml +++ b/addons/purchase/test/process/run_scheduler.yml @@ -1,18 +1,26 @@ - - In order to test the scheduler to generate RFQ. + In order to test the scheduler to generate RFQ, I create a new product +- + !record {model: product.product, id: scheduler_product}: + name: scheduler prod + type: product + seller_ids: + - delay: 1 + name: base.res_partner_2 + min_qty: 5.0 +- + Add Buy route +- + !python {model: product.product, id: scheduler_product}: | + self.write(cr, uid, [ref("scheduler_product")], {"route_ids": [(4, ref("purchase.route_warehouse0_buy"))]}) - I create a procurement order. - !record {model: procurement.order, id: procurement_order_testcase0}: location_id: stock.stock_location_stock name: Test scheduler for RFQ - procure_method: make_to_order - product_id: product.product_product_45 + product_id: scheduler_product product_qty: 15.0 -- - I confirm on procurement order. -- - !workflow {model: procurement.order, action: button_confirm, ref: procurement_order_testcase0} - I run the scheduler. - @@ -23,14 +31,12 @@ - !python {model: procurement.order}: | procurement = self.browse(cr, uid, ref('procurement_order_testcase0')) - assert procurement.purchase_id, 'RFQ should be generated!' + assert procurement.purchase_line_id, 'RFQ should be generated!' - I delete the line from the purchase order and check that the move and the procurement are cancelled - !python {model: procurement.order}: | procurement = self.browse(cr, uid, ref('procurement_order_testcase0')) - move = procurement.purchase_id.order_line[0].move_dest_id - procurement.purchase_id.order_line[0].unlink() - assert move.state == 'cancel', 'Move should be cancelled' + procurement.purchase_line_id.unlink() procurement.refresh() assert procurement.state == 'cancel', 'Procurement should be cancelled' diff --git a/addons/purchase/views/report_purchaseorder.xml b/addons/purchase/views/report_purchaseorder.xml index c03e535ff75..300149e4f1d 100644 --- a/addons/purchase/views/report_purchaseorder.xml +++ b/addons/purchase/views/report_purchaseorder.xml @@ -16,9 +16,9 @@

VAT:

-
- -
+ +

VAT:

diff --git a/addons/purchase/views/report_purchasequotation.xml b/addons/purchase/views/report_purchasequotation.xml index 68e8995ddd8..a18619f99f9 100644 --- a/addons/purchase/views/report_purchasequotation.xml +++ b/addons/purchase/views/report_purchasequotation.xml @@ -16,9 +16,9 @@ t-field-options='{"widget": "contact", "fields": ["address", "name", "phone", "fax"], "no_marker": true}'/>

VAT:

-
- -
+ +

VAT:

diff --git a/addons/purchase/wizard/purchase_order_group.py b/addons/purchase/wizard/purchase_order_group.py index 243f27efea4..70a6b3240ab 100644 --- a/addons/purchase/wizard/purchase_order_group.py +++ b/addons/purchase/wizard/purchase_order_group.py @@ -66,12 +66,7 @@ class purchase_order_group(osv.osv_memory): id = mod_obj.read(cr, uid, result, ['res_id']) allorders = order_obj.do_merge(cr, uid, context.get('active_ids',[]), context) - for new_order in allorders: - proc_ids = proc_obj.search(cr, uid, [('purchase_id', 'in', allorders[new_order])], context=context) - for proc in proc_obj.browse(cr, uid, proc_ids, context=context): - if proc.purchase_id: - proc_obj.write(cr, uid, [proc.id], {'purchase_id': new_order}, context) - + return { 'domain': "[('id','in', [" + ','.join(map(str, allorders.keys())) + "])]", 'name': _('Purchase Orders'), diff --git a/addons/purchase_requisition/__openerp__.py b/addons/purchase_requisition/__openerp__.py index 483ea4a0d56..e2d63967a5f 100644 --- a/addons/purchase_requisition/__openerp__.py +++ b/addons/purchase_requisition/__openerp__.py @@ -34,21 +34,23 @@ keep track and order all your purchase orders. """, 'depends' : ['purchase'], 'demo': ['purchase_requisition_demo.xml'], - 'data': ['security/purchase_tender.xml', + 'data': ['views/purchase_requisition.xml', + 'security/purchase_tender.xml', 'wizard/purchase_requisition_partner_view.xml', + 'wizard/bid_line_qty_view.xml', 'purchase_requisition_data.xml', 'purchase_requisition_view.xml', 'purchase_requisition_report.xml', + 'purchase_requisition_workflow.xml', 'security/ir.model.access.csv','purchase_requisition_sequence.xml', - 'views/report_purchaserequisition.xml', ], 'auto_install': False, 'test': [ 'test/purchase_requisition_users.yml', 'test/purchase_requisition_demo.yml', - 'test/purchase_requisition.yml', 'test/cancel_purchase_requisition.yml', + 'test/purchase_requisition.yml', ], 'installable': True, } diff --git a/addons/purchase_requisition/purchase_requisition.py b/addons/purchase_requisition/purchase_requisition.py index 319cceb1e1a..cdc56e3ad15 100644 --- a/addons/purchase_requisition/purchase_requisition.py +++ b/addons/purchase_requisition/purchase_requisition.py @@ -23,95 +23,155 @@ from datetime import datetime from dateutil.relativedelta import relativedelta import time -from openerp.osv import fields,osv +from openerp.osv import fields, osv from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp class purchase_requisition(osv.osv): _name = "purchase.requisition" - _description="Purchase Requisition" + _description = "Purchase Requisition" _inherit = ['mail.thread', 'ir.needaction_mixin'] + + def _get_po_line(self, cr, uid, ids, field_names, arg=None, context=None): + result = {}.fromkeys(ids, []) + for element in self.browse(cr, uid, ids, context=context): + for po in element.purchase_ids: + result[element.id] += [po_line.id for po_line in po.order_line] + return result + _columns = { - 'name': fields.char('Requisition Reference', size=32,required=True), + 'name': fields.char('Call for Bids Reference', size=32, required=True), 'origin': fields.char('Source Document', size=32), - 'date_start': fields.datetime('Requisition Date'), - 'date_end': fields.datetime('Requisition Deadline'), + 'ordering_date': fields.date('Scheduled Ordering Date'), + 'date_end': fields.datetime('Bid Submission Deadline'), + 'schedule_date': fields.date('Scheduled Date', select=True, help="The expected and scheduled date where all the products are received"), 'user_id': fields.many2one('res.users', 'Responsible'), - 'exclusive': fields.selection([('exclusive','Purchase Requisition (exclusive)'),('multiple','Multiple Requisitions')],'Requisition Type', required=True, help="Purchase Requisition (exclusive): On the confirmation of a purchase order, it cancels the remaining purchase order.\nMultiple Requisitions: It allows to have multiple purchase orders.On confirmation of a purchase order it does not cancel the remaining orders"""), + 'exclusive': fields.selection([('exclusive', 'Select only one RFQ (exclusive)'), ('multiple', 'Select multiple RFQ')], 'Bid Selection Type', required=True, help="Select only one RFQ (exclusive): On the confirmation of a purchase order, it cancels the remaining purchase order.\nSelect multiple RFQ: It allows to have multiple purchase orders.On confirmation of a purchase order it does not cancel the remaining orders"""), 'description': fields.text('Description'), 'company_id': fields.many2one('res.company', 'Company', required=True), - 'purchase_ids' : fields.one2many('purchase.order','requisition_id','Purchase Orders',states={'done': [('readonly', True)]}), - 'line_ids' : fields.one2many('purchase.requisition.line','requisition_id','Products to Purchase',states={'done': [('readonly', True)]}), - 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'), - 'state': fields.selection([('draft','New'),('in_progress','Sent to Suppliers'),('cancel','Cancelled'),('done','Purchase Done')], - 'Status', track_visibility='onchange', required=True) + 'purchase_ids': fields.one2many('purchase.order', 'requisition_id', 'Purchase Orders', states={'done': [('readonly', True)]}), + 'po_line_ids': fields.function(_get_po_line, method=True, type='one2many', relation='purchase.order.line', string='Products by supplier'), + 'line_ids': fields.one2many('purchase.requisition.line', 'requisition_id', 'Products to Purchase', states={'done': [('readonly', True)]}), + 'procurement_id': fields.many2one('procurement.order', 'Procurement', ondelete='set null'), + 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'), + 'state': fields.selection([('draft', 'Draft'), ('in_progress', 'Confirmed'), ('open', 'Bid Selection'), ('done', 'PO Created'), ('cancel', 'Cancelled')], + 'Status', track_visibility='onchange', required=True), + 'multiple_rfq_per_supplier': fields.boolean('Multiple RFQ per supplier'), + 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'), + 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', required=True), } + + def _get_picking_in(self, cr, uid, context=None): + obj_data = self.pool.get('ir.model.data') + return obj_data.get_object_reference(cr, uid, 'stock','picking_type_in')[1] + _defaults = { - 'date_start': lambda *args: time.strftime('%Y-%m-%d %H:%M:%S'), 'state': 'draft', 'exclusive': 'multiple', 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'purchase.requisition', context=c), - 'user_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).id , + 'user_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).id, 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'purchase.order.requisition'), + 'picking_type_id': _get_picking_in, } def copy(self, cr, uid, id, default=None, context=None): - if not default: - default = {} + default = default or {} default.update({ - 'state':'draft', - 'purchase_ids':[], + 'state': 'draft', + 'purchase_ids': [], 'name': self.pool.get('ir.sequence').get(cr, uid, 'purchase.order.requisition'), }) return super(purchase_requisition, self).copy(cr, uid, id, default, context) - + def tender_cancel(self, cr, uid, ids, context=None): purchase_order_obj = self.pool.get('purchase.order') - for purchase in self.browse(cr, uid, ids, context=context): - for purchase_id in purchase.purchase_ids: - if str(purchase_id.state) in('draft'): - purchase_order_obj.action_cancel(cr,uid,[purchase_id.id]) + #try to set all associated quotations to cancel state + purchase_ids = [] + for tender in self.browse(cr, uid, ids, context=context): + for purchase_order in tender.purchase_ids: + purchase_order_obj.action_cancel(cr, uid, [purchase_order.id], context=context) + purchase_order_obj.message_post(cr, uid, [purchase_order.id], body=_('Cancelled by the tender associated to this quotation.'), context=context) return self.write(cr, uid, ids, {'state': 'cancel'}) def tender_in_progress(self, cr, uid, ids, context=None): - return self.write(cr, uid, ids, {'state':'in_progress'} ,context=context) + return self.write(cr, uid, ids, {'state': 'in_progress'}, context=context) + + def tender_open(self, cr, uid, ids, context=None): + return self.write(cr, uid, ids, {'state': 'open'}, context=context) def tender_reset(self, cr, uid, ids, context=None): - return self.write(cr, uid, ids, {'state': 'draft'}) + self.write(cr, uid, ids, {'state': 'draft'}) + for p_id in ids: + # Deleting the existing instance of workflow for PO + self.delete_workflow(cr, uid, [p_id]) + self.create_workflow(cr, uid, [p_id]) + return True def tender_done(self, cr, uid, ids, context=None): - return self.write(cr, uid, ids, {'state':'done', 'date_end':time.strftime('%Y-%m-%d %H:%M:%S')}, context=context) + return self.write(cr, uid, ids, {'state': 'done'}, context=context) - def _planned_date(self, requisition, delay=0.0): - company = requisition.company_id - date_planned = False - if requisition.date_start: - date_planned = datetime.strptime(requisition.date_start, '%Y-%m-%d %H:%M:%S') - relativedelta(days=company.po_lead) - else: - date_planned = datetime.today() - relativedelta(days=company.po_lead) - if delay: - date_planned -= relativedelta(days=delay) - return date_planned and date_planned.strftime('%Y-%m-%d %H:%M:%S') or False + def open_product_line(self, cr, uid, ids, context=None): + """ This opens product line view to view all lines from the different quotations, groupby default by product and partner to show comparaison + between supplier price + @return: the product line tree view + """ + if context is None: + context = {} + res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'purchase_requisition', 'purchase_line_tree', context=context) + res['context'] = context + po_lines = self.browse(cr, uid, ids, context=context)[0].po_line_ids + res['context'] = { + 'search_default_groupby_product': True, + 'search_default_hide_cancelled': True, + } + res['domain'] = [('id', 'in', [line.id for line in po_lines])] + return res - def _seller_details(self, cr, uid, requisition_line, supplier, context=None): + def open_rfq(self, cr, uid, ids, context=None): + """ This opens rfq view to view all quotations associated to the call for bids + @return: the RFQ tree view + """ + if context is None: + context = {} + res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'purchase', 'purchase_rfq', context=context) + res['context'] = context + po_ids = [po.id for po in self.browse(cr, uid, ids, context=context)[0].purchase_ids] + res['domain'] = [('id', 'in', po_ids)] + return res + + def _prepare_purchase_order(self, cr, uid, requisition, supplier, context=None): + supplier_pricelist = supplier.property_product_pricelist_purchase and supplier.property_product_pricelist_purchase.id or False + picking_type_in = self.pool.get("purchase.order")._get_picking_in(cr, uid, context=context) + return { + 'origin': requisition.name, + 'date_order': requisition.date_end or fields.date.context_today(self, cr, uid, context=context), + 'partner_id': supplier.id, + 'pricelist_id': supplier_pricelist, + 'location_id': requisition.picking_type_id.default_location_dest_id.id, + 'company_id': requisition.company_id.id, + 'fiscal_position': supplier.property_account_position and supplier.property_account_position.id or False, + 'requisition_id': requisition.id, + 'notes': requisition.description, + 'picking_type_id': picking_type_in, + } + + def _prepare_purchase_order_line(self, cr, uid, requisition, requisition_line, purchase_id, supplier, context=None): + po_line_obj = self.pool.get('purchase.order.line') product_uom = self.pool.get('product.uom') - pricelist = self.pool.get('product.pricelist') product = requisition_line.product_id default_uom_po_id = product.uom_po_id.id + date_order = requisition.ordering_date or fields.date.context_today(self, cr, uid, context=context) qty = product_uom._compute_qty(cr, uid, requisition_line.product_uom_id.id, requisition_line.product_qty, default_uom_po_id) - seller_delay = 0.0 - seller_price = False - seller_qty = False - for product_supplier in product.seller_ids: - if supplier.id == product_supplier.name and qty >= product_supplier.qty: - seller_delay = product_supplier.delay - seller_qty = product_supplier.qty - supplier_pricelist = supplier.property_product_pricelist_purchase or False - seller_price = pricelist.price_get(cr, uid, [supplier_pricelist.id], product.id, qty, supplier.id, {'uom': default_uom_po_id})[supplier_pricelist.id] - if seller_qty: - qty = max(qty,seller_qty) - date_planned = self._planned_date(requisition_line.requisition_id, seller_delay) - return seller_price, qty, default_uom_po_id, date_planned + supplier_pricelist = supplier.property_product_pricelist_purchase and supplier.property_product_pricelist_purchase.id or False + vals = po_line_obj.onchange_product_id(cr, uid, [], supplier_pricelist, product.id, qty, default_uom_po_id, + supplier.id, date_order=date_order, fiscal_position_id=supplier.property_account_position, date_planned=requisition_line.schedule_date, + name=False, price_unit=False, state='draft', context=context)['value'] + vals.update({ + 'order_id': purchase_id, + 'product_id': product.id, + 'account_analytic_id': requisition_line.account_analytic_id.id, + }) + return vals def make_purchase_order(self, cr, uid, ids, partner_id, context=None): """ @@ -123,62 +183,137 @@ class purchase_requisition(osv.osv): purchase_order = self.pool.get('purchase.order') purchase_order_line = self.pool.get('purchase.order.line') res_partner = self.pool.get('res.partner') - fiscal_position = self.pool.get('account.fiscal.position') supplier = res_partner.browse(cr, uid, partner_id, context=context) - supplier_pricelist = supplier.property_product_pricelist_purchase or False res = {} for requisition in self.browse(cr, uid, ids, context=context): - if supplier.id in filter(lambda x: x, [rfq.state <> 'cancel' and rfq.partner_id.id or None for rfq in requisition.purchase_ids]): - raise osv.except_osv(_('Warning!'), _('You have already one %s purchase order for this partner, you must cancel this purchase order to create a new quotation.') % rfq.state) - location_id = requisition.warehouse_id.lot_input_id.id + if not requisition.multiple_rfq_per_supplier and supplier.id in filter(lambda x: x, [rfq.state != 'cancel' and rfq.partner_id.id or None for rfq in requisition.purchase_ids]): + raise osv.except_osv(_('Warning!'), _('You have already one %s purchase order for this partner, you must cancel this purchase order to create a new quotation.') % rfq.state) context.update({'mail_create_nolog': True}) - purchase_id = purchase_order.create(cr, uid, { - 'origin': requisition.name, - 'partner_id': supplier.id, - 'pricelist_id': supplier_pricelist.id, - 'location_id': location_id, - 'company_id': requisition.company_id.id, - 'fiscal_position': supplier.property_account_position and supplier.property_account_position.id or False, - 'requisition_id':requisition.id, - 'notes':requisition.description, - 'warehouse_id':requisition.warehouse_id.id , - }) + purchase_id = purchase_order.create(cr, uid, self._prepare_purchase_order(cr, uid, requisition, supplier, context=context), context=context) purchase_order.message_post(cr, uid, [purchase_id], body=_("RFQ created"), context=context) res[requisition.id] = purchase_id for line in requisition.line_ids: - product = line.product_id - seller_price, qty, default_uom_po_id, date_planned = self._seller_details(cr, uid, line, supplier, context=context) - taxes_ids = product.supplier_taxes_id - taxes = fiscal_position.map_tax(cr, uid, supplier.property_account_position, taxes_ids) - purchase_order_line.create(cr, uid, { - 'order_id': purchase_id, - 'name': product.partner_ref, - 'product_qty': qty, - 'product_id': product.id, - 'product_uom': default_uom_po_id, - 'price_unit': seller_price, - 'date_planned': date_planned, - 'taxes_id': [(6, 0, taxes)], - }, context=context) - + purchase_order_line.create(cr, uid, self._prepare_purchase_order_line(cr, uid, requisition, line, purchase_id, supplier, context=context), context=context) return res + def check_valid_quotation(self, cr, uid, quotation, context=None): + """ + Check if a quotation has all his order lines bid in order to confirm it if its the case + return True if all order line have been selected during bidding process, else return False + + args : 'quotation' must be a browse record + """ + for line in quotation.order_line: + if line.state != 'confirmed' or line.product_qty != line.quantity_bid: + return False + return True + + def _prepare_po_from_tender(self, cr, uid, tender, context=None): + """ Prepare the values to write in the purchase order + created from a tender. + + :param tender: the source tender from which we generate a purchase order + """ + return {'order_line': [], + 'requisition_id': tender.id, + 'origin': tender.name} + + def _prepare_po_line_from_tender(self, cr, uid, tender, line, purchase_id, context=None): + """ Prepare the values to write in the purchase order line + created from a line of the tender. + + :param tender: the source tender from which we generate a purchase order + :param line: the source tender's line from which we generate a line + :param purchase_id: the id of the new purchase + """ + return {'product_qty': line.quantity_bid, + 'order_id': purchase_id} + + def generate_po(self, cr, uid, ids, context=None): + """ + Generate all purchase order based on selected lines, should only be called on one tender at a time + """ + if context is None: + contex = {} + po = self.pool.get('purchase.order') + poline = self.pool.get('purchase.order.line') + id_per_supplier = {} + for tender in self.browse(cr, uid, ids, context=context): + if tender.state == 'done': + raise osv.except_osv(_('Warning!'), _('You have already generate the purchase order(s).')) + + confirm = False + #check that we have at least confirm one line + for po_line in tender.po_line_ids: + if po_line.state == 'confirmed': + confirm = True + break + if not confirm: + raise osv.except_osv(_('Warning!'), _('You have no line selected for buying.')) + + #check for complete RFQ + for quotation in tender.purchase_ids: + if (self.check_valid_quotation(cr, uid, quotation, context=context)): + #use workflow to set PO state to confirm + po.signal_purchase_confirm(cr, uid, [quotation.id]) + + #get other confirmed lines per supplier + for po_line in tender.po_line_ids: + #only take into account confirmed line that does not belong to already confirmed purchase order + if po_line.state == 'confirmed' and po_line.order_id.state in ['draft', 'sent', 'bid']: + if id_per_supplier.get(po_line.partner_id.id): + id_per_supplier[po_line.partner_id.id].append(po_line) + else: + id_per_supplier[po_line.partner_id.id] = [po_line] + + #generate po based on supplier and cancel all previous RFQ + ctx = context.copy() + ctx['force_requisition_id'] = True + for supplier, product_line in id_per_supplier.items(): + #copy a quotation for this supplier and change order_line then validate it + quotation_id = po.search(cr, uid, [('requisition_id', '=', tender.id), ('partner_id', '=', supplier)], limit=1)[0] + vals = self._prepare_po_from_tender(cr, uid, tender, context=context) + new_po = po.copy(cr, uid, quotation_id, default=vals, context=ctx) + #duplicate po_line and change product_qty if needed and associate them to newly created PO + for line in product_line: + vals = self._prepare_po_line_from_tender(cr, uid, tender, line, new_po, context=context) + poline.copy(cr, uid, line.id, default=vals, context=context) + #use workflow to set new PO state to confirm + po.signal_purchase_confirm(cr, uid, [new_po]) + + #cancel other orders + self.cancel_unconfirmed_quotations(cr, uid, tender, context=context) + + #set tender to state done + self.signal_done(cr, uid, [tender.id]) + return True + + def cancel_unconfirmed_quotations(self, cr, uid, tender, context=None): + #cancel other orders + po = self.pool.get('purchase.order') + for quotation in tender.purchase_ids: + if quotation.state in ['draft', 'sent', 'bid']: + self.pool.get('purchase.order').signal_purchase_cancel(cr, uid, [quotation.id]) + po.message_post(cr, uid, [quotation.id], body=_('Cancelled by the call for bids associated to this request for quotation.'), context=context) + return True + class purchase_requisition_line(osv.osv): - _name = "purchase.requisition.line" - _description="Purchase Requisition Line" + _description = "Purchase Requisition Line" _rec_name = 'product_id' _columns = { - 'product_id': fields.many2one('product.product', 'Product' ), + 'product_id': fields.many2one('product.product', 'Product'), 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'), 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure')), - 'requisition_id' : fields.many2one('purchase.requisition','Purchase Requisition', ondelete='cascade'), - 'company_id': fields.related('requisition_id','company_id',type='many2one',relation='res.company',string='Company', store=True, readonly=True), + 'requisition_id': fields.many2one('purchase.requisition', 'Call for Bids', ondelete='cascade'), + 'company_id': fields.related('requisition_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True), + 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account',), + 'schedule_date': fields.date('Scheduled Date'), } - def onchange_product_id(self, cr, uid, ids, product_id, product_uom_id, context=None): + def onchange_product_id(self, cr, uid, ids, product_id, product_uom_id, parent_analytic_account, analytic_account, parent_date, date, context=None): """ Changes UoM and name if product_id changes. @param name: Name of the field @param product_id: Changed product_id @@ -187,7 +322,11 @@ class purchase_requisition_line(osv.osv): value = {'product_uom_id': ''} if product_id: prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context) - value = {'product_uom_id': prod.uom_id.id,'product_qty':1.0} + value = {'product_uom_id': prod.uom_id.id, 'product_qty': 1.0} + if not analytic_account: + value.update({'account_analytic_id': parent_analytic_account}) + if not date: + value.update({'schedule_date': parent_date}) return {'value': value} _defaults = { @@ -196,33 +335,68 @@ class purchase_requisition_line(osv.osv): class purchase_order(osv.osv): _inherit = "purchase.order" + _columns = { - 'requisition_id' : fields.many2one('purchase.requisition','Purchase Requisition') + 'requisition_id': fields.many2one('purchase.requisition', 'Call for Bids'), } def wkf_confirm_order(self, cr, uid, ids, context=None): res = super(purchase_order, self).wkf_confirm_order(cr, uid, ids, context=context) proc_obj = self.pool.get('procurement.order') for po in self.browse(cr, uid, ids, context=context): - if po.requisition_id and (po.requisition_id.exclusive=='exclusive'): + if po.requisition_id and (po.requisition_id.exclusive == 'exclusive'): for order in po.requisition_id.purchase_ids: if order.id != po.id: proc_ids = proc_obj.search(cr, uid, [('purchase_id', '=', order.id)]) - if proc_ids and po.state=='confirmed': + if proc_ids and po.state == 'confirmed': proc_obj.write(cr, uid, proc_ids, {'purchase_id': po.id}) self.signal_purchase_cancel(cr, uid, [order.id]) po.requisition_id.tender_done(context=context) return res + def copy(self, cr, uid, id, default=None, context=None): + if context is None: + context = {} + if not context.get('force_requisition_id'): + default = default or {} + default.update({'requisition_id': False}) + return super(purchase_order, self).copy(cr, uid, id, default=default, context=context) + + def _prepare_order_line_move(self, cr, uid, order, order_line, picking_id, group_id, context=None): + stock_move_lines = super(purchase_order, self)._prepare_order_line_move(cr, uid, order, order_line, picking_id, group_id, context=context) + if order.requisition_id and order.requisition_id.procurement_id and order.requisition_id.procurement_id.move_dest_id: + for i in range(0, len(stock_move_lines)): + stock_move_lines[i]['move_dest_id'] = order.requisition_id.procurement_id.move_dest_id.id + return stock_move_lines + + +class purchase_order_line(osv.osv): + _inherit = 'purchase.order.line' + + _columns = { + 'quantity_bid': fields.float('Quantity Bid', digits_compute=dp.get_precision('Product Unit of Measure'), help="Technical field for not loosing the initial information about the quantity proposed in the bid"), + } + + def action_draft(self, cr, uid, ids, context=None): + self.write(cr, uid, ids, {'state': 'draft'}, context=context) + + def action_confirm(self, cr, uid, ids, context=None): + super(purchase_order_line, self).action_confirm(cr, uid, ids, context=context) + for element in self.browse(cr, uid, ids, context=context): + if not element.quantity_bid: + self.write(cr, uid, ids, {'quantity_bid': element.product_qty}, context=context) + return True + + def generate_po(self, cr, uid, tender_id, context=None): + #call generate_po from tender with active_id. Called from js widget + return self.pool.get('purchase.requisition').generate_po(cr, uid, [tender_id], context=context) + class product_product(osv.osv): _inherit = 'product.product' _columns = { - 'purchase_requisition': fields.boolean('Purchase Requisition', help="Check this box to generates purchase requisition instead of generating requests for quotation from procurement.") - } - _defaults = { - 'purchase_requisition': False + 'purchase_requisition': fields.boolean('Call for Bids', help="Check this box to generate Call for Bids instead of generating requests for quotation from procurement.") } @@ -232,65 +406,35 @@ class procurement_order(osv.osv): 'requisition_id': fields.many2one('purchase.requisition', 'Latest Requisition') } - def _get_warehouse(self, procurement, user_company): - """ - Return the warehouse containing the procurment stock location (or one of it ancestors) - If none match, returns then first warehouse of the company - """ - # NOTE This method is a copy of the one on the procurement.order defined in purchase - # module. It's been copied to ensure it been always available, even if module - # purchase is not up to date. - # Do not forget to update both version in case of modification. - company_id = (procurement.company_id or user_company).id - domains = [ - [ - '&', ('company_id', '=', company_id), - '|', '&', ('lot_stock_id.parent_left', '<', procurement.location_id.parent_left), - ('lot_stock_id.parent_right', '>', procurement.location_id.parent_right), - ('lot_stock_id', '=', procurement.location_id.id) - ], - [('company_id', '=', company_id)] - ] - - cr, uid = procurement._cr, procurement._uid - context = procurement._context - Warehouse = self.pool['stock.warehouse'] - for domain in domains: - ids = Warehouse.search(cr, uid, domain, context=context) - if ids: - return ids[0] - return False - - def make_po(self, cr, uid, ids, context=None): - res = {} + def _run(self, cr, uid, procurement, context=None): requisition_obj = self.pool.get('purchase.requisition') - non_requisition = [] - for procurement in self.browse(cr, uid, ids, context=context): - if procurement.product_id.purchase_requisition: - user_company = self.pool['res.users'].browse(cr, uid, uid, context=context).company_id - req = res[procurement.id] = requisition_obj.create(cr, uid, { - 'origin': procurement.origin, - 'date_end': procurement.date_planned, - 'warehouse_id': self._get_warehouse(procurement, user_company), - 'company_id': procurement.company_id.id, - 'line_ids': [(0, 0, { - 'product_id': procurement.product_id.id, - 'product_uom_id': procurement.product_uom.id, - 'product_qty': procurement.product_qty + warehouse_obj = self.pool.get('stock.warehouse') + if procurement.rule_id and procurement.rule_id.action == 'buy' and procurement.product_id.purchase_requisition: + warehouse_id = warehouse_obj.search(cr, uid, [('company_id', '=', procurement.company_id.id)], context=context) + requisition_id = requisition_obj.create(cr, uid, { + 'origin': procurement.origin, + 'date_end': procurement.date_planned, + 'warehouse_id': warehouse_id and warehouse_id[0] or False, + 'company_id': procurement.company_id.id, + 'procurement_id': procurement.id, + 'line_ids': [(0, 0, { + 'product_id': procurement.product_id.id, + 'product_uom_id': procurement.product_uom.id, + 'product_qty': procurement.product_qty - })], - }) - procurement.write({ - 'state': 'running', - 'requisition_id': req - }) - else: - non_requisition.append(procurement.id) - - if non_requisition: - res.update(super(procurement_order, self).make_po(cr, uid, non_requisition, context=context)) - - return res + })], + }) + self.message_post(cr, uid, [procurement.id], body=_("Purchase Requisition created"), context=context) + return self.write(cr, uid, [procurement.id], {'requisition_id': requisition_id}, context=context) + return super(procurement_order, self)._run(cr, uid, procurement, context=context) + def _check(self, cr, uid, procurement, context=None): + requisition_obj = self.pool.get('purchase.requisition') + if procurement.rule_id and procurement.rule_id.action == 'buy' and procurement.product_id.purchase_requisition: + if procurement.requisition_id.state == 'done': + if any([purchase.shipped for purchase in procurement.requisition_id.purchase_ids]): + return True + return False + return super(procurement_order, self)._check(cr, uid, procurement, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/purchase_requisition/purchase_requisition_demo.xml b/addons/purchase_requisition/purchase_requisition_demo.xml index 21d348c2f0e..22c090fe44a 100644 --- a/addons/purchase_requisition/purchase_requisition_demo.xml +++ b/addons/purchase_requisition/purchase_requisition_demo.xml @@ -15,7 +15,6 @@ exclusive - diff --git a/addons/purchase_requisition/purchase_requisition_report.xml b/addons/purchase_requisition/purchase_requisition_report.xml index 64cbc1e7ea1..7089415ec07 100644 --- a/addons/purchase_requisition/purchase_requisition_report.xml +++ b/addons/purchase_requisition/purchase_requisition_report.xml @@ -2,7 +2,7 @@ purchase.order - + @@ -28,19 +28,26 @@ purchase.requisition.form purchase.requisition -
-
-
+
+
@@ -52,29 +59,38 @@
- - + + + + - - - - + + + + + + - + - + + + + + + @@ -82,26 +98,28 @@
- - + + - + ") + .click(this.proxy('generate_purchase_order')); + self.__parentedParent.$el.find('.oe_list_buttons').append(button); + } + }); + }, + generate_purchase_order: function () { + var self = this; + new instance.web.Model(self.dataset.model).call("generate_po",[self.dataset.context.active_id,self.dataset.context]).then(function(result) { + self.ViewManager.ActionManager.history_back(); + }); + }, + }); +} diff --git a/addons/purchase_requisition/test/purchase_requisition.yml b/addons/purchase_requisition/test/purchase_requisition.yml index 579febe64ea..5ac152d3d29 100644 --- a/addons/purchase_requisition/test/purchase_requisition.yml +++ b/addons/purchase_requisition/test/purchase_requisition.yml @@ -8,7 +8,7 @@ product_id: product.product_product_13 qty: 15 uom_id: product.product_uom_unit - warehouse_id: stock.stock_warehouse_shop0 + warehouse_id: stock.warehouse0 - !python {model: make.procurement}: | self.make_procurement(cr, uid, [ref('procurement_product_hdd3')], context) @@ -30,16 +30,26 @@ assert line.product_id.id == procurement.product_id.id, "Product is not correspond." assert line.product_uom_id.id == procurement.product_uom.id, "UOM is not correspond." assert line.product_qty == procurement.product_qty, "Quantity is not correspond." +- + I send the purchase order associated to the requisition. +- + !python {model: purchase.requisition}: | + po = self.pool.get('purchase.order') + for element in self.browse(cr, uid, [ref("requisition1")], context=context): + for purchase in element.purchase_ids: + po.write(cr, uid, purchase.id, {'state': 'sent'}, context=context) + - Give access rights of Purchase Requisition User to open requisition - !context uid: 'res_users_purchase_requisition_user' - - I open another requisition. + I open another requisition and set tender state to choose bidding line. - !python {model: purchase.requisition}: | self.tender_in_progress(cr, uid, [ref("requisition1")], context=context) + self.tender_open(cr, uid, [ref("requisition1")], context=context) - Supplier send one RFQ so I create requisition request of that supplier. - @@ -64,13 +74,6 @@ supplier = rfq.partner_id assert supplier.id == ref('base.res_partner_12'), "RFQ Partner is not correspond." assert len(rfq.order_line) == len(requisition.line_ids), "Lines are not correspond." - for rfq_line in rfq.order_line: - for line in requisition.line_ids: - if rfq_line.product_id.id == line.product_id.id: - seller_price, qty, default_uom_po_id, date_planned = purchase_requisition._seller_details(cr, uid, line, supplier, context=context) - assert rfq_line.product_qty == qty, "Quantity is not correspond." - assert rfq_line.product_uom.id == default_uom_po_id, "UOM is not correspond." - assert rfq_line.price_unit == seller_price, "Unit Price is not correspond." - I confirmed RFQ which has best price. - diff --git a/addons/purchase_requisition/views/purchase_requisition.xml b/addons/purchase_requisition/views/purchase_requisition.xml new file mode 100644 index 00000000000..3d9ecc7d78f --- /dev/null +++ b/addons/purchase_requisition/views/purchase_requisition.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/addons/purchase_requisition/views/report_purchaserequisition.xml b/addons/purchase_requisition/views/report_purchaserequisition.xml index 249558fbdb6..209a92bc3a3 100644 --- a/addons/purchase_requisition/views/report_purchaserequisition.xml +++ b/addons/purchase_requisition/views/report_purchaserequisition.xml @@ -8,19 +8,19 @@
-

Purchase for Requisitions

+

Call for Bids

- Requisition Reference:
+ Call for Bif Reference:
- Requisition Date:
- + Scheduled Ordering Date:
+
- Type:
+ Selection Type:
Purchase Requisitions (exclusive) Multiple Requisitions
@@ -31,7 +31,7 @@
-

Product Detail

+

Products

@@ -40,6 +40,7 @@ + @@ -56,19 +57,22 @@ +
Product UoM Scheduled Date
+ +
-

Quotation Detail

+

Requests for Quotation Details

- - + + diff --git a/addons/purchase_requisition/wizard/__init__.py b/addons/purchase_requisition/wizard/__init__.py index a9691cb6e25..e19f2efb14f 100644 --- a/addons/purchase_requisition/wizard/__init__.py +++ b/addons/purchase_requisition/wizard/__init__.py @@ -20,6 +20,7 @@ ############################################################################## import purchase_requisition_partner +import bid_line_qty # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/procurement/company.py b/addons/purchase_requisition/wizard/bid_line_qty.py similarity index 62% rename from addons/procurement/company.py rename to addons/purchase_requisition/wizard/bid_line_qty.py index 1fd08d967f1..7bae7755414 100644 --- a/addons/procurement/company.py +++ b/addons/purchase_requisition/wizard/bid_line_qty.py @@ -19,19 +19,20 @@ # ############################################################################## -from openerp.osv import osv,fields +from openerp.osv import fields, osv +import openerp.addons.decimal_precision as dp -class company(osv.osv): - _inherit = 'res.company' +class bid_line_qty(osv.osv_memory): + _name = "bid.line.qty" + _description = "Change Bid line quantity" _columns = { - 'schedule_range': fields.float('Scheduler Range Days', required=True, - help="This is the time frame analysed by the scheduler when "\ - "computing procurements. All procurements that are not between "\ - "today and today+range are skipped for future computation."), - } - _defaults = { - 'schedule_range': 730.0, + 'qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True), } + def change_qty(self, cr, uid, ids, context=None): + active_ids = context and context.get('active_ids', []) + data = self.browse(cr, uid, ids, context=context)[0] + self.pool.get('purchase.order.line').write(cr, uid, active_ids, {'quantity_bid': data.qty}) + return {'type': 'ir.actions.act_window_close'} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/purchase_requisition/wizard/bid_line_qty_view.xml b/addons/purchase_requisition/wizard/bid_line_qty_view.xml new file mode 100644 index 00000000000..0bc8ad2ac5f --- /dev/null +++ b/addons/purchase_requisition/wizard/bid_line_qty_view.xml @@ -0,0 +1,31 @@ + + + + + Quantity to Purchase + bid.line.qty + +
+ + + +
+
+ +
+
+ + + Bid Line Qty + ir.actions.act_window + bid.line.qty + form + form + {'record_id' : active_id} + new + +
+
diff --git a/addons/purchase_requisition/wizard/purchase_requisition_partner.py b/addons/purchase_requisition/wizard/purchase_requisition_partner.py index 96285d42e43..cef4b6be142 100644 --- a/addons/purchase_requisition/wizard/purchase_requisition_partner.py +++ b/addons/purchase_requisition/wizard/purchase_requisition_partner.py @@ -46,5 +46,4 @@ class purchase_requisition_partner(osv.osv_memory): return {'type': 'ir.actions.act_window_close'} - # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/purchase_requisition/wizard/purchase_requisition_partner_view.xml b/addons/purchase_requisition/wizard/purchase_requisition_partner_view.xml index f5f0367ad4b..3db4ca3ae83 100644 --- a/addons/purchase_requisition/wizard/purchase_requisition_partner_view.xml +++ b/addons/purchase_requisition/wizard/purchase_requisition_partner_view.xml @@ -2,15 +2,15 @@ - Purchase Requisition + Choose Supplier purchase.requisition.partner -
+
-
@@ -19,7 +19,7 @@
- Purchase Requisition + Choose Supplier ir.actions.act_window purchase.requisition.partner form @@ -27,5 +27,6 @@ {'record_id' : active_id} new +
diff --git a/addons/report/models/report.py b/addons/report/models/report.py index 8b09fa35419..d8a51387cb7 100644 --- a/addons/report/models/report.py +++ b/addons/report/models/report.py @@ -285,6 +285,7 @@ class Report(osv.Model): 'report_name': report.report_name, 'report_type': report.report_type, 'report_file': report.report_file, + 'context': context, } #-------------------------------------------------------------------------- diff --git a/addons/report_webkit/header_view.xml b/addons/report_webkit/header_view.xml index da47e6f1642..0fa9480f080 100644 --- a/addons/report_webkit/header_view.xml +++ b/addons/report_webkit/header_view.xml @@ -5,12 +5,12 @@ ir.header_img + - + - diff --git a/addons/resource/resource.py b/addons/resource/resource.py index 962cad9eb92..58acc0cd170 100644 --- a/addons/resource/resource.py +++ b/addons/resource/resource.py @@ -436,7 +436,7 @@ class resource_calendar(osv.osv): working_intervals = self.get_working_intervals_of_day(cr, uid, id, **call_args) - if id is None and not working_interval: # no calendar -> consider working 8 hours + if id is None and not working_intervals: # no calendar -> consider working 8 hours remaining_hours -= 8.0 elif working_intervals: if backwards: diff --git a/addons/sale/__openerp__.py b/addons/sale/__openerp__.py index 2faeb5b3693..96a3dde5075 100644 --- a/addons/sale/__openerp__.py +++ b/addons/sale/__openerp__.py @@ -58,8 +58,8 @@ The Dashboard for the Sales Manager will include """, 'author': 'OpenERP SA', 'website': 'http://www.openerp.com', - 'images': ['images/sale_dashboard.jpeg','images/Sale_order_line_to_invoice.jpeg','images/sale_order.jpeg','images/sales_analysis.jpeg'], - 'depends': ['sale_team','account_voucher','report'], + 'images': ['images/Sale_order_line_to_invoice.jpeg','images/sale_order.jpeg','images/sales_analysis.jpeg'], + 'depends': ['sale_team','account_voucher', 'procurement', 'report'], 'data': [ 'wizard/sale_make_invoice_advance.xml', 'wizard/sale_line_invoice.xml', diff --git a/addons/sale/sale.py b/addons/sale/sale.py index c8ab29ffe34..34886a22991 100644 --- a/addons/sale/sale.py +++ b/addons/sale/sale.py @@ -27,7 +27,7 @@ from dateutil import relativedelta import time from openerp.osv import fields, osv from openerp.tools.translate import _ -from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare +from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT import openerp.addons.decimal_precision as dp from openerp import workflow @@ -46,12 +46,13 @@ class sale_order(osv.osv): if not default: default = {} default.update({ - 'date_order': fields.date.context_today(self, cr, uid, context=context), + 'date_order': fields.datetime.now(), 'state': 'draft', 'invoice_ids': [], 'date_confirm': False, 'client_order_ref': '', 'name': self.pool.get('ir.sequence').get(cr, uid, 'sale.order'), + 'procurement_group_id': False, }) return super(sale_order, self).copy(cr, uid, id, default, context=context) @@ -183,11 +184,14 @@ class sale_order(osv.osv): ('waiting_date', 'Waiting Schedule'), ('progress', 'Sales Order'), ('manual', 'Sale to Invoice'), + ('shipping_except', 'Shipping Exception'), ('invoice_except', 'Invoice Exception'), ('done', 'Done'), - ], 'Status', readonly=True, track_visibility='onchange', - help="Gives the status of the quotation or sales order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the sales order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True), - 'date_order': fields.date('Date', required=True, readonly=True, select=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}), + ], 'Status', readonly=True, help="Gives the status of the quotation or sales order.\ + \nThe exception status is automatically set when a cancel operation occurs \ + in the invoice validation (Invoice Exception) or in the picking list process (Shipping Exception).\nThe 'Waiting Schedule' status is set when the invoice is confirmed\ + but waiting for the scheduler to run on the order date.", select=True), + 'date_order': fields.datetime('Date', required=True, readonly=True, select=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}), 'create_date': fields.datetime('Creation Date', readonly=True, select=True, help="Date on which sales order is created."), 'date_confirm': fields.date('Confirmation Date', readonly=True, select=True, help="Date on which sales order is confirmed."), 'user_id': fields.many2one('res.users', 'Salesperson', states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, select=True, track_visibility='onchange'), @@ -230,20 +234,20 @@ class sale_order(osv.osv): }, multi='sums', help="The total amount."), - 'invoice_quantity': fields.selection([('order', 'Ordered Quantities')], 'Invoice on', help="The sales order will automatically create the invoice proposition (draft invoice).", required=True, readonly=True, states={'draft': [('readonly', False)]}), 'payment_term': fields.many2one('account.payment.term', 'Payment Term'), 'fiscal_position': fields.many2one('account.fiscal.position', 'Fiscal Position'), 'company_id': fields.many2one('res.company', 'Company'), 'section_id': fields.many2one('crm.case.section', 'Sales Team'), + 'procurement_group_id': fields.many2one('procurement.group', 'Procurement group'), + } _defaults = { - 'date_order': fields.date.context_today, + 'date_order': fields.datetime.now, 'order_policy': 'manual', 'company_id': _get_default_company, 'state': 'draft', 'user_id': lambda obj, cr, uid, context: uid, 'name': lambda obj, cr, uid, context: '/', - 'invoice_quantity': 'order', 'partner_invoice_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['invoice'])['invoice'], 'partner_shipping_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['delivery'])['delivery'], 'note': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.sale_note, @@ -304,7 +308,7 @@ class sale_order(osv.osv): partner_lang = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context).lang context_lang.update({'lang': partner_lang}) return self.pool.get('res.users').browse(cr, uid, uid, context=context_lang).company_id.sale_note - + def onchange_partner_id(self, cr, uid, ids, part, context=None): if not part: return {'value': {'partner_invoice_id': False, 'partner_shipping_id': False, 'payment_term': False, 'fiscal_position': False}} @@ -330,7 +334,7 @@ class sale_order(osv.osv): def create(self, cr, uid, vals, context=None): if context is None: - context = {} + context = {} if vals.get('name', '/') == '/': vals['name'] = self.pool.get('ir.sequence').get(cr, uid, 'sale.order') or '/' if vals.get('partner_id') and any(f not in vals for f in ['partner_invoice_id', 'partner_shipping_id', 'pricelist_id']): @@ -636,8 +640,138 @@ class sale_order(osv.osv): } def action_done(self, cr, uid, ids, context=None): + for order in self.browse(cr, uid, ids, context=context): + self.pool.get('sale.order.line').write(cr, uid, [line.id for line in order.order_line], {'state': 'done'}, context=context) return self.write(cr, uid, ids, {'state': 'done'}, context=context) + def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None): + date_planned = self._get_date_planned(cr, uid, order, line, order.date_order, context=context) + return { + 'name': line.name, + 'origin': order.name, + 'date_planned': date_planned, + 'product_id': line.product_id.id, + 'product_qty': line.product_uom_qty, + 'product_uom': line.product_uom.id, + 'product_uos_qty': (line.product_uos and line.product_uos_qty) or line.product_uom_qty, + 'product_uos': (line.product_uos and line.product_uos.id) or line.product_uom.id, + 'company_id': order.company_id.id, + 'group_id': group_id, + 'invoice_state': (order.order_policy == 'picking') and '2binvoiced' or 'none', + 'sale_line_id': line.id + } + + def _get_date_planned(self, cr, uid, order, line, start_date, context=None): + date_planned = datetime.strptime(start_date, DEFAULT_SERVER_DATETIME_FORMAT) + timedelta(days=line.delay or 0.0) + return date_planned + + def _prepare_procurement_group(self, cr, uid, order, context=None): + return {'name': order.name, 'partner_id': order.partner_shipping_id.id} + + def procurement_needed(self, cr, uid, ids, context=None): + #when sale is installed only, there is no need to create procurements, that's only + #further installed modules (project_mrp, sale_stock) that will change this. + sale_line_obj = self.pool.get('sale.order.line') + res = [] + for order in self.browse(cr, uid, ids, context=context): + res.append(sale_line_obj.need_procurement(cr, uid, [line.id for line in order.order_line], context=context)) + return any(res) + + def action_ignore_delivery_exception(self, cr, uid, ids, context=None): + for sale_order in self.browse(cr, uid, ids, context=context): + self.write(cr, uid, ids, {'state': 'progress' if sale_order.invoice_exists else 'manual'}, context=context) + return True + + def action_ship_create(self, cr, uid, ids, context=None): + """Create the required procurements to supply sales order lines, also connecting + the procurements to appropriate stock moves in order to bring the goods to the + sales order's requested location. + + :return: True + """ + procurement_obj = self.pool.get('procurement.order') + sale_line_obj = self.pool.get('sale.order.line') + for order in self.browse(cr, uid, ids, context=context): + proc_ids = [] + vals = self._prepare_procurement_group(cr, uid, order, context=context) + if not order.procurement_group_id: + group_id = self.pool.get("procurement.group").create(cr, uid, vals, context=context) + order.write({'procurement_group_id': group_id}, context=context) + + for line in order.order_line: + #Try to fix exception procurement (possible when after a shipping exception the user choose to recreate) + if line.procurement_ids: + #first check them to see if they are in exception or not (one of the related moves is cancelled) + procurement_obj.check(cr, uid, [x.id for x in line.procurement_ids if x.state not in ['cancel', 'done']]) + line.refresh() + #run again procurement that are in exception in order to trigger another move + proc_ids += [x.id for x in line.procurement_ids if x.state == 'exception'] + elif sale_line_obj.need_procurement(cr, uid, [line.id], context=context): + if (line.state == 'done') or not line.product_id: + continue + vals = self._prepare_order_line_procurement(cr, uid, order, line, group_id=group_id, context=context) + proc_id = procurement_obj.create(cr, uid, vals, context=context) + proc_ids.append(proc_id) + #Confirm procurement order such that rules will be applied on it + #note that the workflow normally ensure proc_ids isn't an empty list + procurement_obj.run(cr, uid, proc_ids, context=context) + + #if shipping was in exception and the user choose to recreate the delivery order, write the new status of SO + if order.state == 'shipping_except': + val = {'state': 'progress', 'shipped': False} + + if (order.order_policy == 'manual'): + for line in order.order_line: + if (not line.invoiced) and (line.state not in ('cancel', 'draft')): + val['state'] = 'manual' + break + order.write(val) + return True + + # if mode == 'finished': + # returns True if all lines are done, False otherwise + # if mode == 'canceled': + # returns True if there is at least one canceled line, False otherwise + def test_state(self, cr, uid, ids, mode, *args): + assert mode in ('finished', 'canceled'), _("invalid mode for test_state") + finished = True + canceled = False + write_done_ids = [] + write_cancel_ids = [] + for order in self.browse(cr, uid, ids, context={}): + + #TODO: Need to rethink what happens when cancelling + for line in order.order_line: + states = [x.state for x in line.procurement_ids] + cancel = states and all([x == 'cancel' for x in states]) + doneorcancel = all([x in ('done', 'cancel') for x in states]) + if cancel: + canceled = True + if line.state != 'exception': + write_cancel_ids.append(line.id) + if not doneorcancel: + finished = False + if doneorcancel and not cancel: + write_done_ids.append(line.id) + + if write_done_ids: + self.pool.get('sale.order.line').write(cr, uid, write_done_ids, {'state': 'done'}) + if write_cancel_ids: + self.pool.get('sale.order.line').write(cr, uid, write_cancel_ids, {'state': 'exception'}) + + if mode == 'finished': + return finished + elif mode == 'canceled': + return canceled + + + def procurement_lines_get(self, cr, uid, ids, *args): + res = [] + for order in self.browse(cr, uid, ids, context={}): + for line in order.order_line: + res += [x.id for x in line.procurement_ids] + return res + def onchange_fiscal_position(self, cr, uid, ids, fiscal_position, order_lines, context=None): '''Update taxes of order lines for each line where a product is defined @@ -687,6 +821,11 @@ class sale_order(osv.osv): # - use it in report if there is a uos class sale_order_line(osv.osv): + def need_procurement(self, cr, uid, ids, context=None): + #when sale is installed only, there is no need to create procurements, that's only + #further installed modules (project_mrp, sale_stock) that will change this. + return False + def _amount_line(self, cr, uid, ids, field_name, arg, context=None): tax_obj = self.pool.get('account.tax') cur_obj = self.pool.get('res.currency') @@ -722,6 +861,7 @@ class sale_order_line(osv.osv): WHERE rel.invoice_id = ANY(%s)""", (list(ids),)) return [i[0] for i in cr.fetchall()] + _name = 'sale.order.line' _description = 'Sales Order Line' _columns = { @@ -733,10 +873,9 @@ class sale_order_line(osv.osv): 'invoiced': fields.function(_fnct_line_invoiced, string='Invoiced', type='boolean', store={ 'account.invoice': (_order_lines_from_invoice, ['state'], 10), - 'sale.order.line': (lambda self,cr,uid,ids,ctx=None: ids, ['invoice_lines'], 10)}), + 'sale.order.line': (lambda self,cr,uid,ids,ctx=None: ids, ['invoice_lines'], 10) + }), 'price_unit': fields.float('Unit Price', required=True, digits_compute= dp.get_precision('Product Price'), readonly=True, states={'draft': [('readonly', False)]}), - 'type': fields.selection([('make_to_stock', 'from stock'), ('make_to_order', 'on order')], 'Procurement Method', required=True, readonly=True, states={'draft': [('readonly', False)]}, - help="From stock: When needed, the product is taken from the stock or we wait for replenishment.\nOn order: When needed, the product is purchased or produced."), 'price_subtotal': fields.function(_amount_line, string='Subtotal', digits_compute= dp.get_precision('Account')), 'tax_id': fields.many2many('account.tax', 'sale_order_tax', 'order_line_id', 'tax_id', 'Taxes', readonly=True, states={'draft': [('readonly', False)]}), 'address_allotment_id': fields.many2one('res.partner', 'Allotment Partner',help="A partner to whom the particular product needs to be allotted."), @@ -755,6 +894,8 @@ class sale_order_line(osv.osv): 'order_partner_id': fields.related('order_id', 'partner_id', type='many2one', relation='res.partner', store=True, string='Customer'), 'salesman_id':fields.related('order_id', 'user_id', type='many2one', relation='res.users', store=True, string='Salesperson'), 'company_id': fields.related('order_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True), + 'delay': fields.float('Delivery Lead Time', required=True, help="Number of days between the order confirmation and the shipping of the products to the customer", readonly=True, states={'draft': [('readonly', False)]}), + 'procurement_ids': fields.one2many('procurement.order', 'sale_line_id', 'Procurements'), } _order = 'order_id desc, sequence, id' _defaults = { @@ -764,20 +905,18 @@ class sale_order_line(osv.osv): 'product_uos_qty': 1, 'sequence': 10, 'state': 'draft', - 'type': 'make_to_stock', 'price_unit': 0.0, + 'delay': 0.0, } def _get_line_qty(self, cr, uid, line, context=None): - if (line.order_id.invoice_quantity=='order'): - if line.product_uos: - return line.product_uos_qty or 0.0 + if line.product_uos: + return line.product_uos_qty or 0.0 return line.product_uom_qty def _get_line_uom(self, cr, uid, line, context=None): - if (line.order_id.invoice_quantity=='order'): - if line.product_uos: - return line.product_uos.id + if line.product_uos: + return line.product_uos.id return line.product_uom.id def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None): @@ -908,17 +1047,17 @@ class sale_order_line(osv.osv): def copy_data(self, cr, uid, id, default=None, context=None): if not default: default = {} - default.update({'state': 'draft', 'invoice_lines': []}) + default.update({'state': 'draft', 'invoice_lines': [], 'procurement_ids': []}) return super(sale_order_line, self).copy_data(cr, uid, id, default, context=context) def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None): context = context or {} - lang = lang or context.get('lang',False) + lang = lang or context.get('lang', False) if not partner_id: raise osv.except_osv(_('No Customer Defined!'), _('Before choosing a product,\n select a customer in the sales form.')) - warning = {} + warning = False product_uom_obj = self.pool.get('product.uom') partner_obj = self.pool.get('res.partner') product_obj = self.pool.get('product.product') @@ -1090,8 +1229,17 @@ class account_invoice(osv.Model): 'section_id': lambda self, cr, uid, c=None: self.pool.get('res.users').browse(cr, uid, uid, c).default_section_id.id or False, } + +class procurement_order(osv.osv): + _inherit = 'procurement.order' + _columns = { + 'sale_line_id': fields.many2one('sale.order.line', string='Sale Order Line'), + } + + class product_product(osv.Model): _inherit = 'product.product' + def _sales_count(self, cr, uid, ids, field_name, arg, context=None): SaleOrderLine = self.pool['sale.order.line'] return { @@ -1100,5 +1248,8 @@ class product_product(osv.Model): } _columns = { 'sales_count': fields.function(_sales_count, string='# Sales', type='integer'), + } + + # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/sale/sale_demo.xml b/addons/sale/sale_demo.xml index 0c6e92e86ff..2e0019598f7 100644 --- a/addons/sale/sale_demo.xml +++ b/addons/sale/sale_demo.xml @@ -252,6 +252,7 @@ + Test/001 diff --git a/addons/sale/sale_unit_test.xml b/addons/sale/sale_unit_test.xml index 8d7d54d9640..4521bb0e59b 100644 --- a/addons/sale/sale_unit_test.xml +++ b/addons/sale/sale_unit_test.xml @@ -18,7 +18,6 @@ 450 2 2 - make_to_stock @@ -28,7 +27,6 @@ 90 3 3 - make_to_stock diff --git a/addons/sale/sale_view.xml b/addons/sale/sale_view.xml index 6d263f4fdab..25163d9e5b8 100644 --- a/addons/sale/sale_view.xml +++ b/addons/sale/sale_view.xml @@ -149,7 +149,6 @@ - @@ -510,8 +509,6 @@ - - res.company.form.inherit diff --git a/addons/sale/sale_workflow.xml b/addons/sale/sale_workflow.xml index 53542c754bc..831a0a9d12c 100644 --- a/addons/sale/sale_workflow.xml +++ b/addons/sale/sale_workflow.xml @@ -19,7 +19,7 @@ sent function write({'state':'sent'}) - + @@ -162,5 +162,140 @@ + + + + + + + wait_ship + + + + + cancel3 + True + stopall + action_cancel() + + + + + ship + function + action_ship_create() + + + + + ship_ignore + function + action_ignore_delivery_exception() + + + + + ship_end + dummy + + + + + ship_cancel + True + stopall + action_cancel() + + + + + ship_except + function + write({'state':'shipping_except'}) + + + + + + + + + + + + + + + (order_policy=='picking') + + + + + + order_policy=='prepaid' + + + + + + cancel + + + + + + procurement_needed() and ((order_policy!='prepaid') or invoiced) + + + + + not procurement_needed() + + + + + + + + + + + procurement.order + procurement_lines_get() + test_state('finished') + + + + + + ship_except + + + + + + ship_recreate + + + + + + ship_corrected + + + + + + + + + + + ship_cancel + + + diff --git a/addons/sale/security/ir.model.access.csv b/addons/sale/security/ir.model.access.csv index 5fea141bd2b..74a06d201f3 100644 --- a/addons/sale/security/ir.model.access.csv +++ b/addons/sale/security/ir.model.access.csv @@ -1,4 +1,4 @@ -id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink access_sale_order,sale.order,model_sale_order,base.group_sale_salesman,1,1,1,0 access_sale_order_line,sale.order.line,model_sale_order_line,base.group_sale_salesman,1,1,1,1 access_sale_order_line_accountant,sale.order.line accountant,model_sale_order_line,account.group_account_user,1,1,0,0 @@ -33,11 +33,14 @@ access_product_ul_sale_manager,product.ul salemanager,product.model_product_ul,b access_product_category_sale_manager,product.category salemanager,product.model_product_category,base.group_sale_manager,1,1,1,1 access_product_supplierinfo_user,product.supplierinfo.user,product.model_product_supplierinfo,base.group_sale_salesman,1,0,0,0 access_product_supplierinfo_sale_manager,product.supplierinfo salemanager,product.model_product_supplierinfo,base.group_sale_manager,1,1,1,1 -access_pricelist_partnerinfo_sale_manager,pricelist.partnerinfo salemanager,product.model_pricelist_partnerinfo,base.group_sale_manager,1,1,1,1 +access_pricelist_partnerinfo_sale_manager,pricelist.partnerinfo salemanager,product.model_pricelist_partnerinfo,base.group_sale_manager,1,1,1,1 access_product_price_type_sale_manager,product.price.type salemanager,product.model_product_price_type,base.group_sale_manager,1,1,1,1 access_product_pricelist_type_sale_manager,product.pricelist.type salemanager,product.model_product_pricelist_type,base.group_sale_manager,1,1,1,1 access_product_pricelist_sale_manager,product.pricelist salemanager,product.model_product_pricelist,base.group_sale_manager,1,1,1,1 access_product_group_res_partner_sale_manager,res_partner group_sale_manager,base.model_res_partner,base.group_sale_manager,1,1,1,0 access_product_pricelist_version_sale_manager,product.pricelist.version sale_manager,product.model_product_pricelist_version,base.group_sale_manager,1,1,1,1 access_account_invoice_report_salesman,account.invoice.report salesman,account.model_account_invoice_report,base.group_sale_salesman,1,0,0,0 -access_account_move_line_salesman,account.move.line invoice,account.model_account_move_line,base.group_sale_salesman,1,0,0,0 \ No newline at end of file +access_account_move_line_salesman,account.move.line invoice,account.model_account_move_line,base.group_sale_salesman,1,0,0,0 +access_product_price_history_salemanager,prices.history sale manager,product.model_product_price_history,base.group_sale_manager,1,1,1,1 +access_product_price_history_account_user,prices.history account user,product.model_product_price_history,account.group_account_user,1,0,0,0 +access_product_price_history_sale_use,prices.history sale use,product.model_product_price_history,base.group_sale_salesman,1,0,0,0 diff --git a/addons/sale_journal/sale_journal.py b/addons/sale_journal/sale_journal.py index 73fd5b672f1..6a9ca22490d 100644 --- a/addons/sale_journal/sale_journal.py +++ b/addons/sale_journal/sale_journal.py @@ -60,18 +60,6 @@ class picking(osv.osv): 'invoice_type_id': fields.many2one('sale_journal.invoice.type', 'Invoice Type', readonly=True) } -class stock_picking_in(osv.osv): - _inherit = "stock.picking.in" - _columns = { - 'invoice_type_id': fields.many2one('sale_journal.invoice.type', 'Invoice Type', readonly=True) - } - -class stock_picking_out(osv.osv): - _inherit = "stock.picking.out" - _columns = { - 'invoice_type_id': fields.many2one('sale_journal.invoice.type', 'Invoice Type', readonly=True) - } - class sale(osv.osv): _inherit = "sale.order" diff --git a/addons/sale_journal/sale_journal_view.xml b/addons/sale_journal/sale_journal_view.xml index 9d41103252e..d5867cb749a 100644 --- a/addons/sale_journal/sale_journal_view.xml +++ b/addons/sale_journal/sale_journal_view.xml @@ -85,61 +85,6 @@ - - stock.picking.journal.view.tree - stock.picking - - - - - - - - - - stock.picking.journal.view.form - stock.picking.in - - - - - - - - - - stock.picking.journal.view.tree - stock.picking.in - - - - - - - - - - stock.picking.journal.view.form - stock.picking.out - - - - - - - - - - stock.picking.journal.view.tree - stock.picking.out - - - - - - - - res.partner.journal.property.form.inherit res.partner @@ -165,37 +110,18 @@ + + stock.picking.internal.search.inherit stock.picking - + - - stock.picking.out.search.inherit - stock.picking.out - - - - - - - - - - stock.picking.in.search.inherit - stock.picking.in - - - - - - - diff --git a/addons/sale_margin/test/sale_margin.yml b/addons/sale_margin/test/sale_margin.yml index 197f51a9681..666e0602fb7 100644 --- a/addons/sale_margin/test/sale_margin.yml +++ b/addons/sale_margin/test/sale_margin.yml @@ -6,7 +6,6 @@ - !record {model: sale.order, id: sale_order_so11}: date_order: !eval time.strftime('%Y-%m-%d') - invoice_quantity: order name: Test_SO011 order_line: - name: '[CARD] Graphics Card' @@ -17,7 +16,6 @@ product_id: product.product_product_24 product_uos_qty: 100.0 th_weight: 0.0 - type: make_to_stock order_policy: manual partner_id: base.res_partner_4 partner_invoice_id: base.res_partner_address_7 diff --git a/addons/sale_mrp/__openerp__.py b/addons/sale_mrp/__openerp__.py index bc9b84cd471..7f9c1c2dc56 100644 --- a/addons/sale_mrp/__openerp__.py +++ b/addons/sale_mrp/__openerp__.py @@ -40,7 +40,10 @@ from sales order. It adds sales name and sales Reference on production order. 'sale_mrp_view.xml', ], 'demo': [], - 'test':['test/sale_mrp.yml'], + 'test':[ + 'test/cancellation_propagated.yml', + 'test/sale_mrp.yml', + ], 'installable': True, 'auto_install': True, } diff --git a/addons/sale_mrp/sale_mrp.py b/addons/sale_mrp/sale_mrp.py index ffdf0384913..1852326c86f 100644 --- a/addons/sale_mrp/sale_mrp.py +++ b/addons/sale_mrp/sale_mrp.py @@ -64,9 +64,9 @@ class mrp_production(osv.osv): if parent_move_line: move = move_obj.browse(cr, uid, parent_move_line) if field_name == 'name': - res[production.id] = move.sale_line_id and move.sale_line_id.order_id.name or False + res[production.id] = move.procurement_id and move.procurement_id.sale_line_id and move.procurement_id.sale_line_id.order_id.name or False if field_name == 'client_order_ref': - res[production.id] = move.sale_line_id and move.sale_line_id.order_id.client_order_ref or False + res[production.id] = move.procurement_id and move.procurement_id.sale_line_id and move.procurement_id.sale_line_id.order_id.client_order_ref or False return res def _hook_create_post_procurement(self, cr, uid, production, procurement_id, context=None): @@ -74,8 +74,8 @@ class mrp_production(osv.osv): if move.move_dest_id: return get_parent_move(move.move_dest_id) return move - - res = super(mrp_production, self)._hook_create_post_procurement(cr, uid, production, procurement_id, context) + + res = super(mrp_production, self)._hook_create_post_procurement(cr, uid, production, procurement_id, context) if production.move_prod_id: parent_move_line = get_parent_move(production.move_prod_id) if parent_move_line and parent_move_line.sale_line_id: @@ -89,9 +89,17 @@ class mrp_production(osv.osv): class sale_order(osv.Model): - _inherit ='sale.order' + _inherit = 'sale.order' - def _prepare_order_line_procurement(self, cr, uid, order, line, move_id, date_planned, context=None): - result = super(sale_order, self)._prepare_order_line_procurement(cr, uid, order, line, move_id, date_planned, context) + def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None): + result = super(sale_order, self)._prepare_order_line_procurement(cr, uid, order, line, group_id=group_id, context=context) result['property_ids'] = [(6, 0, [x.id for x in line.property_ids])] return result + + +class sale_order_line(osv.osv): + + _inherit = 'sale.order.line' + _columns = { + 'property_ids': fields.many2many('mrp.property', 'sale_order_line_property_rel', 'order_id', 'property_id', 'Properties', readonly=True, states={'draft': [('readonly', False)]}), + } diff --git a/addons/sale_mrp/test/cancellation_propagated.yml b/addons/sale_mrp/test/cancellation_propagated.yml new file mode 100644 index 00000000000..0005e15db53 --- /dev/null +++ b/addons/sale_mrp/test/cancellation_propagated.yml @@ -0,0 +1,92 @@ +- + I first create a warehouse with pick-pack-ship and reception in 2 steps +- + !record {model: stock.warehouse, id: wh_pps}: + name: WareHouse PickPackShip + code: whpps + reception_steps: 'two_steps' + delivery_steps: 'pick_pack_ship' + manufacture_to_resupply: True +- + Next I create a new product in this warehouse +- + !record {model: product.product, id: product_manu}: + name: "My MTO Product" + type: product + uom_id: product.product_uom_unit + uom_po_id: product.product_uom_unit +- + I create a bom for this product +- + !record {model: mrp.bom, id: mrp_bom_test1}: + company_id: base.main_company + name: My BOM + product_id: product_manu + product_qty: 1.0 + type: normal + bom_lines: + - company_id: base.main_company + name: GrapWorks Software + product_id: product.product_product_44 + product_qty: 1.0 +- + And set routes on product to be MTO and manufacture +- + !python {model: product.product}: | + route_warehouse0_manufacture = self.pool.get('stock.warehouse').browse(cr, uid, ref('stock.warehouse0')).manufacture_pull_id.route_id.id + route_warehouse0_mto = self.pool.get('stock.warehouse').browse(cr, uid, ref('stock.warehouse0')).mto_pull_id.route_id.id + self.write(cr, uid, ref('product_manu'), { 'route_ids': [(6, 0, [route_warehouse0_mto,route_warehouse0_manufacture])]}, context=context) +- + I create a sales order +- + !record {model: sale.order, id: sale_order_product_manu}: + partner_id: base.res_partner_3 + note: Create Sales order + warehouse_id: wh_pps + order_line: + - product_id: product_manu + product_uom_qty: 5.00 + +- + Confirm sales order +- + !workflow {model: sale.order, action: order_confirm, ref: sale_order_product_manu} +- + I run scheduler. +- + !python {model: procurement.order}: | + self.run_scheduler(cr, uid) +- + Check the propagation when we cancel the main procurement + * Retrieve related procurements and check that there are all running + * Check that the purchase order has been well created + * Cancel the main procurement + * Check that all procurements related and the purchase order has been well cancelled +- + !python {model: procurement.order}: | + # Retrieve related procu + so = self.pool.get('sale.order').browse(cr, uid, ref('sale_order_product_manu')) + procu_ids = self.search(cr, uid, [('group_id.name', '=', so.name)]) + assert len(procu_ids)>0, 'No procurements are found for sale order "%s" (with id : %d)' %(so.name, so.id) + + # Check that all procurements are running + for procu in self.browse(cr, uid, procu_ids, context=context): + assert procu.state == u'running', 'Procurement with id %d should be "running" but is with a state : %s!' %(procu.id, procu.state) + + # Check that one production order exist + prodor_ids = [proc.production_id for proc in self.browse(cr, uid, procu_ids) if proc.production_id] + assert len(prodor_ids) > 0, 'No production order found !' + + # Cancel the main procurement + main_procu_id = self.search(cr, uid, [('origin', '=', so.name)]) + assert len(main_procu_id) == 1, 'Main procurement not identified !' + self.cancel(cr, uid, main_procu_id,context=context) + assert self.browse(cr, uid, main_procu_id[0]).state == u'cancel', 'Main procurement should be cancelled !' + + # Check that all procurements related are cancelled + for procu in self.browse(cr, uid, procu_ids, context=context): + assert procu.state == u'cancel', 'Procurement with id %d should be with the state "cancel" but is with a state : %s!' %(procu.id, procu.state) + + # Check that the production order is cancelled + for prodor in self.pool.get('mrp.production').browse(cr, uid, [prodor.id for prodor in prodor_ids], context=context): + assert prodor.state == u'cancel', 'Production order %d should be cancelled but is in state : %s!' %(prodor.id, prodor.state) diff --git a/addons/sale_mrp/test/sale_mrp.yml b/addons/sale_mrp/test/sale_mrp.yml index f0ec2de6efc..85e25b502f3 100644 --- a/addons/sale_mrp/test/sale_mrp.yml +++ b/addons/sale_mrp/test/sale_mrp.yml @@ -1,5 +1,5 @@ - - In order to test the sale_mrp module in OpenERP,I start by creating a new product 'Slider Mobile' + In order to test the sale_mrp module in OpenERP, I start by creating a new product 'Slider Mobile' - I define product category Mobile Products Sellable. - @@ -15,13 +15,10 @@ - !record {model: product.template, id: product_template_slidermobile0}: categ_id: product_category_allproductssellable0 - cost_method: standard list_price: 200.0 mes_type: fixed name: Slider Mobile - procure_method: make_to_order standard_price: 189.0 - supply_method: produce type: product uom_id: product.product_uom_unit uom_po_id: product.product_uom_unit @@ -30,11 +27,9 @@ - !record {model: product.product, id: product_product_slidermobile0}: categ_id: product_category_allproductssellable0 - cost_method: standard list_price: 200.0 mes_type: fixed name: Slider Mobile - procure_method: make_to_order seller_delay: '1' seller_ids: - delay: 1 @@ -42,10 +37,16 @@ min_qty: 2.0 qty: 5.0 standard_price: 189.0 - supply_method: produce type: product uom_id: product.product_uom_unit uom_po_id: product.product_uom_unit +- + I add the routes manufacture and mto to the product +- + !python {model: product.product, id: scheduler_product}: | + route_warehouse0_manufacture = self.pool.get('stock.warehouse').browse(cr, uid, ref('stock.warehouse0')).manufacture_pull_id.route_id.id + route_warehouse0_mto = self.pool.get('stock.warehouse').browse(cr, uid, ref('stock.warehouse0')).mto_pull_id.route_id.id + self.write(cr, uid, ref('product_product_slidermobile0'), { 'route_ids': [(6, 0, [route_warehouse0_mto,route_warehouse0_manufacture])]}, context=context) - I create a Bill of Material record for Slider Mobile - @@ -65,7 +66,6 @@ !record {model: sale.order, id: sale_order_so0}: client_order_ref: ref1 date_order: !eval time.strftime('%Y-%m-%d') - invoice_quantity: order name: Test_SO001 order_line: - name: Slider Mobile @@ -76,7 +76,6 @@ delay: 7.0 product_id: product_product_slidermobile0 product_uos_qty: 500.0 - type: make_to_order order_policy: manual partner_id: base.res_partner_4 partner_invoice_id: base.res_partner_address_7 @@ -101,23 +100,25 @@ !python {model: procurement.order}: | sale_order_obj = self.pool.get('sale.order') so = sale_order_obj.browse(cr, uid, ref("sale_order_so0")) - proc_ids = self.search(cr, uid, [('origin','=',so.name)]) - self.signal_button_check(cr, uid, proc_ids) + proc_ids = self.search(cr, uid, [('origin','like',so.name)]) + self.run(cr, uid, proc_ids) - I verify that a procurement state is "running" - !python {model: procurement.order}: | sale_order_obj = self.pool.get('sale.order') so = sale_order_obj.browse(cr, uid, ref("sale_order_so0")) - proc_ids = self.search(cr, uid, [('origin','=',so.name) and ('state','=','running')]) - assert proc_ids, 'Procurement is not in the running state!' + proc_ids = self.search(cr, uid, [('origin','like',so.name)]) + # Check that all procurement are running + for procu in self.browse(cr,uid,proc_ids,context=context): + assert procu.state == u'running', 'Procurement with id %d should be with a state "running" but is with a state : %s!' %(procu.id,procu.state) - I verify that a manufacturing order has been generated, and that its name and reference are correct - !python {model: sale.order}: | mnf_obj = self.pool.get('mrp.production') so = self.browse(cr, uid, ref("sale_order_so0")) - mnf_id = mnf_obj.search(cr, uid, [('origin','=',so.name)]) + mnf_id = mnf_obj.search(cr, uid, [('origin','like',so.name)]) assert mnf_id, 'Manufacturing order has not been generated' mo = mnf_obj.browse(cr, uid, mnf_id)[0] assert mo.sale_name == so.name, 'Wrong Name for the Manufacturing Order. Expected %s, Got %s' % (so.name, mo.name) diff --git a/addons/stock/tests/__init__.py b/addons/sale_mrp/tests/__init__.py similarity index 95% rename from addons/stock/tests/__init__.py rename to addons/sale_mrp/tests/__init__.py index 39ebd5e451f..0ca809f8e9c 100644 --- a/addons/stock/tests/__init__.py +++ b/addons/sale_mrp/tests/__init__.py @@ -19,10 +19,10 @@ # ############################################################################## -from . import test_multicompany +from . import test_move_explode checks = [ - test_multicompany, + test_move_explode, ] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/sale_mrp/tests/test_move_explode.py b/addons/sale_mrp/tests/test_move_explode.py new file mode 100644 index 00000000000..5bb8e8550cc --- /dev/null +++ b/addons/sale_mrp/tests/test_move_explode.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Business Applications +# Copyright (c) 2012-TODAY OpenERP S.A. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +from openerp.tests import common + + +class TestMoveExplode(common.TransactionCase): + + def setUp(self): + super(TestMoveExplode, self).setUp() + cr, uid = self.cr, self.uid + + # Usefull models + self.ir_model_data = self.registry('ir.model.data') + self.sale_order_line = self.registry('sale.order.line') + self.sale_order = self.registry('sale.order') + self.mrp_bom = self.registry('mrp.bom') + + #product that has a phantom bom + self.product_bom_id = self.ir_model_data.get_object_reference(cr, uid, 'product', 'product_product_4')[1] + #bom with that product + self.bom_id = self.ir_model_data.get_object_reference(cr, uid, 'mrp', 'mrp_bom_24')[1] + #partner agrolait + self.partner_id = self.ir_model_data.get_object_reference(cr, uid, 'base', 'res_partner_1')[1] + + def test_00_sale_move_explode(self): + """check that when creating a sale order with a product that has a phantom BoM, move explode into content of the + BoM""" + cr, uid, context = self.cr, self.uid, {} + #create sale order with one sale order line containing product with a phantom bom + so_id = self.sale_order.create(cr, uid, vals={'partner_id': self.partner_id}, context=context) + self.sale_order_line.create(cr, uid, values={'order_id': so_id, 'product_id': self.product_bom_id, 'product_uom_qty': 1}, context=context) + #confirm sale order + self.sale_order.action_button_confirm(cr, uid, [so_id], context=context) + #get all move associated to that sale_order + browse_move_ids = self.sale_order.browse(cr, uid, so_id, context=context).picking_ids[0].move_lines + move_ids = [x.id for x in browse_move_ids] + #we should have same amount of move as the component in the phatom bom + bom = self.mrp_bom.browse(cr, uid, self.bom_id, context=context) + bom_component_length = self.mrp_bom._bom_explode(cr, uid, bom, 1, []) + self.assertEqual(len(move_ids), len(bom_component_length[0])) diff --git a/addons/sale_order_dates/sale_order_dates.py b/addons/sale_order_dates/sale_order_dates.py index f3ff971be9f..61d28f2bbce 100644 --- a/addons/sale_order_dates/sale_order_dates.py +++ b/addons/sale_order_dates/sale_order_dates.py @@ -23,7 +23,7 @@ from datetime import datetime, timedelta from openerp.osv import fields, osv from openerp.tools.translate import _ -from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT +from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class sale_order_dates(osv.osv): """Add several date fields to Sale Orders, computed or user-entered""" @@ -32,21 +32,17 @@ class sale_order_dates(osv.osv): def copy(self, cr, uid, id, default=None, context=None): """Don't copy the requested date along with the Sales Order""" default = dict(default or {}, requested_date=False) - return super(sale_order_dates, self).copy(cr, uid, id, default=default, - context=context) - - def _get_date_planned(self, cr, uid, order, line, start_date, context=None): + return super(sale_order_dates, self).copy(cr, uid, id, default=default, context=context) + + def _get_date_planned(self, cr, uid, order, line, start_date, context=None): """Compute the expected date from the requested date, not the order date""" if order and order.requested_date: - planned_str = self.date_to_datetime(cr, uid, - order.requested_date, context) - date_planned = datetime.strptime(planned_str, - DEFAULT_SERVER_DATETIME_FORMAT) + date_planned = datetime.strptime(order.requested_date, DEFAULT_SERVER_DATETIME_FORMAT) date_planned -= timedelta(days=order.company_id.security_lead) return date_planned.strftime(DEFAULT_SERVER_DATETIME_FORMAT) return super(sale_order_dates, self)._get_date_planned( cr, uid, order, line, start_date, context=context) - + def _get_effective_date(self, cr, uid, ids, name, arg, context=None): """Read the shipping date from the related packings""" # TODO: would be better if it returned the date the picking was processed? @@ -67,14 +63,11 @@ class sale_order_dates(osv.osv): res = {} dates_list = [] for order in self.browse(cr, uid, ids, context=context): - order_datetime_str = self.date_to_datetime(cr, uid, order.date_order, - context) - order_datetime = datetime.strptime(order_datetime_str, - DEFAULT_SERVER_DATETIME_FORMAT) dates_list = [] + order_datetime = datetime.strptime(order.date_order, DEFAULT_SERVER_DATETIME_FORMAT) for line in order.order_line: dt = order_datetime + timedelta(days=line.delay or 0.0) - dt_s = dt.strftime(DEFAULT_SERVER_DATE_FORMAT) + dt_s = dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT) dates_list.append(dt_s) if dates_list: res[order.id] = min(dates_list) @@ -83,8 +76,7 @@ class sale_order_dates(osv.osv): def onchange_requested_date(self, cr, uid, ids, requested_date, commitment_date, context=None): """Warn if the requested dates is sooner than the commitment date""" - if (requested_date and commitment_date - and requested_date < commitment_date): + if (requested_date and commitment_date and requested_date < commitment_date): return {'warning': { 'title': _('Requested date is too soon!'), 'message': _("The date requested by the customer is " @@ -96,11 +88,11 @@ class sale_order_dates(osv.osv): _columns = { 'commitment_date': fields.function(_get_commitment_date, store=True, - type='date', string='Commitment Date', + type='datetime', string='Commitment Date', help="Date by which the products are sure to be delivered. This is " "a date that you can promise to the customer, based on the " "Product Lead Times."), - 'requested_date': fields.date('Requested Date', + 'requested_date': fields.datetime('Requested Date', readonly=True, states={'draft': [('readonly', False)]}, help="Date by which the customer has requested the items to be " "delivered.\n" diff --git a/addons/sale_order_dates/test/requested_date.yml b/addons/sale_order_dates/test/requested_date.yml index d05191a4d99..0e8f7fb1816 100644 --- a/addons/sale_order_dates/test/requested_date.yml +++ b/addons/sale_order_dates/test/requested_date.yml @@ -18,15 +18,12 @@ !python {model: sale.order}: | from datetime import datetime, timedelta from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT - + from openerp.osv import fields so = self.browse(cr, uid, ref("sale.sale_order_6")) security_delay = timedelta(days=so.company_id.security_lead) - requested_date = datetime.strptime( - self.date_to_datetime(cr, uid, so.requested_date), - DEFAULT_SERVER_DATETIME_FORMAT) - right_date = (requested_date - security_delay).strftime( - DEFAULT_SERVER_DATETIME_FORMAT) + requested_date = datetime.strptime(so.requested_date, DEFAULT_SERVER_DATETIME_FORMAT) + right_date = (requested_date - security_delay).strftime(DEFAULT_SERVER_DATETIME_FORMAT) for line in so.order_line: - assert line.procurement_id, "No Procurement was created" - assert line.procurement_id.date_planned == right_date, "The planned date for the Procurement Order is wrong" - assert line.procurement_id.move_id.date_expected == right_date, "The expected date for the Stock Move is wrong" + assert line.procurement_ids, "No Procurement was created" + assert line.procurement_ids[0].date_planned == right_date, "The planned date for the Procurement Order is wrong" + assert line.procurement_ids[0].move_ids and line.procurement_ids[0].move_ids[0].date_expected == right_date, "The expected date for the Stock Move is wrong" diff --git a/addons/sale_stock/__init__.py b/addons/sale_stock/__init__.py index b5899113530..72b3d5672d5 100644 --- a/addons/sale_stock/__init__.py +++ b/addons/sale_stock/__init__.py @@ -20,9 +20,7 @@ ############################################################################## import sale_stock -import stock import report import company import res_config -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: \ No newline at end of file diff --git a/addons/sale_stock/__openerp__.py b/addons/sale_stock/__openerp__.py index 356d2715d2b..dececc36e87 100644 --- a/addons/sale_stock/__openerp__.py +++ b/addons/sale_stock/__openerp__.py @@ -45,26 +45,25 @@ You can choose flexible invoicing methods: 'author': 'OpenERP SA', 'website': 'http://www.openerp.com', 'images': ['images/deliveries_to_invoice.jpeg'], - 'depends': ['sale', 'stock', 'procurement'], + 'depends': ['sale', 'stock_account'], 'data': [ - 'security/sale_stock_security.xml', - 'security/ir.model.access.csv', - 'company_view.xml', - 'sale_stock_view.xml', - 'sale_stock_workflow.xml', - 'stock_view.xml', - 'res_config_view.xml', - 'report/sale_report_view.xml', - ], - 'demo': ['sale_stock_demo.xml'], - 'test': ['test/sale_stock_users.yml', - 'test/cancel_order_sale_stock.yml', - 'test/picking_order_policy.yml', - 'test/prepaid_order_policy.yml', - 'test/sale_order_onchange.yml', - ], + 'security/sale_stock_security.xml', + 'security/ir.model.access.csv', + 'company_view.xml', + 'sale_stock_view.xml', + 'sale_stock_workflow.xml', + 'stock_view.xml', + 'res_config_view.xml', + 'report/sale_report_view.xml', + ], + 'demo': ['sale_stock_demo.xml'], + 'test': [ + 'test/sale_stock_users.yml', + 'test/cancel_order_sale_stock.yml', + 'test/picking_order_policy.yml', + 'test/prepaid_order_policy.yml', + 'test/sale_order_onchange.yml', + ], 'installable': True, 'auto_install': True, - } -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/sale_stock/company.py b/addons/sale_stock/company.py index 5be1dbd524d..129c412187a 100644 --- a/addons/sale_stock/company.py +++ b/addons/sale_stock/company.py @@ -34,5 +34,3 @@ class company(osv.osv): _defaults = { 'security_lead': 0.0, } - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/sale_stock/report/__init__.py b/addons/sale_stock/report/__init__.py index 418927acc78..db31a38b3f3 100644 --- a/addons/sale_stock/report/__init__.py +++ b/addons/sale_stock/report/__init__.py @@ -18,4 +18,5 @@ # along with this program. If not, see . # ############################################################################## -import sale_report \ No newline at end of file + +import sale_report diff --git a/addons/sale_stock/report/sale_report.py b/addons/sale_stock/report/sale_report.py index 7a8234fa7fa..2d126fcdb2a 100644 --- a/addons/sale_stock/report/sale_report.py +++ b/addons/sale_stock/report/sale_report.py @@ -46,4 +46,3 @@ class sale_report(osv.osv): def _group_by(self): return super(sale_report, self)._group_by() + ", s.warehouse_id, s.shipped" -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/sale_stock/res_config.py b/addons/sale_stock/res_config.py index 16af83dd5ac..8c1d5c87f99 100644 --- a/addons/sale_stock/res_config.py +++ b/addons/sale_stock/res_config.py @@ -51,6 +51,9 @@ class sale_configuration(osv.osv_memory): help="Allows you to tag sales order lines with properties."), 'module_project_timesheet': fields.boolean("Project Timesheet"), 'module_project_mrp': fields.boolean("Project MRP"), + 'group_route_so_lines': fields.boolean('Choose MTO, drop shipping,... on sales order lines', + implied_group='sale_stock.group_route_so_lines', + help="Allows you to choose a delivery route on sales order lines"), } _defaults = { @@ -80,7 +83,7 @@ class sale_configuration(osv.osv_memory): ir_values.set_default(cr, SUPERUSER_ID, 'sale.order', 'picking_policy', default_picking_policy) res = super(sale_configuration, self).set_sale_defaults(cr, uid, ids, context) return res - + def onchange_invoice_methods(self, cr, uid, ids, group_invoice_so_lines, group_invoice_deli_orders, context=None): if not group_invoice_deli_orders: return {'value': {'default_order_policy': 'manual'}} diff --git a/addons/sale_stock/res_config_view.xml b/addons/sale_stock/res_config_view.xml index b039251d827..89c2f191915 100644 --- a/addons/sale_stock/res_config_view.xml +++ b/addons/sale_stock/res_config_view.xml @@ -1,7 +1,6 @@ - sale settings sale.config.settings @@ -25,14 +24,14 @@ -
-
+
@@ -62,9 +61,14 @@
+ +
+ +
+
- \ No newline at end of file diff --git a/addons/sale_stock/sale_stock.py b/addons/sale_stock/sale_stock.py index b2ee991bf0e..0020ebf1d8e 100644 --- a/addons/sale_stock/sale_stock.py +++ b/addons/sale_stock/sale_stock.py @@ -22,48 +22,22 @@ from datetime import datetime, timedelta from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare from openerp.osv import fields, osv +from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ import pytz from openerp import SUPERUSER_ID class sale_order(osv.osv): _inherit = "sale.order" - + def copy(self, cr, uid, id, default=None, context=None): if not default: default = {} default.update({ 'shipped': False, - 'picking_ids': [], + 'picking_ids': [] }) return super(sale_order, self).copy(cr, uid, id, default, context=context) - - def shipping_policy_change(self, cr, uid, ids, policy, context=None): - if not policy: - return {} - inv_qty = 'order' - if policy == 'prepaid': - inv_qty = 'order' - elif policy == 'picking': - inv_qty = 'procurement' - return {'value': {'invoice_quantity': inv_qty}} - - def write(self, cr, uid, ids, vals, context=None): - if vals.get('order_policy', False): - if vals['order_policy'] == 'prepaid': - vals.update({'invoice_quantity': 'order'}) - elif vals['order_policy'] == 'picking': - vals.update({'invoice_quantity': 'procurement'}) - return super(sale_order, self).write(cr, uid, ids, vals, context=context) - - def create(self, cr, uid, vals, context=None): - if vals.get('order_policy', False): - if vals['order_policy'] == 'prepaid': - vals.update({'invoice_quantity': 'order'}) - if vals['order_policy'] == 'picking': - vals.update({'invoice_quantity': 'procurement'}) - order = super(sale_order, self).create(cr, uid, vals, context=context) - return order def _get_default_warehouse(self, cr, uid, context=None): company_id = self.pool.get('res.users')._get_company(cr, uid, context=context) @@ -72,60 +46,50 @@ class sale_order(osv.osv): return False return warehouse_ids[0] - # This is False - def _picked_rate(self, cr, uid, ids, name, arg, context=None): - if not ids: - return {} + def _get_shipped(self, cr, uid, ids, name, args, context=None): res = {} - tmp = {} - for id in ids: - tmp[id] = {'picked': 0.0, 'total': 0.0} - cr.execute('''SELECT - p.sale_id as sale_order_id, sum(m.product_qty) as nbr, mp.state as procurement_state, m.state as move_state, p.type as picking_type - FROM - stock_move m - LEFT JOIN - stock_picking p on (p.id=m.picking_id) - LEFT JOIN - procurement_order mp on (mp.move_id=m.id) - WHERE - p.sale_id IN %s GROUP BY m.state, mp.state, p.sale_id, p.type''', (tuple(ids),)) - - for item in cr.dictfetchall(): - if item['move_state'] == 'cancel': - continue - - if item['picking_type'] == 'in':#this is a returned picking - tmp[item['sale_order_id']]['total'] -= item['nbr'] or 0.0 # Deducting the return picking qty - if item['procurement_state'] == 'done' or item['move_state'] == 'done': - tmp[item['sale_order_id']]['picked'] -= item['nbr'] or 0.0 + for sale in self.browse(cr, uid, ids, context=context): + group = sale.procurement_group_id + if group: + res[sale.id] = all([proc.state in ['cancel', 'done'] for proc in group.procurement_ids]) else: - tmp[item['sale_order_id']]['total'] += item['nbr'] or 0.0 - if item['procurement_state'] == 'done' or item['move_state'] == 'done': - tmp[item['sale_order_id']]['picked'] += item['nbr'] or 0.0 - - for order in self.browse(cr, uid, ids, context=context): - if order.shipped: - res[order.id] = 100.0 - else: - res[order.id] = tmp[order.id]['total'] and (100.0 * tmp[order.id]['picked'] / tmp[order.id]['total']) or 0.0 + res[sale.id] = False return res - + + def _get_orders(self, cr, uid, ids, context=None): + res = set() + for move in self.browse(cr, uid, ids, context=context): + if move.procurement_id and move.procurement_id.sale_line_id: + res.add(move.procurement_id.sale_line_id.order_id.id) + return list(res) + + def _get_orders_procurements(self, cr, uid, ids, context=None): + res = set() + for proc in self.pool.get('procurement.order').browse(cr, uid, ids, context=context): + if proc.state =='done' and proc.sale_line_id: + res.add(proc.sale_line_id.order_id.id) + return list(res) + + def _get_picking_ids(self, cr, uid, ids, name, args, context=None): + res = {} + for sale in self.browse(cr, uid, ids, context=context): + if not sale.procurement_group_id: + res[sale.id] = [] + continue + res[sale.id] = self.pool.get('stock.picking').search(cr, uid, [('group_id', '=', sale.procurement_group_id.id)], context=context) + return res + + def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None): + vals = super(sale_order, self)._prepare_order_line_procurement(cr, uid, order, line, group_id=group_id, context=context) + location_id = order.partner_shipping_id.property_stock_customer.id + vals['location_id'] = location_id + routes = line.route_id and [(4, line.route_id.id)] or [] + vals['route_ids'] = routes + vals['warehouse_id'] = order.warehouse_id and order.warehouse_id.id or False + vals['partner_dest_id'] = order.partner_shipping_id.id + return vals + _columns = { - 'state': fields.selection([ - ('draft', 'Draft Quotation'), - ('sent', 'Quotation Sent'), - ('cancel', 'Cancelled'), - ('waiting_date', 'Waiting Schedule'), - ('progress', 'Sales Order'), - ('manual', 'Sale to Invoice'), - ('shipping_except', 'Shipping Exception'), - ('invoice_except', 'Invoice Exception'), - ('done', 'Done'), - ], 'Status', readonly=True,help="Gives the status of the quotation or sales order.\ - \nThe exception status is automatically set when a cancel operation occurs \ - in the invoice validation (Invoice Exception) or in the picking list process (Shipping Exception).\nThe 'Waiting Schedule' status is set when the invoice is confirmed\ - but waiting for the scheduler to run on the order date.", select=True), 'incoterm': fields.many2one('stock.incoterms', 'Incoterm', help="International Commercial Terms are a series of predefined commercial terms used in international transactions."), 'picking_policy': fields.selection([('direct', 'Deliver each product when available'), ('one', 'Deliver all products at once')], 'Shipping Policy', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, @@ -136,33 +100,17 @@ class sale_order(osv.osv): ('prepaid', 'Before Delivery'), ], 'Create Invoice', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="""On demand: A draft invoice can be created from the sales order when needed. \nOn delivery order: A draft invoice can be created from the delivery order when the products have been delivered. \nBefore delivery: A draft invoice is created from the sales order and must be paid before the products can be delivered."""), - 'picking_ids': fields.one2many('stock.picking.out', 'sale_id', 'Related Picking', readonly=True, help="This is a list of delivery orders that has been generated for this sales order."), - 'shipped': fields.boolean('Delivered', readonly=True, help="It indicates that the sales order has been delivered. This field is updated only after the scheduler(s) have been launched."), - 'picked_rate': fields.function(_picked_rate, string='Picked', type='float'), + 'shipped': fields.function(_get_shipped, string='Delivered', type='boolean', store={ + 'procurement.order': (_get_orders_procurements, ['state'], 10) + }), 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True), - 'invoice_quantity': fields.selection([('order', 'Ordered Quantities'), ('procurement', 'Shipped Quantities')], 'Invoice on', - help="The sales order will automatically create the invoice proposition (draft invoice).\ - You have to choose if you want your invoice based on ordered ", required=True, readonly=True, states={'draft': [('readonly', False)]}), + 'picking_ids': fields.function(_get_picking_ids, method=True, type='one2many', relation='stock.picking', string='Picking associated to this sale'), } _defaults = { - 'warehouse_id': _get_default_warehouse, - 'picking_policy': 'direct', - 'order_policy': 'manual', - 'invoice_quantity': 'order', - } - - # Form filling - def unlink(self, cr, uid, ids, context=None): - sale_orders = self.read(cr, uid, ids, ['state'], context=context) - unlink_ids = [] - for s in sale_orders: - if s['state'] in ['draft', 'cancel']: - unlink_ids.append(s['id']) - else: - raise osv.except_osv(_('Invalid Action!'), _('In order to delete a confirmed sales order, you must cancel it. \nTo do so, you must first cancel all related delivery order(s).')) - - return osv.osv.unlink(self, cr, uid, unlink_ids, context=context) - + 'warehouse_id': _get_default_warehouse, + 'picking_policy': 'direct', + 'order_policy': 'manual', + } def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None): val = {} if warehouse_id: @@ -173,33 +121,39 @@ class sale_order(osv.osv): def action_view_delivery(self, cr, uid, ids, context=None): ''' - This function returns an action that display existing delivery orders of given sales order ids. It can either be a in a list or in a form view, if there is only one delivery order to show. + This function returns an action that display existing delivery orders + of given sales order ids. It can either be a in a list or in a form + view, if there is only one delivery order to show. ''' + mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') - result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_picking_tree') + result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_picking_tree_all') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] + #compute the number of delivery orders to display pick_ids = [] for so in self.browse(cr, uid, ids, context=context): pick_ids += [picking.id for picking in so.picking_ids] + #choose the view_mode accordingly if len(pick_ids) > 1: - result['domain'] = "[('id','in',["+','.join(map(str, pick_ids))+"])]" + result['domain'] = "[('id','in',[" + ','.join(map(str, pick_ids)) + "])]" else: - res = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_out_form') + res = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_form') result['views'] = [(res and res[1] or False, 'form')] result['res_id'] = pick_ids and pick_ids[0] or False return result def action_invoice_create(self, cr, uid, ids, grouped=False, states=['confirmed', 'done', 'exception'], date_invoice = False, context=None): - picking_obj = self.pool.get('stock.picking') - res = super(sale_order,self).action_invoice_create( cr, uid, ids, grouped=grouped, states=states, date_invoice = date_invoice, context=context) + move_obj = self.pool.get("stock.move") + res = super(sale_order,self).action_invoice_create(cr, uid, ids, grouped=grouped, states=states, date_invoice = date_invoice, context=context) for order in self.browse(cr, uid, ids, context=context): if order.order_policy == 'picking': - picking_obj.write(cr, uid, map(lambda x: x.id, order.picking_ids), {'invoice_state': 'invoiced'}) + for picking in order.picking_ids: + move_obj.write(cr, uid, [x.id for x in picking.move_lines], {'invoice_state': 'invoiced'}, context=context) return res def action_cancel(self, cr, uid, ids, context=None): @@ -214,13 +168,7 @@ class sale_order(osv.osv): raise osv.except_osv( _('Cannot cancel sales order!'), _('You must first cancel all delivery order(s) attached to this sales order.')) - if pick.state == 'cancel': - for mov in pick.move_lines: - proc_ids = proc_obj.search(cr, uid, [('move_id', '=', mov.id)]) - if proc_ids: - proc_obj.signal_button_check(cr, uid, proc_ids) - for r in self.read(cr, uid, ids, ['picking_ids']): - stock_obj.signal_button_cancel(cr, uid, r['picking_ids']) + stock_obj.signal_button_cancel(cr, uid, [p.id for p in sale.picking_ids]) return super(sale_order, self).action_cancel(cr, uid, ids, context=context) def action_wait(self, cr, uid, ids, context=None): @@ -231,234 +179,18 @@ class sale_order(osv.osv): self.write(cr, uid, [o.id], {'order_policy': 'manual'}, context=context) return res - def procurement_lines_get(self, cr, uid, ids, *args): - res = [] - for order in self.browse(cr, uid, ids, context={}): - for line in order.order_line: - if line.procurement_id: - res.append(line.procurement_id.id) - return res - - def date_to_datetime(self, cr, uid, userdate, context=None): - """ Convert date values expressed in user's timezone to - server-side UTC timestamp, assuming a default arbitrary - time of 12:00 AM - because a time is needed. - - :param str userdate: date string in in user time zone - :return: UTC datetime string for server-side use - """ - # TODO: move to fields.datetime in server after 7.0 - user_date = datetime.strptime(userdate, DEFAULT_SERVER_DATE_FORMAT) - if context and context.get('tz'): - tz_name = context['tz'] - else: - tz_name = self.pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] - if tz_name: - utc = pytz.timezone('UTC') - context_tz = pytz.timezone(tz_name) - user_datetime = user_date + timedelta(hours=12.0) - local_timestamp = context_tz.localize(user_datetime, is_dst=False) - user_datetime = local_timestamp.astimezone(utc) - return user_datetime.strftime(DEFAULT_SERVER_DATETIME_FORMAT) - return user_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT) - - # if mode == 'finished': - # returns True if all lines are done, False otherwise - # if mode == 'canceled': - # returns True if there is at least one canceled line, False otherwise - def test_state(self, cr, uid, ids, mode, *args): - assert mode in ('finished', 'canceled'), _("invalid mode for test_state") - finished = True - canceled = False - write_done_ids = [] - write_cancel_ids = [] - for order in self.browse(cr, uid, ids, context={}): - for line in order.order_line: - if (not line.procurement_id) or (line.procurement_id.state=='done'): - if line.state != 'done': - write_done_ids.append(line.id) - else: - finished = False - if line.procurement_id: - if (line.procurement_id.state == 'cancel'): - canceled = True - if line.state != 'exception': - write_cancel_ids.append(line.id) - if write_done_ids: - self.pool.get('sale.order.line').write(cr, uid, write_done_ids, {'state': 'done'}) - if write_cancel_ids: - self.pool.get('sale.order.line').write(cr, uid, write_cancel_ids, {'state': 'exception'}) - - if mode == 'finished': - return finished - elif mode == 'canceled': - return canceled - - def _prepare_order_line_procurement(self, cr, uid, order, line, move_id, date_planned, context=None): - return { - 'name': line.name, - 'origin': order.name, - 'date_planned': date_planned, - 'product_id': line.product_id.id, - 'product_qty': line.product_uom_qty, - 'product_uom': line.product_uom.id, - 'product_uos_qty': (line.product_uos and line.product_uos_qty)\ - or line.product_uom_qty, - 'product_uos': (line.product_uos and line.product_uos.id)\ - or line.product_uom.id, - 'location_id': order.warehouse_id.lot_stock_id.id, - 'procure_method': line.type, - 'move_id': move_id, - 'company_id': order.company_id.id, - 'note': line.name, - } - - def _prepare_order_line_move(self, cr, uid, order, line, picking_id, date_planned, context=None): - location_id = order.warehouse_id.lot_stock_id.id - output_id = order.warehouse_id.lot_output_id.id - return { - 'name': line.name, - 'picking_id': picking_id, - 'product_id': line.product_id.id, - 'date': date_planned, - 'date_expected': date_planned, - 'product_qty': line.product_uom_qty, - 'product_uom': line.product_uom.id, - 'product_uos_qty': (line.product_uos and line.product_uos_qty) or line.product_uom_qty, - 'product_uos': (line.product_uos and line.product_uos.id)\ - or line.product_uom.id, - 'product_packaging': line.product_packaging.id, - 'partner_id': line.address_allotment_id.id or order.partner_shipping_id.id, - 'location_id': location_id, - 'location_dest_id': output_id, - 'sale_line_id': line.id, - 'tracking_id': False, - 'state': 'draft', - #'state': 'waiting', - 'company_id': order.company_id.id, - 'price_unit': line.product_id.standard_price or 0.0 - } - - def _prepare_order_picking(self, cr, uid, order, context=None): - pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out') - return { - 'name': pick_name, - 'origin': order.name, - 'date': self.date_to_datetime(cr, uid, order.date_order, context), - 'type': 'out', - 'state': 'auto', - 'move_type': order.picking_policy, - 'sale_id': order.id, - 'partner_id': order.partner_shipping_id.id, - 'note': order.note, - 'invoice_state': (order.order_policy=='picking' and '2binvoiced') or 'none', - 'company_id': order.company_id.id, - } - - def ship_recreate(self, cr, uid, order, line, move_id, proc_id): - """ - Define ship_recreate for process after shipping exception - param order: sales order to which the order lines belong - param line: sales order line records to procure - param move_id: the ID of stock move - param proc_id: the ID of procurement - """ - move_obj = self.pool.get('stock.move') - proc_obj = self.pool.get('procurement.order') - if move_id and order.state == 'shipping_except': - current_move = move_obj.browse(cr, uid, move_id) - moves = [] - for picking in order.picking_ids: - if picking.id != current_move.picking_id.id and picking.state != 'cancel': - moves.extend(move for move in picking.move_lines if move.state != 'cancel' and move.sale_line_id.id == line.id) - if moves: - product_qty = current_move.product_qty - product_uos_qty = current_move.product_uos_qty - for move in moves: - product_qty -= move.product_qty - product_uos_qty -= move.product_uos_qty - if product_qty > 0 or product_uos_qty > 0: - move_obj.write(cr, uid, [move_id], {'product_qty': product_qty, 'product_uos_qty': product_uos_qty}) - proc_obj.write(cr, uid, [proc_id], {'product_qty': product_qty, 'product_uos_qty': product_uos_qty}) - else: - current_move.unlink() - proc_obj.unlink(cr, uid, [proc_id]) - return True - def _get_date_planned(self, cr, uid, order, line, start_date, context=None): - """Compute the Stock Move date for the Sale Order Line""" - start_date = self.date_to_datetime(cr, uid, start_date, context) - date_planned = datetime.strptime(start_date, DEFAULT_SERVER_DATETIME_FORMAT) + timedelta(days=line.delay or 0.0) + date_planned = super(sale_order, self)._get_date_planned(cr, uid, order, line, start_date, context=context) date_planned = (date_planned - timedelta(days=order.company_id.security_lead)).strftime(DEFAULT_SERVER_DATETIME_FORMAT) return date_planned - def _create_pickings_and_procurements(self, cr, uid, order, order_lines, picking_id=False, context=None): - """Create the required procurements to supply sales order lines, also connecting - the procurements to appropriate stock moves in order to bring the goods to the - sales order's requested location. - - If ``picking_id`` is provided, the stock moves will be added to it, otherwise - a standard outgoing picking will be created to wrap the stock moves, as returned - by :meth:`~._prepare_order_picking`. - - Modules that wish to customize the procurements or partition the stock moves over - multiple stock pickings may override this method and call ``super()`` with - different subsets of ``order_lines`` and/or preset ``picking_id`` values. - - :param browse_record order: sales order to which the order lines belong - :param list(browse_record) order_lines: sales order line records to procure - :param int picking_id: optional ID of a stock picking to which the created stock moves - will be added. A new picking will be created if ommitted. - :return: True - """ - move_obj = self.pool.get('stock.move') - picking_obj = self.pool.get('stock.picking') - procurement_obj = self.pool.get('procurement.order') - proc_ids = [] - - for line in order_lines: - if line.state == 'done': - continue - - date_planned = self._get_date_planned(cr, uid, order, line, order.date_order, context=context) - - if line.product_id: - if line.product_id.type in ('product', 'consu'): - if not picking_id: - picking_id = picking_obj.create(cr, uid, self._prepare_order_picking(cr, uid, order, context=context)) - move_id = move_obj.create(cr, uid, self._prepare_order_line_move(cr, uid, order, line, picking_id, date_planned, context=context)) - else: - # a service has no stock move - move_id = False - - proc_id = procurement_obj.create(cr, uid, self._prepare_order_line_procurement(cr, uid, order, line, move_id, date_planned, context=context)) - proc_ids.append(proc_id) - line.write({'procurement_id': proc_id}) - self.ship_recreate(cr, uid, order, line, move_id, proc_id) - - if picking_id: - picking_obj.signal_button_confirm(cr, uid, [picking_id]) - procurement_obj.signal_button_confirm(cr, uid, proc_ids) - - val = {} - if order.state == 'shipping_except': - val['state'] = 'progress' - val['shipped'] = False - - if (order.order_policy == 'manual'): - for line in order.order_line: - if (not line.invoiced) and (line.state not in ('cancel', 'draft')): - val['state'] = 'manual' - break - order.write(val) - return True - - def action_ship_create(self, cr, uid, ids, context=None): - for order in self.browse(cr, uid, ids, context=context): - self._create_pickings_and_procurements(cr, uid, order, order.order_line, None, context=context) - return True + def _prepare_procurement_group(self, cr, uid, order, context=None): + res = super(sale_order, self)._prepare_procurement_group(cr, uid, order, context=None) + res.update({'move_type': order.picking_policy}) + return res def action_ship_end(self, cr, uid, ids, context=None): + super(sale_order, self).action_ship_end(cr, uid, ids, context=context) for order in self.browse(cr, uid, ids, context=context): val = {'shipped': True} if order.state == 'shipping_except': @@ -468,15 +200,12 @@ class sale_order(osv.osv): if (not line.invoiced) and (line.state not in ('cancel', 'draft')): val['state'] = 'manual' break - for line in order.order_line: - towrite = [] - if line.state == 'exception': - towrite.append(line.id) - if towrite: - self.pool.get('sale.order.line').write(cr, uid, towrite, {'state': 'done'}, context=context) res = self.write(cr, uid, [order.id], val) return True + + + def has_stockable_products(self, cr, uid, ids, *args): for order in self.browse(cr, uid, ids): for order_line in order.order_line: @@ -486,6 +215,15 @@ class sale_order(osv.osv): class sale_order_line(osv.osv): + _inherit = 'sale.order.line' + + def need_procurement(self, cr, uid, ids, context=None): + #when sale is installed alone, there is no need to create procurements, but with sale_stock + #we must create a procurement for each product that is not a service. + for line in self.browse(cr, uid, ids, context=context): + if line.product_id and line.product_id.type != 'service': + return True + return super(sale_order_line, self).need_procurement(cr, uid, ids, context=context) def _number_packages(self, cr, uid, ids, field_name, arg, context=None): res = {} @@ -496,35 +234,16 @@ class sale_order_line(osv.osv): res[line.id] = 1 return res - _inherit = 'sale.order.line' - _columns = { - 'delay': fields.float('Delivery Lead Time', required=True, help="Number of days between the order confirmation and the shipping of the products to the customer", readonly=True, states={'draft': [('readonly', False)]}), - 'procurement_id': fields.many2one('procurement.order', 'Procurement'), - 'property_ids': fields.many2many('mrp.property', 'sale_order_line_property_rel', 'order_id', 'property_id', 'Properties', readonly=True, states={'draft': [('readonly', False)]}), + _columns = { 'product_packaging': fields.many2one('product.packaging', 'Packaging'), - 'move_ids': fields.one2many('stock.move', 'sale_line_id', 'Inventory Moves', readonly=True), 'number_packages': fields.function(_number_packages, type='integer', string='Number Packages'), + 'route_id': fields.many2one('stock.location.route', 'Route', domain=[('sale_selectable', '=', True)]), } + _defaults = { - 'delay': 0.0, 'product_packaging': False, } - def _get_line_qty(self, cr, uid, line, context=None): - if line.procurement_id and not (line.order_id.invoice_quantity=='order'): - return self.pool.get('procurement.order').quantity_get(cr, uid, - line.procurement_id.id, context=context) - else: - return super(sale_order_line, self)._get_line_qty(cr, uid, line, context=context) - - - def _get_line_uom(self, cr, uid, line, context=None): - if line.procurement_id and not (line.order_id.invoice_quantity=='order'): - return self.pool.get('procurement.order').uom_get(cr, uid, - line.procurement_id.id, context=context) - else: - return super(sale_order_line, self)._get_line_uom(cr, uid, line, context=context) - def button_cancel(self, cr, uid, ids, context=None): res = super(sale_order_line, self).button_cancel(cr, uid, ids, context=context) for line in self.browse(cr, uid, ids, context=context): @@ -532,7 +251,7 @@ class sale_order_line(osv.osv): if move_line.state != 'cancel': raise osv.except_osv( _('Cannot cancel sales order line!'), - _('You must first cancel stock moves attached to this sales order line.')) + _('You must first cancel stock moves attached to this sales order line.')) return res def copy_data(self, cr, uid, id, default=None, context=None): @@ -555,14 +274,11 @@ class sale_order_line(osv.osv): res = self.product_id_change(cr, uid, ids, pricelist=pricelist, product=product, qty=qty, uom=uom, partner_id=partner_id, packaging=packaging, flag=False, context=context) - warning_msgs = res.get('warning') and res['warning']['message'] + warning_msgs = res.get('warning') and res['warning'].get('message', '') or '' products = product_obj.browse(cr, uid, product, context=context) if not products.packaging: packaging = result['product_packaging'] = False - elif not packaging and products.packaging and not flag: - packaging = products.packaging[0].id - result['product_packaging'] = packaging if packaging: default_uom = products.uom_id and products.uom_id.id @@ -588,12 +304,12 @@ class sale_order_line(osv.osv): return {'value': result, 'warning': warning} - def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, + + def product_id_change_with_wh(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, - lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None): + lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, warehouse_id=False, context=None): context = context or {} product_uom_obj = self.pool.get('product.uom') - partner_obj = self.pool.get('res.partner') product_obj = self.pool.get('product.product') warning = {} res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty=qty, @@ -607,29 +323,48 @@ class sale_order_line(osv.osv): #update of result obtained in super function product_obj = product_obj.browse(cr, uid, product, context=context) res['value']['delay'] = (product_obj.sale_delay or 0.0) - res['value']['type'] = product_obj.procure_method - - #check if product is available, and if not: raise an error - uom2 = False - if uom: - uom2 = product_uom_obj.browse(cr, uid, uom, context=context) - if product_obj.uom_id.category_id.id != uom2.category_id.id: - uom = False - if not uom2: - uom2 = product_obj.uom_id # Calling product_packaging_change function after updating UoM res_packing = self.product_packaging_change(cr, uid, ids, pricelist, product, qty, uom, partner_id, packaging, context=context) res['value'].update(res_packing.get('value', {})) warning_msgs = res_packing.get('warning') and res_packing['warning']['message'] or '' - compare_qty = float_compare(product_obj.virtual_available * uom2.factor, qty * product_obj.uom_id.factor, precision_rounding=product_obj.uom_id.rounding) - if (product_obj.type=='product') and int(compare_qty) == -1 \ - and (product_obj.procure_method=='make_to_stock'): - warn_msg = _('You plan to sell %.2f %s but you only have %.2f %s available !\nThe real stock is %.2f %s. (without reservations)') % \ - (qty, uom2 and uom2.name or product_obj.uom_id.name, - max(0,product_obj.virtual_available), product_obj.uom_id.name, - max(0,product_obj.qty_available), product_obj.uom_id.name) - warning_msgs += _("Not enough stock ! : ") + warn_msg + "\n\n" + + #determine if the product is MTO or not (for a further check) + isMto = False + if warehouse_id: + warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context) + for product_route in product_obj.route_ids: + if warehouse.mto_pull_id and warehouse.mto_pull_id.route_id and warehouse.mto_pull_id.route_id.id == product_route.id: + isMto = True + break + else: + try: + mto_route_id = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'route_warehouse0_mto').id + except: + # if route MTO not found in ir_model_data, we treat the product as in MTS + mto_route_id = False + if mto_route_id: + for product_route in product_obj.route_ids: + if product_route.id == mto_route_id: + isMto = True + break + + #check if product is available, and if not: raise a warning, but do this only for products that aren't processed in MTO + if not isMto: + uom2 = False + if uom: + uom2 = product_uom_obj.browse(cr, uid, uom, context=context) + if product_obj.uom_id.category_id.id != uom2.category_id.id: + uom = False + if not uom2: + uom2 = product_obj.uom_id + compare_qty = float_compare(product_obj.virtual_available * uom2.factor, qty * product_obj.uom_id.factor, precision_rounding=product_obj.uom_id.rounding) + if (product_obj.type=='product') and int(compare_qty) == -1: + warn_msg = _('You plan to sell %.2f %s but you only have %.2f %s available !\nThe real stock is %.2f %s. (without reservations)') % \ + (qty, uom2 and uom2.name or product_obj.uom_id.name, + max(0,product_obj.virtual_available), product_obj.uom_id.name, + max(0,product_obj.qty_available), product_obj.uom_id.name) + warning_msgs += _("Not enough stock ! : ") + warn_msg + "\n\n" #update of warning messages if warning_msgs: @@ -640,33 +375,82 @@ class sale_order_line(osv.osv): res.update({'warning': warning}) return res +class stock_move(osv.osv): + _inherit = 'stock.move' -class sale_advance_payment_inv(osv.osv_memory): - _inherit = "sale.advance.payment.inv" + def action_cancel(self, cr, uid, ids, context=None): + sale_ids = [] + for move in self.browse(cr, uid, ids, context=context): + if move.procurement_id and move.procurement_id.sale_line_id: + sale_ids.append(move.procurement_id.sale_line_id.order_id.id) + if sale_ids: + self.pool.get('sale.order').signal_ship_except(cr, uid, sale_ids) + return super(stock_move, self).action_cancel(cr, uid, ids, context=context) - def _create_invoices(self, cr, uid, inv_values, sale_id, context=None): - result = super(sale_advance_payment_inv, self)._create_invoices(cr, uid, inv_values, sale_id, context=context) + def _create_invoice_line_from_vals(self, cr, uid, move, invoice_line_vals, context=None): + invoice_line_id = self.pool.get('account.invoice.line').create(cr, uid, invoice_line_vals, context=context) + if move.procurement_id and move.procurement_id.sale_line_id: + sale_line = move.procurement_id.sale_line_id + self.pool.get('sale.order.line').write(cr, uid, [sale_line.id], { + 'invoice_lines': [(4, invoice_line_id)] + }, context=context) + self.pool.get('sale.order').write(cr, uid, [sale_line.order_id.id], { + 'invoice_ids': [(4, invoice_line_vals['invoice_id'])], + }) + return invoice_line_id + + def _get_master_data(self, cr, uid, move, company, context=None): + if move.procurement_id and move.procurement_id.sale_line_id: + sale_order = move.procurement_id.sale_line_id.order_id + return sale_order.partner_invoice_id, sale_order.user_id.id, sale_order.pricelist_id.currency_id.id + return super(stock_move, self)._get_master_data(cr, uid, move, company, context=context) + + def _get_invoice_line_vals(self, cr, uid, move, partner, inv_type, context=None): + res = super(stock_move, self)._get_invoice_line_vals(cr, uid, move, partner, inv_type, context=context) + if move.procurement_id and move.procurement_id.sale_line_id: + sale_line = move.procurement_id.sale_line_id + res['invoice_line_tax_id'] = [(6, 0, [x.id for x in sale_line.tax_id])] + res['account_analytic_id'] = sale_line.order_id.project_id and sale_line.order_id.project_id.id or False + res['price_unit'] = sale_line.price_unit + res['discount'] = sale_line.discount + return res + + +class stock_location_route(osv.osv): + _inherit = "stock.location.route" + _columns = { + 'sale_selectable': fields.boolean("Selectable on Sales Order Line") + } + + +class stock_picking(osv.osv): + _inherit = "stock.picking" + + def _get_sale_id(self, cr, uid, ids, name, args, context=None): + sale_obj = self.pool.get("sale.order") + res = {} + for picking in self.browse(cr, uid, ids, context=context): + res[picking.id] = False + if picking.group_id: + sale_ids = sale_obj.search(cr, uid, [('procurement_group_id', '=', picking.group_id.id)], context=context) + if sale_ids: + res[picking.id] = sale_ids[0] + return res + + _columns = { + 'sale_id': fields.function(_get_sale_id, type="many2one", relation="sale.order", string="Sale Order"), + } + + def _create_invoice_from_picking(self, cr, uid, picking, vals, context=None): sale_obj = self.pool.get('sale.order') sale_line_obj = self.pool.get('sale.order.line') - wizard = self.browse(cr, uid, [result], context) - sale = sale_obj.browse(cr, uid, sale_id, context=context) - - # If invoice on picking: add the cost on the SO - # If not, the advance will be deduced when generating the final invoice - line_name = inv_values.get('invoice_line') and inv_values.get('invoice_line')[0][2].get('name') or '' - line_tax = inv_values.get('invoice_line') and inv_values.get('invoice_line')[0][2].get('invoice_line_tax_id') or False - if sale.order_policy == 'picking': - vals = { - 'order_id': sale.id, - 'name': line_name, - 'price_unit': -inv_amount, - 'product_uom_qty': wizard.qtty or 1.0, - 'product_uos_qty': wizard.qtty or 1.0, - 'product_uos': res.get('uos_id', False), - 'product_uom': res.get('uom_id', False), - 'product_id': wizard.product_id.id or False, - 'discount': False, - 'tax_id': line_tax, - } - sale_line_obj.create(cr, uid, vals, context=context) - return result + invoice_line_obj = self.pool.get('account.invoice.line') + invoice_id = super(stock_picking, self)._create_invoice_from_picking(cr, uid, picking, vals, context=context) + if picking.group_id: + sale_ids = sale_obj.search(cr, uid, [('procurement_group_id', '=', picking.group_id.id)], context=context) + if sale_ids: + sale_line_ids = sale_line_obj.search(cr, uid, [('order_id', 'in', sale_ids), ('product_id.type', '=', 'service'), ('invoiced', '=', False)], context=context) + if sale_line_ids: + created_lines = sale_line_obj.invoice_line_create(cr, uid, sale_line_ids, context=context) + invoice_line_obj.write(cr, uid, created_lines, {'invoice_id': invoice_id}, context=context) + return invoice_id diff --git a/addons/sale_stock/sale_stock_demo.xml b/addons/sale_stock/sale_stock_demo.xml index 42c09b7e9f0..9359e0a7875 100644 --- a/addons/sale_stock/sale_stock_demo.xml +++ b/addons/sale_stock/sale_stock_demo.xml @@ -38,26 +38,6 @@ - - make_to_order - - - - make_to_order - - - - make_to_order - - - - make_to_order - - - - produce - - diff --git a/addons/sale_stock/sale_stock_view.xml b/addons/sale_stock/sale_stock_view.xml index a926a16dc14..130bcef5ed7 100644 --- a/addons/sale_stock/sale_stock_view.xml +++ b/addons/sale_stock/sale_stock_view.xml @@ -15,7 +15,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {'default_groups_ref': ['base.group_user', 'base.group_sale_manager', 'stock.group_stock_manager']} - -
- - - - product.product.standard.price.form.inherit - product.product - - - - - - - - - product.normal.stock.acc.property.form.inherit - product.product - - 26 - - - - - - - - - - - - - - - - - - Receptions stock.move ir.actions.act_window form tree,form - [('picking_id.type','=','in')] +

- Click to register a reception for this product. + Click to register a reception for this product.

Here you will find the history of all receptions related to this product, as well as all future receptions you are waiting @@ -210,8 +95,8 @@ ir.actions.act_window form tree,form - [('picking_id.type','=','out')] +

diff --git a/addons/stock/report/__init__.py b/addons/stock/report/__init__.py index e1e083c2a8d..7f3669174db 100644 --- a/addons/stock/report/__init__.py +++ b/addons/stock/report/__init__.py @@ -20,12 +20,7 @@ ############################################################################## import product_stock -import picking -import lot_overview_all import report_stock -import report_stock_move -import stock_inventory_move_report -import lot_overview # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/stock/report/lot_move_label.xml b/addons/stock/report/lot_move_label.xml deleted file mode 100644 index 62f26c0a800..00000000000 --- a/addons/stock/report/lot_move_label.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/addons/stock/report/lot_move_label.xsl b/addons/stock/report/lot_move_label.xsl deleted file mode 100644 index 57b29e69405..00000000000 --- a/addons/stock/report/lot_move_label.xsl +++ /dev/null @@ -1,63 +0,0 @@ - - - 24.5 - 1 - 3.8 - 7 - 3.5cm - 6.5cm - 3 - 21 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cm - - - - cm - - - - - - - , - - Serial: - Tracking: - - - - - diff --git a/addons/stock/report/lot_overview.py b/addons/stock/report/lot_overview.py deleted file mode 100644 index c8e80ac54b9..00000000000 --- a/addons/stock/report/lot_overview.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2010 Tiny SPRL (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## -import time -from openerp.report import report_sxw - -class lot_overview(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(lot_overview, self).__init__(cr, uid, name, context=context) - self.price_total = 0.0 - self.grand_total = 0.0 - self.localcontext.update({ - 'time': time, - 'process':self.process, - 'price_total': self._price_total, - 'grand_total_price':self._grand_total, - }) - - def process(self, location_id): - location_obj = self.pool['stock.location'] - data = location_obj._product_get_report(self.cr,self.uid, [location_id]) - - data['location_name'] = location_obj.read(self.cr, self.uid, [location_id],['complete_name'])[0]['complete_name'] - self.price_total = 0.0 - self.price_total += data['total_price'] - self.grand_total += data['total_price'] - return [data] - - def _price_total(self): - return self.price_total - - def _grand_total(self): - return self.grand_total - -report_sxw.report_sxw('report.lot.stock.overview', 'stock.location', 'addons/stock/report/lot_overview.rml', parser=lot_overview,header='internal') - - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: - diff --git a/addons/stock/report/lot_overview.rml b/addons/stock/report/lot_overview.rml deleted file mode 100644 index 82c402a3fdf..00000000000 --- a/addons/stock/report/lot_overview.rml +++ /dev/null @@ -1,227 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

- - - - - - - - - - - - Location Inventory Overview - - - - - - - - - - - - -
- [[ repeatIn(objects,'o') ]] -
- [[ repeatIn(process(o.id),'ob') ]] - -
- - - - - - -
- [[ repeatIn(ob['product'],'p') ]] - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/addons/stock/report/lot_overview_all.py b/addons/stock/report/lot_overview_all.py deleted file mode 100644 index aba97fa6e1e..00000000000 --- a/addons/stock/report/lot_overview_all.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2010 Tiny SPRL (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## -import time -from openerp.report import report_sxw - -class lot_overview_all(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(lot_overview_all, self).__init__(cr, uid, name, context=context) - self.price_total = 0.0 - self.grand_total = 0.0 - self.localcontext.update({ - 'time': time, - 'process':self.process, - 'price_total': self._price_total, - 'grand_total_price':self._grand_total, - }) - - def process(self, location_id): - location_obj = self.pool['stock.location'] - data = location_obj._product_get_all_report(self.cr,self.uid, [location_id]) - data['location_name'] = location_obj.read(self.cr, self.uid, [location_id],['complete_name'])[0]['complete_name'] - self.price_total = 0.0 - self.price_total += data['total_price'] - self.grand_total += data['total_price'] - return [data] - - def _price_total(self): - return self.price_total - - def _grand_total(self): - return self.grand_total - -report_sxw.report_sxw('report.lot.stock.overview_all', 'stock.location', 'addons/stock/report/lot_overview_all.rml', parser=lot_overview_all,header='internal') - - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: - diff --git a/addons/stock/report/lot_overview_all.rml b/addons/stock/report/lot_overview_all.rml deleted file mode 100644 index 51b93c6323b..00000000000 --- a/addons/stock/report/lot_overview_all.rml +++ /dev/null @@ -1,227 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Location Content - - - - - - - - - - - - -
- [[ repeatIn(objects,'o') ]] -
- [[ repeatIn(process(o.id),'ob') ]] - -
- - - - - - -
- [[ repeatIn(ob['product'],'p') ]] - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/addons/stock/report/picking.rml b/addons/stock/report/picking.rml deleted file mode 100644 index 381b7eb4c28..00000000000 --- a/addons/stock/report/picking.rml +++ /dev/null @@ -1,306 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [[repeatIn(objects,'picking')]] - [[picking.type == 'out' and picking.partner_id and setLang(picking.partner_id.lang) or '']] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- [[ repeatIn([line for line in picking.move_lines if ((line.state == 'confirmed' or line.state=='done' or line.state=='assigned') and not line.scrapped)],'move_lines') ]] - [[ (picking.move_lines!=[] and removeParentNode('para')) or removeParentNode('section')]] - -
- - - - - - - - - [[ ([line for line in picking.move_lines if (line.state == 'draft' or line.state=='waiting' )]) and 'Non Assigned Products:' or removeParentNode('para') ]] - -
- [[ repeatIn([line for line in picking.move_lines if (line.state == 'draft' or line.state=='waiting')],'move_lines') ]] - [[ (picking.move_lines!=[] and removeParentNode('para')) or removeParentNode('section')]] - -
- - - - - - - - - - - - - - diff --git a/addons/stock/report/product_stock.py b/addons/stock/report/product_stock.py index d213db673dc..8122e60e4b2 100644 --- a/addons/stock/report/product_stock.py +++ b/addons/stock/report/product_stock.py @@ -64,11 +64,13 @@ class report_stock(report_int): for name in names: names[name] = names[name].encode('utf8') products = {} - prods = registry['stock.location']._product_all_get(cr, uid, location_id, product_ids) + ctx = context.copy() + ctx['location_id'] = loc_ids + prods = registry['product.product']._product_available(cr, uid, product_ids, context=ctx) + for prod in prods.keys(): + products[prod] = [(now, prods[prod]['qty_available'])] + prods[prod] = 0 - for p in prods: - products[p] = [(now,prods[p])] - prods[p] = 0 if not loc_ids or not product_ids: return (False, 'pdf') diff --git a/addons/stock/report/report_stock.py b/addons/stock/report/report_stock.py index d4bbb3ab127..476333d1857 100644 --- a/addons/stock/report/report_stock.py +++ b/addons/stock/report/report_stock.py @@ -20,129 +20,21 @@ ############################################################################## from openerp.osv import fields, osv -from openerp.tools.translate import _ -from openerp import tools from openerp.tools.sql import drop_view_if_exists -class stock_report_prodlots(osv.osv): - _name = "stock.report.prodlots" - _description = "Stock report by serial number" - _auto = False - _columns = { - 'qty': fields.float('Quantity', readonly=True), - 'location_id': fields.many2one('stock.location', 'Location', readonly=True, select=True), - 'product_id': fields.many2one('product.product', 'Product', readonly=True, select=True), - 'prodlot_id': fields.many2one('stock.production.lot', 'Serial Number', readonly=True, select=True), - } - - def init(self, cr): - drop_view_if_exists(cr, 'stock_report_prodlots') - cr.execute(""" - create or replace view stock_report_prodlots as ( - select max(id) as id, - location_id, - product_id, - prodlot_id, - sum(qty) as qty - from ( - select -max(sm.id) as id, - sm.location_id, - sm.product_id, - sm.prodlot_id, - -sum(sm.product_qty /uo.factor) as qty - from stock_move as sm - left join stock_location sl - on (sl.id = sm.location_id) - left join product_uom uo - on (uo.id=sm.product_uom) - where state = 'done' - group by sm.location_id, sm.product_id, sm.product_uom, sm.prodlot_id - union all - select max(sm.id) as id, - sm.location_dest_id as location_id, - sm.product_id, - sm.prodlot_id, - sum(sm.product_qty /uo.factor) as qty - from stock_move as sm - left join stock_location sl - on (sl.id = sm.location_dest_id) - left join product_uom uo - on (uo.id=sm.product_uom) - where sm.state = 'done' - group by sm.location_dest_id, sm.product_id, sm.product_uom, sm.prodlot_id - ) as report - group by location_id, product_id, prodlot_id - )""") - - def unlink(self, cr, uid, ids, context=None): - raise osv.except_osv(_('Error!'), _('You cannot delete any record!')) - - -class stock_report_tracklots(osv.osv): - _name = "stock.report.tracklots" - _description = "Stock report by logistic serial number" - _auto = False - _columns = { - 'name': fields.float('Quantity', readonly=True), - 'location_id': fields.many2one('stock.location', 'Location', readonly=True, select=True), - 'product_id': fields.many2one('product.product', 'Product', readonly=True, select=True), - 'tracking_id': fields.many2one('stock.tracking', 'Logistic Serial Number', readonly=True, select=True), - } - - def init(self, cr): - drop_view_if_exists(cr, 'stock_report_tracklots') - cr.execute(""" - create or replace view stock_report_tracklots as ( - - select max(id) as id, - location_id, - product_id, - tracking_id, - sum(qty) as name - from ( - select -max(sm.id) as id, - sm.location_id, - sm.product_id, - sm.tracking_id, - -sum(sm.product_qty /uo.factor) as qty - from stock_move as sm - left join stock_location sl - on (sl.id = sm.location_id) - left join product_uom uo - on (uo.id=sm.product_uom) - where state = 'done' - group by sm.location_id, sm.product_id, sm.product_uom, sm.tracking_id - union all - select max(sm.id) as id, - sm.location_dest_id as location_id, - sm.product_id, - sm.tracking_id, - sum(sm.product_qty /uo.factor) as qty - from stock_move as sm - left join stock_location sl - on (sl.id = sm.location_dest_id) - left join product_uom uo - on (uo.id=sm.product_uom) - where sm.state = 'done' - group by sm.location_dest_id, sm.product_id, sm.product_uom, sm.tracking_id - ) as report - group by location_id, product_id, tracking_id - )""") - - def unlink(self, cr, uid, ids, context=None): - raise osv.except_osv(_('Error!'), _('You cannot delete any record!')) - - class report_stock_lines_date(osv.osv): _name = "report.stock.lines.date" - _description = "Dates of Inventories" + _description = "Dates of Inventories and latest Moves" _auto = False _order = "date" _columns = { - 'id': fields.integer('Inventory Line Id', readonly=True), + 'id': fields.integer('Product Id', readonly=True), 'product_id': fields.many2one('product.product', 'Product', readonly=True, select=True), - 'date': fields.datetime('Latest Inventory Date'), + 'date': fields.datetime('Date of latest Inventory', readonly=True), + 'move_date': fields.datetime('Date of latest Stock Move', readonly=True), + "active": fields.boolean("Active", readonly=True), } + def init(self, cr): drop_view_if_exists(cr, 'report_stock_lines_date') cr.execute(""" @@ -150,13 +42,16 @@ class report_stock_lines_date(osv.osv): select p.id as id, p.id as product_id, - max(s.date) as date + max(s.date) as date, + max(m.date) as move_date, + p.active as active from product_product p - left outer join stock_inventory_line l on (p.id=l.product_id) - left join stock_inventory s on (l.inventory_id=s.id) - and s.state = 'done' - where p.active='true' + left join ( + stock_inventory_line l + inner join stock_inventory s on (l.inventory_id=s.id and s.state = 'done') + ) on (p.id=l.product_id) + left join stock_move m on (m.product_id=p.id and m.state = 'done') group by p.id )""") diff --git a/addons/stock/report/report_stock_move.py b/addons/stock/report/report_stock_move.py deleted file mode 100644 index 1b183f5fcbd..00000000000 --- a/addons/stock/report/report_stock_move.py +++ /dev/null @@ -1,198 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2010 Tiny SPRL (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## - -from openerp import tools -from openerp.osv import fields,osv -from openerp.addons.decimal_precision import decimal_precision as dp - - -class report_stock_move(osv.osv): - _name = "report.stock.move" - _description = "Moves Statistics" - _auto = False - _columns = { - 'date': fields.date('Date', readonly=True), - 'partner_id':fields.many2one('res.partner', 'Partner', readonly=True), - 'product_id':fields.many2one('product.product', 'Product', readonly=True), - 'company_id':fields.many2one('res.company', 'Company', readonly=True), - 'picking_id':fields.many2one('stock.picking', 'Shipment', readonly=True), - 'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal'), ('other', 'Others')], 'Shipping Type', required=True, select=True, help="Shipping type specify, goods coming in or going out."), - 'location_id': fields.many2one('stock.location', 'Source Location', readonly=True, select=True, help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations."), - 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', readonly=True, select=True, help="Location where the system will stock the finished products."), - 'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Cancelled')], 'Status', readonly=True, select=True), - 'product_qty':fields.integer('Quantity',readonly=True), - 'categ_id': fields.many2one('product.category', 'Product Category', ), - 'product_qty_in':fields.integer('In Qty',readonly=True), - 'product_qty_out':fields.integer('Out Qty',readonly=True), - 'value' : fields.float('Total Value', required=True), - 'day_diff2':fields.float('Lag (Days)',readonly=True, digits_compute=dp.get_precision('Shipping Delay'), group_operator="avg"), - 'day_diff1':fields.float('Planned Lead Time (Days)',readonly=True, digits_compute=dp.get_precision('Shipping Delay'), group_operator="avg"), - 'day_diff':fields.float('Execution Lead Time (Days)',readonly=True, digits_compute=dp.get_precision('Shipping Delay'), group_operator="avg"), - 'stock_journal': fields.many2one('stock.journal','Stock Journal', select=True), - - - } - - def init(self, cr): - tools.drop_view_if_exists(cr, 'report_stock_move') - cr.execute(""" - CREATE OR REPLACE view report_stock_move AS ( - SELECT - min(sm.id) as id, - date_trunc('day', sm.date) as date, - avg(date(sm.date)-date(sm.create_date)) as day_diff, - avg(date(sm.date_expected)-date(sm.create_date)) as day_diff1, - avg(date(sm.date)-date(sm.date_expected)) as day_diff2, - sm.location_id as location_id, - sm.picking_id as picking_id, - sm.company_id as company_id, - sm.location_dest_id as location_dest_id, - sum(sm.product_qty) as product_qty, - sum( - (CASE WHEN sp.type in ('out') THEN - (sm.product_qty * pu.factor / pu2.factor) - ELSE 0.0 - END) - ) as product_qty_out, - sum( - (CASE WHEN sp.type in ('in') THEN - (sm.product_qty * pu.factor / pu2.factor) - ELSE 0.0 - END) - ) as product_qty_in, - sm.partner_id as partner_id, - sm.product_id as product_id, - sm.state as state, - sm.product_uom as product_uom, - pt.categ_id as categ_id , - coalesce(sp.type, 'other') as type, - sp.stock_journal_id AS stock_journal, - sum( - (CASE WHEN sp.type in ('in') THEN - (sm.product_qty * pu.factor / pu2.factor) * pt.standard_price - ELSE 0.0 - END) - - - (CASE WHEN sp.type in ('out') THEN - (sm.product_qty * pu.factor / pu2.factor) * pt.standard_price - ELSE 0.0 - END) - ) as value - FROM - stock_move sm - LEFT JOIN stock_picking sp ON (sm.picking_id=sp.id) - LEFT JOIN product_product pp ON (sm.product_id=pp.id) - LEFT JOIN product_uom pu ON (sm.product_uom=pu.id) - LEFT JOIN product_uom pu2 ON (sm.product_uom=pu2.id) - LEFT JOIN product_template pt ON (pp.product_tmpl_id=pt.id) - GROUP BY - coalesce(sp.type, 'other'), date_trunc('day', sm.date), sm.partner_id, - sm.state, sm.product_uom, sm.date_expected, - sm.product_id, pt.standard_price, sm.picking_id, - sm.company_id, sm.location_id, sm.location_dest_id, pu.factor, pt.categ_id, sp.stock_journal_id - ) - """) - - - -class report_stock_inventory(osv.osv): - _name = "report.stock.inventory" - _description = "Stock Statistics" - _auto = False - _columns = { - 'date': fields.datetime('Date', readonly=True), - 'year': fields.char('Year', size=4, readonly=True), - 'month':fields.selection([('01','January'), ('02','February'), ('03','March'), ('04','April'), - ('05','May'), ('06','June'), ('07','July'), ('08','August'), ('09','September'), - ('10','October'), ('11','November'), ('12','December')], 'Month', readonly=True), - 'partner_id':fields.many2one('res.partner', 'Partner', readonly=True), - 'product_id':fields.many2one('product.product', 'Product', readonly=True), - 'product_categ_id':fields.many2one('product.category', 'Product Category', readonly=True), - 'location_id': fields.many2one('stock.location', 'Location', readonly=True), - 'prodlot_id': fields.many2one('stock.production.lot', 'Lot', readonly=True), - 'company_id': fields.many2one('res.company', 'Company', readonly=True), - 'product_qty':fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), readonly=True), - 'value' : fields.float('Total Value', digits_compute=dp.get_precision('Account'), required=True), - 'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Cancelled')], 'Status', readonly=True, select=True, - help='When the stock move is created it is in the \'Draft\' state.\n After that it is set to \'Confirmed\' state.\n If stock is available state is set to \'Avaiable\'.\n When the picking it done the state is \'Done\'.\ - \nThe state is \'Waiting\' if the move is waiting for another one.'), - 'location_type': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location for Inter-Companies Transfers')], 'Location Type', required=True), - 'scrap_location': fields.boolean('scrap'), - } - def init(self, cr): - tools.drop_view_if_exists(cr, 'report_stock_inventory') - cr.execute(""" -CREATE OR REPLACE view report_stock_inventory AS ( - (SELECT - min(m.id) as id, m.date as date, - to_char(m.date, 'YYYY') as year, - to_char(m.date, 'MM') as month, - m.partner_id as partner_id, m.location_id as location_id, - m.product_id as product_id, pt.categ_id as product_categ_id, l.usage as location_type, l.scrap_location as scrap_location, - m.company_id, - m.state as state, m.prodlot_id as prodlot_id, - - coalesce(sum(-pt.standard_price * m.product_qty * pu.factor / pu2.factor)::decimal, 0.0) as value, - coalesce(sum(-m.product_qty * pu.factor / pu2.factor)::decimal, 0.0) as product_qty - FROM - stock_move m - LEFT JOIN stock_picking p ON (m.picking_id=p.id) - LEFT JOIN product_product pp ON (m.product_id=pp.id) - LEFT JOIN product_template pt ON (pp.product_tmpl_id=pt.id) - LEFT JOIN product_uom pu ON (pt.uom_id=pu.id) - LEFT JOIN product_uom pu2 ON (m.product_uom=pu2.id) - LEFT JOIN product_uom u ON (m.product_uom=u.id) - LEFT JOIN stock_location l ON (m.location_id=l.id) - WHERE m.state != 'cancel' - GROUP BY - m.id, m.product_id, m.product_uom, pt.categ_id, m.partner_id, m.location_id, m.location_dest_id, - m.prodlot_id, m.date, m.state, l.usage, l.scrap_location, m.company_id, pt.uom_id, to_char(m.date, 'YYYY'), to_char(m.date, 'MM') -) UNION ALL ( - SELECT - -m.id as id, m.date as date, - to_char(m.date, 'YYYY') as year, - to_char(m.date, 'MM') as month, - m.partner_id as partner_id, m.location_dest_id as location_id, - m.product_id as product_id, pt.categ_id as product_categ_id, l.usage as location_type, l.scrap_location as scrap_location, - m.company_id, - m.state as state, m.prodlot_id as prodlot_id, - coalesce(sum(pt.standard_price * m.product_qty * pu.factor / pu2.factor)::decimal, 0.0) as value, - coalesce(sum(m.product_qty * pu.factor / pu2.factor)::decimal, 0.0) as product_qty - FROM - stock_move m - LEFT JOIN stock_picking p ON (m.picking_id=p.id) - LEFT JOIN product_product pp ON (m.product_id=pp.id) - LEFT JOIN product_template pt ON (pp.product_tmpl_id=pt.id) - LEFT JOIN product_uom pu ON (pt.uom_id=pu.id) - LEFT JOIN product_uom pu2 ON (m.product_uom=pu2.id) - LEFT JOIN product_uom u ON (m.product_uom=u.id) - LEFT JOIN stock_location l ON (m.location_dest_id=l.id) - WHERE m.state != 'cancel' - GROUP BY - m.id, m.product_id, m.product_uom, pt.categ_id, m.partner_id, m.location_id, m.location_dest_id, - m.prodlot_id, m.date, m.state, l.usage, l.scrap_location, m.company_id, pt.uom_id, to_char(m.date, 'YYYY'), to_char(m.date, 'MM') - ) -); - """) - - - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/stock/report/report_stock_move_view.xml b/addons/stock/report/report_stock_move_view.xml deleted file mode 100644 index 452cfd1b3e6..00000000000 --- a/addons/stock/report/report_stock_move_view.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - - report.stock.move.graph - report.stock.move - - - - - - - - - - - - - report.stock.move.search - report.stock.move - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Moves Analysis - report.stock.move - form - graph - - - {'contact_display': 'partner','search_default_done':1,'search_default_year':1, 'search_default_month':1, 'search_default_group_type':1, 'group_by': [], 'group_by_no_leaf':1,} - Moves Analysis allows you to easily check and analyse your company stock moves. Use this report when you want to analyse the different routes taken by your products and inventory management performance. - - - - - report.stock.inventory.graph - report.stock.inventory - - - - - - - - - - - report.stock.inventory.search - report.stock.inventory - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Inventory Analysis - report.stock.inventory - form - graph - - {'contact_display': 'partner', 'search_default_real':1, -'search_default_year':1,'search_default_month':1, 'search_default_location_type_internal':1,'search_default_group_product':1,'group_by':[], 'group_by_no_leaf':1} - Inventory Analysis allows you to easily check and analyse your company stock levels. Sort and group by selection criteria in order to better analyse and manage your company activities. - - - - - - diff --git a/addons/stock/report/report_stock_view.xml b/addons/stock/report/report_stock_view.xml index e8bb6621355..e770fd871b1 100644 --- a/addons/stock/report/report_stock_view.xml +++ b/addons/stock/report/report_stock_view.xml @@ -2,12 +2,6 @@ - - report.stock.lines.date.tree @@ -16,6 +10,7 @@ + @@ -24,12 +19,13 @@ report.stock.lines.date.search report.stock.lines.date - + - + + @@ -39,36 +35,26 @@ report.stock.lines.date.form report.stock.lines.date -
+ +
- Last Product Inventories + Latest Inventories & Moves report.stock.lines.date form {'search_default_stockable':1} tree,form - Display the last inventories done on your products and easily sort them with specific filtering criteria. If you do frequent and partial inventories, you need this report in order to ensure that the stock of each product is controlled at least once a year. + Display the latest Inventories and Moves done on your products and easily sort them with specific filtering criteria. If you do frequent and partial inventories, you need this report in order to ensure that the stock of each product is controlled at least once a year. This also lets you find out which products have seen little move lately and may deserve special measures (discounted sale, quality control...) - - stock.location.graph - stock.location - - - - - - - -
diff --git a/addons/stock/report/stock_by_location.py b/addons/stock/report/stock_by_location.py deleted file mode 100644 index 153b92f077c..00000000000 --- a/addons/stock/report/stock_by_location.py +++ /dev/null @@ -1,85 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2010 Tiny SPRL (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## - -import openerp -from openerp.report.interface import report_rml -from openerp.report.interface import toxml - -#FIXME: we should use toxml - -class report_custom(report_rml): - def create_xml(self, cr, uid, ids, datas, context=None): - config = """ - - 09/09/2005 - 210.00mm,297.00mm - 595.27 - 841.88 - 60.00mm,60.00mm,60.00mm - Stock by location - Generated by OpenERP - - """ - header = """ -
- Location - Product name - Product quantity -
- """ - - def process(location_id, level): - registry = openerp.registry(cr.dbname) - xml = '' - location_name = registry['stock.location'].read(cr, uid, [location_id], ['name']) - xml += "
" - xml += location_name[0]['name'] + '' - - prod_info = registry['stock.location']._product_get(cr, uid, location_id) - xml += "" - for prod_id in prod_info.keys(): - if prod_info[prod_id] != 0.0: - prod_name = registry['product.product'].read(cr, uid, [prod_id], ['name']) - xml += prod_name[0]['name'] + '\n' - xml += '' - - xml += "" - for prod_id in prod_info.keys(): - if prod_info[prod_id] != 0.0: - xml += str(prod_info[prod_id]) + '\n' - xml += '' - - location_child = registry['stock.location'].read(cr, uid, [location_id], ['child_ids']) - for child_id in location_child[0]['child_ids']: - xml += process(child_id, level+1) - return xml - - for location_id in ids: - xml = '' + process(location_id, 0) + '' - - xml = '' ''+ config + header + xml + '' - - return self.post_process_xml_data(cr, uid, xml, context) - -report_custom('report.stock.lot.location', 'stock.location', '', 'addons/stock/report/stock_by_location.xsl') - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: - diff --git a/addons/stock/report/stock_by_location.xsl b/addons/stock/report/stock_by_location.xsl deleted file mode 100644 index bb70b0b5643..00000000000 --- a/addons/stock/report/stock_by_location.xsl +++ /dev/null @@ -1,109 +0,0 @@ - - - - - - a4_normal - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/addons/stock/report/stock_inventory_move.rml b/addons/stock/report/stock_inventory_move.rml deleted file mode 100644 index 032212a38a3..00000000000 --- a/addons/stock/report/stock_inventory_move.rml +++ /dev/null @@ -1,218 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [[ repeatIn(objects,'o') ]] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- [[ repeatIn(o.inventory_line_id, 'p') ]] - -
- - - - - - - - - - - - - - - - - - - - - - diff --git a/addons/stock/report/stock_inventory_move_report.py b/addons/stock/report/stock_inventory_move_report.py deleted file mode 100644 index 21a7c458ecc..00000000000 --- a/addons/stock/report/stock_inventory_move_report.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2010 Tiny SPRL (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## - -import time -from openerp.report import report_sxw - -class stock_inventory_move(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(stock_inventory_move, self).__init__(cr, uid, name, context=context) - self.localcontext.update({ - 'time': time, - 'qty_total':self._qty_total - }) - - def _qty_total(self, objects): - total = 0.0 - uom = objects[0].product_uom.name - for obj in objects: - total += obj.product_qty - return {'quantity':total,'uom':uom} - -report_sxw.report_sxw( - 'report.stock.inventory.move', - 'stock.inventory', - 'addons/stock/report/stock_inventory_move.rml', - parser=stock_inventory_move, - header='internal' -) -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/stock/res_config.py b/addons/stock/res_config.py index 453f86bc607..73a3db67608 100644 --- a/addons/stock/res_config.py +++ b/addons/stock/res_config.py @@ -20,19 +20,57 @@ ############################################################################## from openerp.osv import fields, osv +from openerp.tools.translate import _ + +class res_company(osv.osv): + _inherit = "res.company" + _columns = { + 'propagation_minimum_delta': fields.integer('Minimum Delta for Propagation of a Date Change on moves linked together'), + 'internal_transit_location_id': fields.many2one('stock.location', 'Internal Transit Location', help="Technical field used for resupply routes between warehouses that belong to this company", on_delete="restrict"), + } + + def create_transit_location(self, cr, uid, company_id, company_name, context=None): + '''Create a transit location with company_id being the given company_id. This is needed + in case of resuply routes between warehouses belonging to the same company, because + we don't want to create accounting entries at that time. + ''' + data_obj = self.pool.get('ir.model.data') + try: + parent_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1] + except: + parent_loc = False + location_vals = { + 'name': _('%s: Transit Location') % company_name, + 'usage': 'transit', + 'company_id': company_id, + 'location_id': parent_loc, + } + location_id = self.pool.get('stock.location').create(cr, uid, location_vals, context=context) + self.write(cr, uid, [company_id], {'internal_transit_location_id': location_id}, context=context) + + def create(self, cr, uid, vals, context=None): + company_id = super(res_company, self).create(cr, uid, vals, context=context) + self.create_transit_location(cr, uid, company_id, vals['name'], context=context) + return company_id + + _defaults = { + 'propagation_minimum_delta': 1, + } class stock_config_settings(osv.osv_memory): _name = 'stock.config.settings' _inherit = 'res.config.settings' _columns = { + 'company_id': fields.many2one('res.company', 'Company', required=True), + 'module_procurement_jit': fields.boolean("Generate procurement in real time", + help="""This allows Just In Time computation of procurement orders. + All procurement orders will be processed immediately, which could in some + cases entail a small performance impact. + This installs the module procurement_jit."""), 'module_claim_from_delivery': fields.boolean("Allow claim on deliveries", help='Adds a Claim link to the delivery order.\n' '-This installs the module claim_from_delivery.'), - 'module_stock_invoice_directly': fields.boolean("Create and open the invoice when the user finish a delivery order", - help='This allows to automatically launch the invoicing wizard if the delivery is ' - 'to be invoiced when you send or deliver goods.\n' - '-This installs the module stock_invoice_directly.'), 'module_product_expiry': fields.boolean("Expiry date on serial numbers", help="""Track different dates on products and serial numbers. The following dates can be tracked: @@ -41,11 +79,6 @@ The following dates can be tracked: - removal date - alert date. This installs the module product_expiry."""), - 'module_stock_location': fields.boolean("Create push/pull logistic rules", - help='Provide push and pull inventory flows. Typical uses of this feature are: ' - 'manage product manufacturing chains, manage default locations per product, ' - 'define routes within your warehouse according to business needs, etc.\n' - '-This installs the module stock_location.'), 'group_uom': fields.boolean("Manage different units of measure for products", implied_group='product.group_uom', help="""Allows you to select and maintain different units of measure for products."""), @@ -56,22 +89,38 @@ This installs the module product_expiry."""), 'group_stock_packaging': fields.boolean("Allow to define several packaging methods on products", implied_group='product.group_stock_packaging', help="""Allows you to create and manage your packaging dimensions and types you want to be maintained in your system."""), - 'group_stock_production_lot': fields.boolean("Track serial number on products", + 'group_stock_production_lot': fields.boolean("Track lots or serial numbers", implied_group='stock.group_production_lot', - help="""This allows you to manage products by using serial numbers. When you select a serial number on product moves, you can get the upstream or downstream traceability of that product."""), - 'group_stock_tracking_lot': fields.boolean("Track serial number on logistic units (pallets)", + help="""This allows you to assign a lot (or serial number) to the pickings and moves. This can make it possible to know which production lot was sent to a certain client, ..."""), + 'group_stock_tracking_lot': fields.boolean("Use packages: pallets, boxes, ...", implied_group='stock.group_tracking_lot', - help="""When you select a serial number on product moves, you can get the upstream or downstream traceability of that product."""), - 'group_stock_inventory_valuation': fields.boolean("Generate accounting entries per stock movement", - implied_group='stock.group_inventory_valuation', - help="""Allows to configure inventory valuations on products and product categories."""), + help="""This allows you to manage products by using serial numbers. When you select a serial number on product moves, you can get the traceability of that product."""), + 'group_stock_tracking_owner': fields.boolean("Manage owner on stock", + implied_group='stock.group_tracking_owner', + help="""This way you can receive products attributed to a certain owner. """), 'group_stock_multiple_locations': fields.boolean("Manage multiple locations and warehouses", implied_group='stock.group_locations', - help='This allows to configure and use multiple stock locations and warehouses, ' - 'instead of having a single default one.'), + help="""This will show you the locations and allows you to define multiple picking types and warehouses."""), + 'group_stock_adv_location': fields.boolean("Manage advanced routes for your warehouse", + implied_group='stock.group_adv_location', + help="""This option supplements the warehouse application by effectively implementing Push and Pull inventory flows through Routes."""), 'decimal_precision': fields.integer('Decimal precision on weight', help="As an example, a decimal precision of 2 will allow weights like: 9.99 kg, whereas a decimal precision of 4 will allow weights like: 0.0231 kg."), + 'propagation_minimum_delta': fields.related('company_id', 'propagation_minimum_delta', type='integer', string="Minimum days to trigger a propagation of date change in pushed/pull flows."), + 'module_stock_dropshipping': fields.boolean("Manage dropshipping", + help='\nCreates the dropship route and add more complex tests' + '-This installs the module stock_dropshipping.'), + 'module_stock_picking_wave': fields.boolean('Manage picking wave', help='Install the picking wave module which will help you grouping your pickings and processing them in batch'), } + def onchange_adv_location(self, cr, uid, ids, group_stock_adv_location, context=None): + if group_stock_adv_location: + return {'value': {'group_stock_multiple_locations': True}} + return {} + + def _default_company(self, cr, uid, context=None): + user = self.pool.get('res.users').browse(cr, uid, uid, context=context) + return user.company_id.id + def get_default_dp(self, cr, uid, fields, context=None): dp = self.pool.get('ir.model.data').get_object(cr, uid, 'product', 'decimal_stock_weight') return {'decimal_precision': dp.digits} @@ -81,4 +130,8 @@ This installs the module product_expiry."""), dp = self.pool.get('ir.model.data').get_object(cr, uid, 'product', 'decimal_stock_weight') dp.write({'digits': config.decimal_precision}) + _defaults = { + 'company_id': _default_company, + } + # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/stock/res_config_view.xml b/addons/stock/res_config_view.xml index 133e6ffa875..140ab36c774 100644 --- a/addons/stock/res_config_view.xml +++ b/addons/stock/res_config_view.xml @@ -23,7 +23,7 @@ + + + + + + + + + + +
+
+
+

+

+
+ + + + +
+
+
+ +
+
+
+

+ + +

+
+
+

+
+ + + + +
+

+
+
+

+ + +

+
+
+
+ +
+
Supplier Date Ordered Order Reference DateReference
- Location / Product - - Variants - - Quantity - - Unit Price - - Value -
- Location / Product - - Variants - - Quantity - - Unit Price - - Value -
- [[ (not ob['product']) and removeParentNode('blockTable') ]] [[ ob['location_name'] ]] - - - - - - - - - - - - -
- - - - - [ [[ p['code'] ]] ] [[ p['prod_name'] ]] - - [[ p['variants'] ]] - - [[formatLang( p['prod_qty']) ]] [[ p['uom'] ]] - - [[ formatLang(p['price'], dp='Account') ]] - - [[ formatLang(p['price_value'], dp='Account', currency_obj = o.company_id.currency_id)]] -
- [[ (not ob['product']) and removeParentNode('blockTable') ]] - - Total: - - [[ formatLang(price_total(), dp='Account', currency_obj = o.company_id.currency_id) ]] -
- Grand Total: - - - - - - [[ formatLang(grand_total_price(), dp='Account', currency_obj = o.company_id.currency_id) ]] -
- Location / Product - - Variants - - Quantity - - Unit Price - - Value -
- Location / Product - - Variants - - Quantity - - Unit Price - - Value -
- [[ (not ob['product']) and removeParentNode('blockTable') ]][[ ob['location_name'] ]] - - - - - - - - - - - - -
- - - - - [ [[ p['code'] ]] ] [[ p['prod_name'] ]] - - [[ p['variants'] ]] - - [[formatLang( p['prod_qty']) ]] [[ p['uom'] ]] - - [[ formatLang(p['price'], dp='Account') ]] - - [[ formatLang(p['price_value'], dp='Account', currency_obj = o.company_id.currency_id)]] -
- [[ (not ob['product']) and removeParentNode('blockTable') ]] - - Total: - - [[ formatLang(price_total(), dp='Account', currency_obj = o.company_id.currency_id) ]] -
- Grand Total: - - - - - - [[ formatLang(grand_total_price(), dp='Account', currency_obj = o.company_id.currency_id) ]] -
- Description - - Lot - - Status - - Location - - Quantity -
- Supplier Address : [[ (picking.type == 'in' or removeParentNode('para')) and '' ]] - Customer Address : [[ (picking.type == 'out' or removeParentNode('para')) and '' ]] - Warehouse Address : [[ (picking.type == 'internal' or removeParentNode('para')) and '' ]] - [[ (picking.partner_id and picking.partner_id.id and picking.partner_id.title.name) or '' ]] [[ picking.partner_id and picking.partner_id.id and picking.partner_id.name ]] - [[ picking.partner_id and display_address(picking.partner_id) ]] - [[ picking.partner_id.phone or picking.partner_id.email or removeParentNode('para')]] - - Contact Address : - [[ picking.partner_id and picking.partner_id.title.name or '' ]] [[ picking.partner_id and picking.partner_id.name or '' ]] - [[ picking.partner_id and display_address(picking.partner_id) ]] - [[ picking.partner_id.phone or picking.partner_id.email or removeParentNode('para')]] -
- Delivery Order : [[ (picking.type == 'out' or removeParentNode('para')) and '' ]] [[ picking.name ]] - Incoming Shipment : [[ (picking.type == 'in' or removeParentNode('para')) and '' ]] [[ picking.name ]] - Internal Shipment : [[ (picking.type == 'internal' or removeParentNode('para')) and '' ]] [[ picking.name ]] -
- Journal - - Order(Origin) - - Schedule Date - - Weight -
- [[ picking.stock_journal_id.name]] - - [[ picking.origin or '']] - - [[ formatLang(picking.min_date,date_time = True) ]] - - [[ 'weight' in picking._columns.keys() and picking.weight or '']] -
- Description - - Serial Number - - Status - - Location - - Quantity -
- [[ get_product_desc(move_lines) ]] - - [[ (move_lines.prodlot_id and move_lines.prodlot_id.name) or '' ]] - - Waiting Availability[[ move_lines.state == 'confirmed' and ' ' or removeParentNode('para') ]] - Done[[ move_lines.state == 'done' and ' ' or removeParentNode('para') ]] - Available[[ move_lines.state == 'assigned' and ' ' or removeParentNode('para') ]] - - [[ (move_lines.location_id and move_lines.location_id.name) or '' ]] - - [[ formatLang(move_lines.product_qty) ]] [[ move_lines.product_uom.name ]] -
- [[ get_product_desc(move_lines) ]] - - [[ (move_lines.prodlot_id and move_lines.prodlot_id.name) or '' ]] - - [[ (picking.type == 'in' or removeParentNode('para')) and '' ]][[ move_lines.state == 'done' and 'Received' or move_lines.state]] - [[ (picking.type == 'out' or removeParentNode('para')) and '']][[ move_lines.state == 'done' and 'Delivered' or move_lines.state]] - [[ (picking.type == 'internal' or removeParentNode('para')) and '' ]][[ move_lines.state == 'done' and 'Transferred' or move_lines.state]] - - [[ (move_lines.location_id and move_lines.location_id.name) or '' ]] - - [[ formatLang(move_lines.product_qty) ]] [[ move_lines.product_uom.name ]] -
- - - -
- - - - - - - - - - - - - - - - - - - - - - -
- Stock Inventory -
- - - -
- Inventory - - Date -
- [[ o.name ]] - - [[ formatLang(o.date,date_time=True) ]] -
- Location - - Production Lot - - Product - - Quantity - - Manual Quantity -
- [[ p.location_id.name ]] - - [[ p.prod_lot_id and p.prod_lot_id.name or '' ]] - - [ [[ p.product_id.code ]] ] [[ p.product_id.name ]] - - [[ formatLang(p.product_qty) ]] [[ p.product_uom.name ]] - - - - -
- - - - - Total: - - [[ formatLang(qty_total(o.inventory_line_id)['quantity']) ]] [[ qty_total(o.inventory_line_id)['uom'] ]] - - - - -
+ + + + + + + + + + + + + + + + + + + + + +
ProductScannedTodoFromTo
+ + + + +
+ +
+ + +
+ +
+
+ + + +
+ + + + : + : + + +
+
+ + + +
+

Search Results

+
+
+ + No picking found. + + + +
+
+
+ +
+
+
+
+
+
+
+ + + +
+ +

Select your operation

+ + + + +
+ +
+
+ + + + +
+ picking(s) +
+
+
+
+
+
+
+ + + + + +
+
+
+ The reserved stock changed. You might want to the operations. +
+
+ + + diff --git a/addons/stock/stock.py b/addons/stock/stock.py index 5e527a77fb9..774985ed3ac 100644 --- a/addons/stock/stock.py +++ b/addons/stock/stock.py @@ -19,21 +19,20 @@ # ############################################################################## -from datetime import datetime -from dateutil.relativedelta import relativedelta -import time -from operator import itemgetter -from itertools import groupby +from datetime import date, datetime +from dateutil import relativedelta -from openerp.osv import fields, osv, orm +import time + +from openerp.osv import fields, osv from openerp.tools.translate import _ -from openerp import workflow -from openerp import tools -from openerp.tools import float_compare, DEFAULT_SERVER_DATETIME_FORMAT +from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT +from openerp import SUPERUSER_ID import openerp.addons.decimal_precision as dp import logging -_logger = logging.getLogger(__name__) + +_logger = logging.getLogger(__name__) #---------------------------------------------------------- # Incoterms #---------------------------------------------------------- @@ -41,44 +40,30 @@ class stock_incoterms(osv.osv): _name = "stock.incoterms" _description = "Incoterms" _columns = { - 'name': fields.char('Name', size=64, required=True, help="Incoterms are series of sales terms.They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."), - 'code': fields.char('Code', size=3, required=True, help="Code for Incoterms"), - 'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM without deleting it."), + 'name': fields.char('Name', size=64, required=True, help="Incoterms are series of sales terms. They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."), + 'code': fields.char('Code', size=3, required=True, help="Incoterm Standard Code"), + 'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM you will not use."), } _defaults = { 'active': True, } - -class stock_journal(osv.osv): - _name = "stock.journal" - _description = "Stock Journal" - _columns = { - 'name': fields.char('Stock Journal', size=32, required=True), - 'user_id': fields.many2one('res.users', 'Responsible'), - } - _defaults = { - 'user_id': lambda s, c, u, ctx: u - } - - #---------------------------------------------------------- # Stock Location #---------------------------------------------------------- + class stock_location(osv.osv): _name = "stock.location" - _description = "Location" + _description = "Inventory Locations" _parent_name = "location_id" _parent_store = True - _parent_order = 'posz,name' + _parent_order = 'name' _order = 'parent_left' + _rec_name = 'complete_name' - # TODO: implement name_search() in a way that matches the results of name_get! - - def name_get(self, cr, uid, ids, context=None): - # always return the full hierarchical name - res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context) - return res.items() + def _location_owner(self, cr, uid, location, context=None): + ''' Return the company owning the location if any ''' + return location and (location.usage == 'internal') and location.company_id or False def _complete_name(self, cr, uid, ids, name, args, context=None): """ Forms complete name of location from parent location to child location. @@ -86,70 +71,38 @@ class stock_location(osv.osv): """ res = {} for m in self.browse(cr, uid, ids, context=context): - names = [m.name] + res[m.id] = m.name parent = m.location_id while parent: - names.append(parent.name) + res[m.id] = parent.name + ' / ' + res[m.id] parent = parent.location_id - res[m.id] = ' / '.join(reversed(names)) return res def _get_sublocations(self, cr, uid, ids, context=None): """ return all sublocations of the given stock locations (included) """ - return self.search(cr, uid, [('id', 'child_of', ids)], context=context) + if context is None: + context = {} + context_with_inactive = context.copy() + context_with_inactive['active_test'] = False + return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive) - def _product_value(self, cr, uid, ids, field_names, arg, context=None): - """Computes stock value (real and virtual) for a product, as well as stock qty (real and virtual). - @param field_names: Name of field - @return: Dictionary of values - """ - prod_id = context and context.get('product_id', False) + def _name_get(self, cr, uid, location, context=None): + name = location.name + while location.location_id and location.usage != 'view': + location = location.location_id + name = location.name + '/' + name + return name - if not prod_id: - return dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids]) - - product_product_obj = self.pool.get('product.product') - - cr.execute('select distinct product_id, location_id from stock_move where location_id in %s', (tuple(ids), )) - dict1 = cr.dictfetchall() - cr.execute('select distinct product_id, location_dest_id as location_id from stock_move where location_dest_id in %s', (tuple(ids), )) - dict2 = cr.dictfetchall() - res_products_by_location = sorted(dict1+dict2, key=itemgetter('location_id')) - products_by_location = dict((k, [v['product_id'] for v in itr]) for k, itr in groupby(res_products_by_location, itemgetter('location_id'))) - - result = dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids]) - result.update(dict([(i, {}.fromkeys(field_names, 0.0)) for i in list(set([aaa['location_id'] for aaa in res_products_by_location]))])) - - currency_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.currency_id.id - currency_obj = self.pool.get('res.currency') - currency = currency_obj.browse(cr, uid, currency_id, context=context) - for loc_id, product_ids in products_by_location.items(): - if prod_id: - product_ids = [prod_id] - c = (context or {}).copy() - c['location'] = loc_id - for prod in product_product_obj.browse(cr, uid, product_ids, context=c): - for f in field_names: - if f == 'stock_real': - if loc_id not in result: - result[loc_id] = {} - result[loc_id][f] += prod.qty_available - elif f == 'stock_virtual': - result[loc_id][f] += prod.virtual_available - elif f == 'stock_real_value': - amount = prod.qty_available * prod.standard_price - amount = currency_obj.round(cr, uid, currency, amount) - result[loc_id][f] += amount - elif f == 'stock_virtual_value': - amount = prod.virtual_available * prod.standard_price - amount = currency_obj.round(cr, uid, currency, amount) - result[loc_id][f] += amount - return result + def name_get(self, cr, uid, ids, context=None): + res = [] + for location in self.browse(cr, uid, ids, context=context): + res.append((location.id, self._name_get(cr, uid, location, context=context))) + return res _columns = { 'name': fields.char('Location Name', size=64, required=True, translate=True), 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."), - 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location for Inter-Companies Transfers')], 'Location Type', required=True, + 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location')], 'Location Type', required=True, help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products \n* Internal Location: Physical locations inside your own warehouses, @@ -157,454 +110,517 @@ class stock_location(osv.osv): \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories) \n* Procurement: Virtual location serving as temporary counterpart for procurement operations when the source (supplier or production) is not known yet. This location should be empty when the procurement scheduler has finished running. \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products - """, select = True), - # temporarily removed, as it's unused: 'allocation_method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO'), ('nearest', 'Nearest')], 'Allocation Method', required=True), - - # as discussed on bug 765559, the main purpose of this field is to allow sorting the list of locations - # according to the displayed names, and reversing that sort by clicking on a column. It does not work for - # translated values though - so it needs fixing. - 'complete_name': fields.function(_complete_name, type='char', size=256, string="Location Name", - store={'stock.location': (_get_sublocations, ['name', 'location_id'], 10)}), - - 'stock_real': fields.function(_product_value, type='float', string='Real Stock', multi="stock"), - 'stock_virtual': fields.function(_product_value, type='float', string='Virtual Stock', multi="stock"), + \n* Transit Location: Counterpart location that should be used in inter-companies or inter-warehouses operations + """, select=True), + 'complete_name': fields.function(_complete_name, type='char', string="Location Name", + store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}), 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'), 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'), - 'chained_journal_id': fields.many2one('stock.journal', 'Chaining Journal',help="Inventory Journal in which the chained move will be written, if the Chaining Type is not Transparent (no journal is used if left empty)"), - 'chained_location_id': fields.many2one('stock.location', 'Chained Location If Fixed'), - 'chained_location_type': fields.selection([('none', 'None'), ('customer', 'Customer'), ('fixed', 'Fixed Location')], - 'Chained Location Type', required=True, - help="Determines whether this location is chained to another location, i.e. any incoming product in this location \n" \ - "should next go to the chained location. The chained location is determined according to the type :"\ - "\n* None: No chaining at all"\ - "\n* Customer: The chained location will be taken from the Customer Location field on the Partner form of the Partner that is specified in the Picking list of the incoming products." \ - "\n* Fixed Location: The chained location is taken from the next field: Chained Location if Fixed." \ - ), - 'chained_auto_packing': fields.selection( - [('auto', 'Automatic Move'), ('manual', 'Manual Operation'), ('transparent', 'Automatic No Step Added')], - 'Chaining Type', - required=True, - help="This is used only if you select a chained location type.\n" \ - "The 'Automatic Move' value will create a stock move after the current one that will be "\ - "validated automatically. With 'Manual Operation', the stock move has to be validated "\ - "by a worker. With 'Automatic No Step Added', the location is replaced in the original move." - ), - 'chained_picking_type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], 'Shipping Type', help="Shipping Type of the Picking List that will contain the chained move (leave empty to automatically detect the type based on the source and destination locations)."), - 'chained_company_id': fields.many2one('res.company', 'Chained Company', help='The company the Picking List containing the chained move will belong to (leave empty to use the default company determination rules'), - 'chained_delay': fields.integer('Chaining Lead Time',help="Delay between original move and chained move in days"), - 'partner_id': fields.many2one('res.partner', 'Location Address',help="Address of customer or supplier."), - 'icon': fields.selection(tools.icons, 'Icon', size=64,help="Icon show in hierarchical tree view"), + 'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"), 'comment': fields.text('Additional Information'), - 'posx': fields.integer('Corridor (X)',help="Optional localization details, for information purpose only"), + 'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"), 'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"), 'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"), 'parent_left': fields.integer('Left Parent', select=1), 'parent_right': fields.integer('Right Parent', select=1), - 'stock_real_value': fields.function(_product_value, type='float', string='Real Stock Value', multi="stock", digits_compute=dp.get_precision('Account')), - 'stock_virtual_value': fields.function(_product_value, type='float', string='Virtual Stock Value', multi="stock", digits_compute=dp.get_precision('Account')), - 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between all companies'), - 'scrap_location': fields.boolean('Scrap Location', help='Check this box to allow using this location to put scrapped/damaged goods.'), - 'valuation_in_account_id': fields.many2one('account.account', 'Stock Valuation Account (Incoming)', domain = [('type','=','other')], - help="Used for real-time inventory valuation. When set on a virtual location (non internal type), " - "this account will be used to hold the value of products being moved from an internal location " - "into this location, instead of the generic Stock Output Account set on the product. " - "This has no effect for internal locations."), - 'valuation_out_account_id': fields.many2one('account.account', 'Stock Valuation Account (Outgoing)', domain = [('type','=','other')], - help="Used for real-time inventory valuation. When set on a virtual location (non internal type), " - "this account will be used to hold the value of products being moved out of this location " - "and into an internal location, instead of the generic Stock Output Account set on the product. " - "This has no effect for internal locations."), + + 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between companies'), + 'scrap_location': fields.boolean('Is a Scrap Location?', help='Check this box to allow using this location to put scrapped/damaged goods.'), + 'removal_strategy_id': fields.many2one('product.removal', 'Removal Strategy', help="Defines the default method used for suggesting the exact location (shelf) where to take the products from, which lot etc. for this location. This method can be enforced at the product category level, and a fallback is made on the parent locations if none is set here."), + 'putaway_strategy_id': fields.many2one('product.putaway', 'Put Away Strategy', help="Defines the default method used for suggesting the exact location (shelf) where to store the products. This method can be enforced at the product category level, and a fallback is made on the parent locations if none is set here."), + 'loc_barcode': fields.char('Location Barcode'), } _defaults = { 'active': True, 'usage': 'internal', - 'chained_location_type': 'none', - 'chained_auto_packing': 'manual', 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c), 'posx': 0, 'posy': 0, 'posz': 0, - 'icon': False, 'scrap_location': False, } + _sql_constraints = [('loc_barcode_company_uniq', 'unique (loc_barcode,company_id)', 'The barcode for a location must be unique per company !')] - def chained_location_get(self, cr, uid, location, partner=None, product=None, context=None): - """ Finds chained location - @param location: Location id - @param partner: Partner id - @param product: Product id - @return: List of values - """ - result = None - if location.chained_location_type == 'customer': - if partner: - result = partner.property_stock_customer - else: - loc_id = self.pool['res.partner'].default_get(cr, uid, ['property_stock_customer'], context=context)['property_stock_customer'] - result = self.pool['stock.location'].browse(cr, uid, loc_id, context=context) - elif location.chained_location_type == 'fixed': - result = location.chained_location_id - if result: - return result, location.chained_auto_packing, location.chained_delay, location.chained_journal_id and location.chained_journal_id.id or False, location.chained_company_id and location.chained_company_id.id or False, location.chained_picking_type, False - return result + def create(self, cr, uid, default, context=None): + if not default.get('loc_barcode', False): + default.update({'loc_barcode': default.get('complete_name', False)}) + return super(stock_location, self).create(cr, uid, default, context=context) - def picking_type_get(self, cr, uid, from_location, to_location, context=None): - """ Gets type of picking. - @param from_location: Source location - @param to_location: Destination location - @return: Location type - """ - result = 'internal' - if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')): - result = 'out' - elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage == 'internal'): - result = 'in' - return result + def get_putaway_strategy(self, cr, uid, location, product, context=None): + ''' Returns the location where the product has to be put, if any compliant putaway strategy is found. Otherwise returns None.''' + putaway_obj = self.pool.get('product.putaway') + loc = location + while loc: + if loc.putaway_strategy_id: + res = putaway_obj.putaway_apply(cr, uid, loc.putaway_strategy_id, product, context=context) + if res: + return res + loc = loc.location_id - def _product_get_all_report(self, cr, uid, ids, product_ids=False, context=None): - return self._product_get_report(cr, uid, ids, product_ids, context, recursive=True) + def _default_removal_strategy(self, cr, uid, context=None): + return 'fifo' - def _product_get_report(self, cr, uid, ids, product_ids=False, - context=None, recursive=False): - """ Finds the product quantity and price for particular location. - @param product_ids: Ids of product - @param recursive: True or False - @return: Dictionary of values - """ - if context is None: - context = {} - product_obj = self.pool.get('product.product') - # Take the user company and pricetype - context['currency_id'] = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id - - # To be able to offer recursive or non-recursive reports we need to prevent recursive quantities by default - context['compute_child'] = False - - if not product_ids: - product_ids = product_obj.search(cr, uid, [], context={'active_test': False}) - - products = product_obj.browse(cr, uid, product_ids, context=context) - products_by_uom = {} - products_by_id = {} - for product in products: - products_by_uom.setdefault(product.uom_id.id, []) - products_by_uom[product.uom_id.id].append(product) - products_by_id.setdefault(product.id, []) - products_by_id[product.id] = product - - result = {} - result['product'] = [] - for id in ids: - quantity_total = 0.0 - total_price = 0.0 - for uom_id in products_by_uom.keys(): - fnc = self._product_get - if recursive: - fnc = self._product_all_get - ctx = context.copy() - ctx['uom'] = uom_id - qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]], - context=ctx) - for product_id in qty.keys(): - if not qty[product_id]: - continue - product = products_by_id[product_id] - quantity_total += qty[product_id] - - # Compute based on pricetype - # Choose the right filed standard_price to read - amount_unit = product.price_get('standard_price', context=context)[product.id] - price = qty[product_id] * amount_unit - - total_price += price - result['product'].append({ - 'price': amount_unit, - 'prod_name': product.name, - 'code': product.default_code, # used by lot_overview_all report! - 'variants': product.variants or '', - 'uom': product.uom_id.name, - 'prod_qty': qty[product_id], - 'price_value': price, - }) - result['total'] = quantity_total - result['total_price'] = total_price - return result - - def _product_get_multi_location(self, cr, uid, ids, product_ids=False, context=None, - states=['done'], what=('in', 'out')): - """ - @param product_ids: Ids of product - @param states: List of states - @param what: Tuple of - @return: - """ - product_obj = self.pool.get('product.product') - if context is None: - context = {} - context.update({ - 'states': states, - 'what': what, - 'location': ids - }) - return product_obj.get_product_available(cr, uid, product_ids, context=context) - - def _product_get(self, cr, uid, id, product_ids=False, context=None, states=None): - """ - @param product_ids: - @param states: - @return: - """ - if states is None: - states = ['done'] - ids = id and [id] or [] - return self._product_get_multi_location(cr, uid, ids, product_ids, context=context, states=states) - - def _product_all_get(self, cr, uid, id, product_ids=False, context=None, states=None): - if states is None: - states = ['done'] - # build the list of ids of children of the location given by id - ids = id and [id] or [] - location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)]) - return self._product_get_multi_location(cr, uid, location_ids, product_ids, context, states) - - def _product_virtual_get(self, cr, uid, id, product_ids=False, context=None, states=None): - if states is None: - states = ['done'] - return self._product_all_get(cr, uid, id, product_ids, context, ['confirmed', 'waiting', 'assigned', 'done']) - - def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None, lock=False): - """ - Attempt to find a quantity ``product_qty`` (in the product's default uom or the uom passed in ``context``) of product ``product_id`` - in locations with id ``ids`` and their child locations. If ``lock`` is True, the stock.move lines - of product with id ``product_id`` in the searched location will be write-locked using Postgres's - "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back, to prevent reservin - twice the same products. - If ``lock`` is True and the lock cannot be obtained (because another transaction has locked some of - the same stock.move lines), a log line will be output and False will be returned, as if there was - not enough stock. - - :param product_id: Id of product to reserve - :param product_qty: Quantity of product to reserve (in the product's default uom or the uom passed in ``context``) - :param lock: if True, the stock.move lines of product with id ``product_id`` in all locations (and children locations) with ``ids`` will - be write-locked using postgres's "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back. This is - to prevent reserving twice the same products. - :param context: optional context dictionary: if a 'uom' key is present it will be used instead of the default product uom to - compute the ``product_qty`` and in the return value. - :return: List of tuples in the form (qty, location_id) with the (partial) quantities that can be taken in each location to - reach the requested product_qty (``qty`` is expressed in the default uom of the product), of False if enough - products could not be found, or the lock could not be obtained (and ``lock`` was True). - """ - result = [] - amount = 0.0 - if context is None: - context = {} - uom_obj = self.pool.get('product.uom') - uom_rounding = self.pool.get('product.product').browse(cr, uid, product_id, context=context).uom_id.rounding - if context.get('uom'): - uom_rounding = uom_obj.browse(cr, uid, context.get('uom'), context=context).rounding - - locations_ids = self.search(cr, uid, [('location_id', 'child_of', ids)]) - if locations_ids: - # Fetch only the locations in which this product has ever been processed (in or out) - cr.execute("""SELECT l.id FROM stock_location l WHERE l.id in %s AND - EXISTS (SELECT 1 FROM stock_move m WHERE m.product_id = %s - AND ((state = 'done' AND m.location_dest_id = l.id) - OR (state in ('done','assigned') AND m.location_id = l.id))) - """, (tuple(locations_ids), product_id,)) - locations_ids = [i for (i,) in cr.fetchall()] - for id in locations_ids: - if lock: - try: - # Must lock with a separate select query because FOR UPDATE can't be used with - # aggregation/group by's (when individual rows aren't identifiable). - # We use a SAVEPOINT to be able to rollback this part of the transaction without - # failing the whole transaction in case the LOCK cannot be acquired. - cr.execute("SAVEPOINT stock_location_product_reserve") - cr.execute("""SELECT id FROM stock_move - WHERE product_id=%s AND - ( - (location_dest_id=%s AND - location_id<>%s AND - state='done') - OR - (location_id=%s AND - location_dest_id<>%s AND - state in ('done', 'assigned')) - ) - FOR UPDATE of stock_move NOWAIT""", (product_id, id, id, id, id), log_exceptions=False) - except Exception: - # Here it's likely that the FOR UPDATE NOWAIT failed to get the LOCK, - # so we ROLLBACK to the SAVEPOINT to restore the transaction to its earlier - # state, we return False as if the products were not available, and log it: - cr.execute("ROLLBACK TO stock_location_product_reserve") - _logger.warning("Failed attempt to reserve %s x product %s, likely due to another transaction already in progress. Next attempt is likely to work. Detailed error available at DEBUG level.", product_qty, product_id) - _logger.debug("Trace of the failed product reservation attempt: ", exc_info=True) - return False - - # XXX TODO: rewrite this with one single query, possibly even the quantity conversion - cr.execute("""SELECT product_uom, sum(product_qty) AS product_qty - FROM stock_move - WHERE location_dest_id=%s AND - location_id<>%s AND - product_id=%s AND - state='done' - GROUP BY product_uom - """, - (id, id, product_id)) - results = cr.dictfetchall() - cr.execute("""SELECT product_uom,-sum(product_qty) AS product_qty - FROM stock_move - WHERE location_id=%s AND - location_dest_id<>%s AND - product_id=%s AND - state in ('done', 'assigned') - GROUP BY product_uom - """, - (id, id, product_id)) - results += cr.dictfetchall() - total = 0.0 - results2 = 0.0 - for r in results: - amount = uom_obj._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False)) - results2 += amount - total += amount - if total <= 0.0: - continue - - amount = results2 - compare_qty = float_compare(amount, 0, precision_rounding=uom_rounding) - if compare_qty == 1: - if amount > min(total, product_qty): - amount = min(product_qty, total) - result.append((amount, id)) - product_qty -= amount - total -= amount - if product_qty <= 0.0: - return result - if total <= 0.0: - continue - return False + def get_removal_strategy(self, cr, uid, location, product, context=None): + ''' Returns the removal strategy to consider for the given product and location. + :param location: browse record (stock.location) + :param product: browse record (product.product) + :rtype: char + ''' + if product.categ_id.removal_strategy_id: + return product.categ_id.removal_strategy_id.method + loc = location + while loc: + if loc.removal_strategy_id: + return loc.removal_strategy_id.method + loc = loc.location_id + return self._default_removal_strategy(cr, uid, context=context) +#---------------------------------------------------------- +# Routes +#---------------------------------------------------------- -class stock_tracking(osv.osv): - _name = "stock.tracking" - _description = "Packs" - - def checksum(sscc): - salt = '31' * 8 + '3' - sum = 0 - for sscc_part, salt_part in zip(sscc, salt): - sum += int(sscc_part) * int(salt_part) - return (10 - (sum % 10)) % 10 - checksum = staticmethod(checksum) - - def make_sscc(self, cr, uid, context=None): - sequence = self.pool.get('ir.sequence').get(cr, uid, 'stock.lot.tracking') - try: - return sequence + str(self.checksum(sequence)) - except Exception: - return sequence +class stock_location_route(osv.osv): + _name = 'stock.location.route' + _description = "Inventory Routes" + _order = 'sequence' _columns = { - 'name': fields.char('Pack Reference', size=64, required=True, select=True, help="By default, the pack reference is generated following the sscc standard. (Serial number + 1 check digit)"), - 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a pack without deleting it."), - 'serial': fields.char('Additional Reference', size=64, select=True, help="Other reference or serial number"), - 'move_ids': fields.one2many('stock.move', 'tracking_id', 'Moves for this pack', readonly=True), - 'date': fields.datetime('Creation Date', required=True), + 'name': fields.char('Route Name', required=True), + 'sequence': fields.integer('Sequence'), + 'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules'), + 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."), + 'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules'), + 'product_selectable': fields.boolean('Applicable on Product'), + 'product_categ_selectable': fields.boolean('Applicable on Product Category'), + 'warehouse_selectable': fields.boolean('Applicable on Warehouse'), + 'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'), + 'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'), + 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this route is shared between all companies'), } + _defaults = { - 'active': 1, - 'name': make_sscc, - 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), + 'sequence': lambda self, cr, uid, ctx: 0, + 'active': True, + 'product_selectable': True, + 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location.route', context=c), } - def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100): - if not args: - args = [] - ids = self.search(cr, user, [('serial', '=', name)]+ args, limit=limit, context=context) - ids += self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context) - return self.name_get(cr, user, ids, context) - - def name_get(self, cr, uid, ids, context=None): - """Append the serial to the name""" - if not len(ids): - return [] - res = [ (r['id'], r['serial'] and '%s [%s]' % (r['name'], r['serial']) - or r['name'] ) - for r in self.read(cr, uid, ids, ['name', 'serial'], - context=context) ] + def write(self, cr, uid, ids, vals, context=None): + '''when a route is deactivated, deactivate also its pull and push rules''' + if isinstance(ids, (int, long)): + ids = [ids] + res = super(stock_location_route, self).write(cr, uid, ids, vals, context=context) + if 'active' in vals: + push_ids = [] + pull_ids = [] + for route in self.browse(cr, uid, ids, context=context): + if route.push_ids: + push_ids += [r.id for r in route.push_ids if r.active != vals['active']] + if route.pull_ids: + pull_ids += [r.id for r in route.pull_ids if r.active != vals['active']] + if push_ids: + self.pool.get('stock.location.path').write(cr, uid, push_ids, {'active': vals['active']}, context=context) + if pull_ids: + self.pool.get('procurement.rule').write(cr, uid, pull_ids, {'active': vals['active']}, context=context) return res - def unlink(self, cr, uid, ids, context=None): - raise osv.except_osv(_('Error!'), _('You cannot remove a lot line.')) +#---------------------------------------------------------- +# Quants +#---------------------------------------------------------- - def action_traceability(self, cr, uid, ids, context=None): - """ It traces the information of a product - @param self: The object pointer. - @param cr: A database cursor - @param uid: ID of the user currently logged in - @param ids: List of IDs selected - @param context: A standard dictionary - @return: A dictionary of values +class stock_quant(osv.osv): + """ + Quants are the smallest unit of stock physical instances + """ + _name = "stock.quant" + _description = "Quants" + + def _get_quant_name(self, cr, uid, ids, name, args, context=None): + """ Forms complete name of location from parent location to child location. + @return: Dictionary of values """ - return self.pool.get('action.traceability').action_traceability(cr,uid,ids,context) + res = {} + for q in self.browse(cr, uid, ids, context=context): + + res[q.id] = q.product_id.code or '' + if q.lot_id: + res[q.id] = q.lot_id.name + res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name + return res + + def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None): + res = {} + uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id + for quant in self.browse(cr, uid, ids, context=context): + context.pop('force_company', None) + if quant.company_id.id != uid_company_id: + #if the company of the quant is different than the current user company, force the company in the context + #then re-do a browse to read the property fields for the good company. + context['force_company'] = quant.company_id.id + quant = self.browse(cr, uid, quant.id, context=context) + res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context) + return res + + def _get_inventory_value(self, cr, uid, quant, context=None): + return quant.product_id.standard_price * quant.qty + + _columns = { + 'name': fields.function(_get_quant_name, type='char', string='Identifier'), + 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete="restrict"), + 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="restrict"), + 'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product"), + 'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant"), + 'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', store=True), + 'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for"), + 'lot_id': fields.many2one('stock.production.lot', 'Lot'), + 'cost': fields.float('Unit Cost'), + 'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant"), + + 'create_date': fields.datetime('Creation Date'), + 'in_date': fields.datetime('Incoming Date'), + + 'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'), + 'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True), + 'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True), + + # Used for negative quants to reconcile after compensated by a new positive one + 'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from'), + 'negative_move_id': fields.many2one('stock.move', 'Move Negative Quant', help='If this is a negative quant, this will be the move that caused this negative quant.'), + 'negative_dest_location_id': fields.related('negative_move_id', 'location_dest_id', type='many2one', relation='stock.location', string="Negative Destination Location", help="Technical field used to record the destination location of a move that created a negative quant"), + } + + _defaults = { + 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c), + } + + def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True): + ''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by''' + res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy) + if 'inventory_value' in fields: + for line in res: + if '__domain' in line: + lines = self.search(cr, uid, line['__domain'], context=context) + inv_value = 0.0 + for line2 in self.browse(cr, uid, lines, context=context): + inv_value += line2.inventory_value + line['inventory_value'] = inv_value + return res + + def action_view_quant_history(self, cr, uid, ids, context=None): + ''' + This function returns an action that display the history of the quant, which + mean all the stock moves that lead to this quant creation with this quant quantity. + ''' + mod_obj = self.pool.get('ir.model.data') + act_obj = self.pool.get('ir.actions.act_window') + + result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2') + id = result and result[1] or False + result = act_obj.read(cr, uid, [id], context={})[0] + + move_ids = [] + for quant in self.browse(cr, uid, ids, context=context): + move_ids += [move.id for move in quant.history_ids] + + result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]" + return result + + def quants_reserve(self, cr, uid, quants, move, link=False, context=None): + '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state + is also set to 'assigned' + + :param quants: list of tuple(quant browse record or None, qty to reserve). If None is given as first tuple element, the item will be ignored. Negative quants should not be received as argument + :param move: browse record + :param link: browse record (stock.move.operation.link) + ''' + toreserve = [] + reserved_availability = move.reserved_availability + #split quants if needed + for quant, qty in quants: + if qty <= 0.0 or (quant and quant.qty <= 0.0): + raise osv.except_osv(_('Error!'), _('You can not reserve a negative quantity or a negative quant.')) + if not quant: + continue + self._quant_split(cr, uid, quant, qty, context=context) + toreserve.append(quant.id) + reserved_availability += quant.qty + #reserve quants + if toreserve: + self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id}, context=context) + #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed + if move.picking_id: + self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context) + #check if move'state needs to be set as 'assigned' + if reserved_availability == move.product_qty and move.state in ('confirmed', 'waiting'): + self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context) + elif reserved_availability > 0 and not move.partially_available: + self.pool.get('stock.move').write(cr, uid, [move.id], {'partially_available': True}, context=context) + + def quants_move(self, cr, uid, quants, move, location_to, location_from=False, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, context=None): + """Moves all given stock.quant in the given destination location. + :param quants: list of tuple(browse record(stock.quant) or None, quantity to move) + :param move: browse record (stock.move) + :param location_to: browse record (stock.location) depicting where the quants have to be moved + :param location_from: optional browse record (stock.location) explaining where the quant has to be taken (may differ from the move source location in case a removal strategy applied). This parameter is only used to pass to _quant_create if a negative quant must be created + :param lot_id: ID of the lot that must be set on the quants to move + :param owner_id: ID of the partner that must own the quants to move + :param src_package_id: ID of the package that contains the quants to move + :param dest_package_id: ID of the package that must be set on the moved quant + """ + quants_reconcile = [] + to_move_quants = [] + self._check_location(cr, uid, location_to, context=context) + for quant, qty in quants: + if not quant: + #If quant is None, we will create a quant to move (and potentially a negative counterpart too) + quant = self._quant_create(cr, uid, qty, move, lot_id=lot_id, owner_id=owner_id, src_package_id=src_package_id, dest_package_id=dest_package_id, force_location_from=location_from, force_location_to=location_to, context=context) + else: + self._quant_split(cr, uid, quant, qty, context=context) + quant.refresh() + to_move_quants.append(quant) + quants_reconcile.append(quant) + if to_move_quants: + to_recompute_move_ids = [x.reservation_id.id for x in to_move_quants if x.reservation_id and x.reservation_id.id != move.id] + self.move_quants_write(cr, uid, to_move_quants, move, location_to, dest_package_id, context=context) + self.pool.get('stock.move').recalculate_move_state(cr, uid, to_recompute_move_ids, context=context) + if location_to.usage == 'internal': + if self.search(cr, uid, [('product_id', '=', move.product_id.id), ('qty','<', 0)], limit=1, context=context): + for quant in quants_reconcile: + quant.refresh() + self._quant_reconcile_negative(cr, uid, quant, move, context=context) + + def move_quants_write(self, cr, uid, quants, move, location_dest_id, dest_package_id, context=None): + vals = {'location_id': location_dest_id.id, + 'history_ids': [(4, move.id)], + 'package_id': dest_package_id} + self.write(cr, SUPERUSER_ID, [q.id for q in quants], vals, context=context) + + def quants_get_prefered_domain(self, cr, uid, location, product, qty, domain=None, prefered_domain_list=[], restrict_lot_id=False, restrict_partner_id=False, context=None): + ''' This function tries to find quants in the given location for the given domain, by trying to first limit + the choice on the quants that match the first item of prefered_domain_list as well. But if the qty requested is not reached + it tries to find the remaining quantity by looping on the prefered_domain_list (tries with the second item and so on). + Make sure the quants aren't found twice => all the domains of prefered_domain_list should be orthogonal + ''' + if domain is None: + domain = [] + quants = [(None, qty)] + #don't look for quants in location that are of type production, supplier or inventory. + if location.usage in ['inventory', 'production', 'supplier']: + return quants + res_qty = qty + if not prefered_domain_list: + return self.quants_get(cr, uid, location, product, qty, domain=domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context) + for prefered_domain in prefered_domain_list: + if res_qty > 0: + #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order + quants.pop() + tmp_quants = self.quants_get(cr, uid, location, product, res_qty, domain=domain + prefered_domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context) + for quant in tmp_quants: + if quant[0]: + res_qty -= quant[1] + quants += tmp_quants + return quants + + def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None): + """ + Use the removal strategies of product to search for the correct quants + If you inherit, put the super at the end of your method. + + :location: browse record of the parent location where the quants have to be found + :product: browse record of the product to find + :qty in UoM of product + """ + result = [] + domain = domain or [('qty', '>', 0.0)] + if restrict_partner_id: + domain += [('owner_id', '=', restrict_partner_id)] + if restrict_lot_id: + domain += [('lot_id', '=', restrict_lot_id)] + if location: + removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context) + result += self.apply_removal_strategy(cr, uid, location, product, qty, domain, removal_strategy, context=context) + return result + + def apply_removal_strategy(self, cr, uid, location, product, quantity, domain, removal_strategy, context=None): + if removal_strategy == 'fifo': + order = 'in_date, id' + return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context) + elif removal_strategy == 'lifo': + order = 'in_date desc, id desc' + return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context) + raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,))) + + def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, + force_location_from=False, force_location_to=False, context=None): + '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location. + ''' + if context is None: + context = {} + price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context) + location = force_location_to or move.location_dest_id + vals = { + 'product_id': move.product_id.id, + 'location_id': location.id, + 'qty': qty, + 'cost': price_unit, + 'history_ids': [(4, move.id)], + 'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT), + 'company_id': move.company_id.id, + 'lot_id': lot_id, + 'owner_id': owner_id, + 'package_id': dest_package_id, + } + + if move.location_id.usage == 'internal': + #if we were trying to move something from an internal location and reach here (quant creation), + #it means that a negative quant has to be created as well. + negative_vals = vals.copy() + negative_vals['location_id'] = force_location_from and force_location_from.id or move.location_id.id + negative_vals['qty'] = -qty + negative_vals['cost'] = price_unit + negative_vals['negative_move_id'] = move.id + negative_vals['package_id'] = src_package_id + negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context) + vals.update({'propagated_from_id': negative_quant_id}) + + #create the quant as superuser, because we want to restrict the creation of quant manually: we should always use this method to create quants + quant_id = self.create(cr, SUPERUSER_ID, vals, context=context) + return self.browse(cr, uid, quant_id, context=context) + + def _quant_split(self, cr, uid, quant, qty, context=None): + context = context or {} + if (quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty): + return False + new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty}, context=context) + self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context) + quant.refresh() + return self.browse(cr, uid, new_quant, context=context) + + def _get_latest_move(self, cr, uid, quant, context=None): + move = False + for m in quant.history_ids: + if not move or m.date > move.date: + move = m + return move + + def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None): + path = [] + for move in solving_quant.history_ids: + path.append((4, move.id)) + self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context) + + def _quant_reconcile_negative(self, cr, uid, quant, move, context=None): + """ + When new quant arrive in a location, try to reconcile it with + negative quants. If it's possible, apply the cost of the new + quant to the conter-part of the negative quant. + """ + solving_quant = quant + dom = [('qty', '<', 0)] + if quant.lot_id: + dom += [('lot_id', '=', quant.lot_id.id)] + dom += [('owner_id', '=', quant.owner_id.id)] + dom += [('package_id', '=', quant.package_id.id)] + quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, dom, context=context) + for quant_neg, qty in quants: + if not quant_neg: + continue + to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context) + if not to_solve_quant_ids: + continue + solving_qty = qty + solved_quant_ids = [] + for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context): + if solving_qty <= 0: + continue + solved_quant_ids.append(to_solve_quant.id) + self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context) + solving_qty -= min(solving_qty, to_solve_quant.qty) + remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context) + remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context) + #if the reconciliation was not complete, we need to link together the remaining parts + if remaining_neg_quant: + remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context) + if remaining_to_solve_quant_ids: + self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context) + #delete the reconciled quants, as it is replaced by the solved quants + self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context) + #price update + accounting entries adjustments + self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context) + #merge history (and cost?) + self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context) + self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context) + solving_quant = remaining_solving_quant + + def _price_update(self, cr, uid, ids, newprice, context=None): + self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context) + + def quants_unreserve(self, cr, uid, move, context=None): + related_quants = [x.id for x in move.reserved_quant_ids] + if related_quants: + #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed + if move.picking_id: + self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context) + if move.partially_available: + self.pool.get("stock.move").write(cr, uid, [move.id], {'partially_available': False}, context=context) + self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False}, context=context) + + def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None): + ''' Implementation of removal strategies + If it can not reserve, it will return a tuple (None, qty) + ''' + if context is None: + context = {} + domain += location and [('location_id', 'child_of', location.id)] or [] + domain += [('product_id', '=', product.id)] + if context.get('force_company'): + domain += [('company_id', '=', context.get('force_company'))] + else: + domain += [('company_id', '=', self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id)] + res = [] + offset = 0 + while quantity > 0: + quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context) + if not quants: + res.append((None, quantity)) + break + for quant in self.browse(cr, uid, quants, context=context): + if quantity >= abs(quant.qty): + res += [(quant, abs(quant.qty))] + quantity -= abs(quant.qty) + elif quantity != 0: + res += [(quant, quantity)] + quantity = 0 + break + offset += 10 + return res + + def _check_location(self, cr, uid, location, context=None): + if location.usage == 'view': + raise osv.except_osv(_('Error'), _('You cannot move to a location of type view %s.') % (location.name)) + return True #---------------------------------------------------------- # Stock Picking #---------------------------------------------------------- + class stock_picking(osv.osv): _name = "stock.picking" _inherit = ['mail.thread'] _description = "Picking List" - _order = "id desc" + _order = "priority desc, date asc, id desc" - def _set_maximum_date(self, cr, uid, ids, name, value, arg, context=None): - """ Calculates planned date if it is greater than 'value'. - @param name: Name of field - @param value: Value of field - @param arg: User defined argument - @return: True or False - """ - if not value: - return False - if isinstance(ids, (int, long)): - ids = [ids] - for pick in self.browse(cr, uid, ids, context=context): - sql_str = """update stock_move set - date_expected='%s' - where - picking_id=%d """ % (value, pick.id) - if pick.max_date: - sql_str += " and (date_expected='" + pick.max_date + "')" - cr.execute(sql_str) - return True - - def _set_minimum_date(self, cr, uid, ids, name, value, arg, context=None): - """ Calculates planned date if it is less than 'value'. - @param name: Name of field - @param value: Value of field - @param arg: User defined argument - @return: True or False - """ - if not value: - return False - if isinstance(ids, (int, long)): - ids = [ids] - for pick in self.browse(cr, uid, ids, context=context): - sql_str = """update stock_move set - date_expected='%s' - where - picking_id=%s """ % (value, pick.id) - if pick.min_date: - sql_str += " and (date_expected='" + pick.min_date + "')" - cr.execute(sql_str) - return True + def _set_min_date(self, cr, uid, id, field, value, arg, context=None): + move_obj = self.pool.get("stock.move") + if value: + move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines] + move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context) def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None): """ Finds minimum and maximum dates for picking. @@ -624,866 +640,797 @@ class stock_picking(osv.osv): where picking_id IN %s group by - picking_id""",(tuple(ids),)) + picking_id""", (tuple(ids),)) for pick, dt1, dt2 in cr.fetchall(): res[pick]['min_date'] = dt1 res[pick]['max_date'] = dt2 return res def create(self, cr, user, vals, context=None): - if ('name' not in vals) or (vals.get('name')=='/') or (vals.get('name') == False): - seq_obj_name = self._name - vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name) - new_id = super(stock_picking, self).create(cr, user, vals, context) - return new_id + context = context or {} + if ('name' not in vals) or (vals.get('name') in ('/', False)): + ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False)) + sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id + vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context) + return super(stock_picking, self).create(cr, user, vals, context) + + def _state_get(self, cr, uid, ids, field_name, arg, context=None): + '''The state of a picking depends on the state of its related stock.move + draft: the picking has no line or any one of the lines is draft + done, draft, cancel: all lines are done / draft / cancel + confirmed, waiting, assigned, partially_available depends on move_type (all at once or partial) + ''' + res = {} + for pick in self.browse(cr, uid, ids, context=context): + if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]): + res[pick.id] = 'draft' + continue + if all([x.state == 'cancel' for x in pick.move_lines]): + res[pick.id] = 'cancel' + continue + if all([x.state in ('cancel', 'done') for x in pick.move_lines]): + res[pick.id] = 'done' + continue + + order = {'confirmed': 0, 'waiting': 1, 'assigned': 2} + order_inv = {0: 'confirmed', 1: 'waiting', 2: 'assigned'} + lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')] + if pick.move_type == 'one': + res[pick.id] = order_inv[min(lst)] + else: + #we are in the case of partial delivery, so if all move are assigned, picking + #should be assign too, else if one of the move is assigned, or partially available, picking should be + #in partially available state, otherwise, picking is in waiting or confirmed state + res[pick.id] = order_inv[max(lst)] + if not all(x == 2 for x in lst): + if any(x == 2 for x in lst): + res[pick.id] = 'partially_available' + else: + #if all moves aren't assigned, check if we have one product partially available + for move in pick.move_lines: + if move.partially_available: + res[pick.id] = 'partially_available' + break + return res + + def _get_pickings(self, cr, uid, ids, context=None): + res = set() + for move in self.browse(cr, uid, ids, context=context): + if move.picking_id: + res.add(move.picking_id.id) + return list(res) + + def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None): + res = {} + for pick in self.browse(cr, uid, ids, context=context): + res[pick.id] = False + if pick.pack_operation_ids: + res[pick.id] = True + return res + + def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None): + res = {} + for pick in self.browse(cr, uid, ids, context=context): + res[pick.id] = False + for move in pick.move_lines: + if move.reserved_quant_ids: + res[pick.id] = True + continue + return res + + def check_group_lot(self, cr, uid, context=None): + """ This function will return true if we have the setting to use lots activated. """ + return self.pool.get('res.users').has_group(cr, uid, 'stock.group_production_lot') + + def check_group_pack(self, cr, uid, context=None): + """ This function will return true if we have the setting to use package activated. """ + return self.pool.get('res.users').has_group(cr, uid, 'stock.group_tracking_lot') + + def action_assign_owner(self, cr, uid, ids, context=None): + for picking in self.browse(cr, uid, ids, context=context): + packop_ids = [op.id for op in picking.pack_operation_ids] + self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context) _columns = { - 'name': fields.char('Reference', size=64, select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}), - 'origin': fields.char('Source Document', size=64, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Reference of the document", select=True), - 'backorder_id': fields.many2one('stock.picking', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True), - 'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], 'Shipping Type', required=True, select=True, help="Shipping type specify, goods coming in or going out."), - 'note': fields.text('Notes', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}), - 'stock_journal_id': fields.many2one('stock.journal','Stock Journal', select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}), - 'location_id': fields.many2one('stock.location', 'Location', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Keep empty if you produce at the location where the finished products are needed." \ - "Set a location if you produce at a fixed location. This can be a partner location " \ - "if you subcontract the manufacturing operations.", select=True), - 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Location where the system will stock the finished products.", select=True), - 'move_type': fields.selection([('direct', 'Partial'), ('one', 'All at once')], 'Delivery Method', required=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="It specifies goods to be deliver partially or all at once"), - 'state': fields.selection([ - ('draft', 'Draft'), - ('cancel', 'Cancelled'), - ('auto', 'Waiting Another Operation'), - ('confirmed', 'Waiting Availability'), - ('assigned', 'Ready to Transfer'), - ('done', 'Transferred'), - ], 'Status', readonly=True, select=True, track_visibility='onchange', help=""" - * Draft: not confirmed yet and will not be scheduled until confirmed\n - * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n - * Waiting Availability: still waiting for the availability of products\n - * Ready to Transfer: products reserved, simply waiting for confirmation.\n - * Transferred: has been processed, can't be modified or cancelled anymore\n - * Cancelled: has been cancelled, can't be confirmed anymore""" + 'name': fields.char('Reference', size=64, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}), + 'origin': fields.char('Source Document', size=64, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True), + 'backorder_id': fields.many2one('stock.picking', 'Back Order of', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True), + 'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}), + 'move_type': fields.selection([('direct', 'Partial'), ('one', 'All at once')], 'Delivery Method', required=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="It specifies goods to be deliver partially or all at once"), + 'state': fields.function(_state_get, type="selection", + store={ + 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type'], 20), + 'stock.move': (_get_pickings, ['state', 'picking_id', 'partially_available'], 20)}, + selection=[ + ('draft', 'Draft'), + ('cancel', 'Cancelled'), + ('waiting', 'Waiting Another Operation'), + ('confirmed', 'Waiting Availability'), + ('partially_available', 'Partially Available'), + ('assigned', 'Ready to Transfer'), + ('done', 'Transferred'), + ], string='Status', readonly=True, select=True, track_visibility='onchange', + help=""" + * Draft: not confirmed yet and will not be scheduled until confirmed\n + * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n + * Waiting Availability: still waiting for the availability of products\n + * Partially Available: some products are available and reserved\n + * Ready to Transfer: products reserved, simply waiting for confirmation.\n + * Transferred: has been processed, can't be modified or cancelled anymore\n + * Cancelled: has been cancelled, can't be confirmed anymore""" ), - 'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date", - store=True, type='datetime', string='Scheduled Time', select=1, help="Scheduled time for the shipment to be processed"), - 'date': fields.datetime('Creation Date', help="Creation date, usually the time of the order.", select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}), - 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}), - 'max_date': fields.function(get_min_max_date, fnct_inv=_set_maximum_date, multi="min_max_date", - store=True, type='datetime', string='Max. Expected Date', select=2), + 'priority': fields.selection([('0', 'Low'), ('1', 'Normal'), ('2', 'High')], states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Priority', required=True), + 'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date, + store={'stock.move': (_get_pickings, ['date_expected'], 20)}, type='datetime', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Scheduled Date', select=1, help="Scheduled time for the first part of the shipment to be processed. Setting manually a value here would set it as expected date for all the stock moves.", track_visibility='onchange'), + 'max_date': fields.function(get_min_max_date, multi="min_max_date", + store={'stock.move': (_get_pickings, ['date_expected'], 20)}, type='datetime', string='Max. Expected Date', select=2, help="Scheduled time for the last part of the shipment to be processed"), + 'date': fields.datetime('Commitment Date', help="Date promised for the completion of the transfer order, usually set the time of the order and revised later on.", select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, track_visibility='onchange'), + 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}), 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}), + 'quant_reserved_exist': fields.function(_get_quant_reserved_exist, type='boolean', string='Quant already reserved ?', help='technical field used to know if there is already at least one quant reserved on moves of a given picking'), + 'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}), + 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}), + 'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Related Packing Operations'), + 'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'), + 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, required=True), + 'picking_type_code': fields.related('picking_type_id', 'code', type='char', string='Picking Type Code', help="Technical field used to display the correct label on print button in the picking view"), + + 'owner_id': fields.many2one('res.partner', 'Owner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Default Owner"), + # Used to search on pickings 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'), - 'auto_picking': fields.boolean('Auto-Picking', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}), - 'partner_id': fields.many2one('res.partner', 'Partner', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}), - 'invoice_state': fields.selection([ - ("invoiced", "Invoiced"), - ("2binvoiced", "To Be Invoiced"), - ("none", "Not Applicable")], "Invoice Control", - select=True, required=True, readonly=True, track_visibility='onchange', states={'draft': [('readonly', False)]}), - 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}), + 'recompute_pack_op': fields.boolean('Recompute pack operation?', help='True if reserved quants changed, which mean we might need to recompute the package operations'), + 'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True), + 'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True), + 'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True, + store={ + 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10), + 'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10), + }), } + _defaults = { 'name': lambda self, cr, uid, context: '/', 'state': 'draft', 'move_type': 'direct', - 'type': 'internal', - 'invoice_state': 'none', - 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), - 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c) + 'priority': '1', # normal + 'date': fields.datetime.now, + 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c), + 'recompute_pack_op': True, } _sql_constraints = [ - ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per Company!'), + ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'), ] - def action_process(self, cr, uid, ids, context=None): - if context is None: - context = {} - """Open the partial picking wizard""" - context.update({ - 'active_model': self._name, - 'active_ids': ids, - 'active_id': len(ids) and ids[0] or False - }) - return { - 'view_type': 'form', - 'view_mode': 'form', - 'res_model': 'stock.partial.picking', - 'type': 'ir.actions.act_window', - 'target': 'new', - 'context': context, - 'nodestroy': True, - } - def copy(self, cr, uid, id, default=None, context=None): if default is None: default = {} default = default.copy() picking_obj = self.browse(cr, uid, id, context=context) if ('name' not in default) or (picking_obj.name == '/'): - seq_obj_name = 'stock.picking.' + picking_obj.type - default['name'] = self.pool.get('ir.sequence').get(cr, uid, seq_obj_name) - default['origin'] = '' + default['name'] = '/' + if not default.get('backorder_id'): default['backorder_id'] = False - if 'invoice_state' not in default and picking_obj.invoice_state == 'invoiced': - default['invoice_state'] = '2binvoiced' - res = super(stock_picking, self).copy(cr, uid, id, default, context) - return res + default['pack_operation_ids'] = [] + default['date_done'] = False + return super(stock_picking, self).copy(cr, uid, id, default, context) - def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False): - if view_type == 'form' and not view_id: - mod_obj = self.pool.get('ir.model.data') - if self._name == "stock.picking.in": - model, view_id = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_in_form') - if self._name == "stock.picking.out": - model, view_id = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_out_form') - return super(stock_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) + def do_print_picking(self, cr, uid, ids, context=None): + '''This function prints the picking list''' + context = context or {} + context['active_ids'] = ids + return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_picking', context=context) - def onchange_partner_in(self, cr, uid, ids, partner_id=None, context=None): - return {} - - def action_explode(self, cr, uid, moves, context=None): - """Hook to allow other modules to split the moves of a picking.""" - return moves def action_confirm(self, cr, uid, ids, context=None): - """ Confirms picking. - @return: True - """ - pickings = self.browse(cr, uid, ids, context=context) - self.write(cr, uid, ids, {'state': 'confirmed'}) todo = [] - for picking in pickings: + todo_force_assign = [] + for picking in self.browse(cr, uid, ids, context=context): + if picking.location_id.usage in ('supplier', 'inventory', 'production'): + todo_force_assign.append(picking.id) for r in picking.move_lines: if r.state == 'draft': todo.append(r.id) - todo = self.action_explode(cr, uid, todo, context) if len(todo): self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context) + + if todo_force_assign: + self.force_assign(cr, uid, todo_force_assign, context=context) return True - def test_auto_picking(self, cr, uid, ids): - # TODO: Check locations to see if in the same location ? - return True - - def action_assign(self, cr, uid, ids, *args): - """ Changes state of picking to available if all moves are confirmed. + def action_assign(self, cr, uid, ids, context=None): + """ Check availability of picking moves. + This has the effect of changing the state and reserve quants on available moves, and may + also impact the state of the picking as it is computed based on move's states. @return: True """ - for pick in self.browse(cr, uid, ids): + for pick in self.browse(cr, uid, ids, context=context): if pick.state == 'draft': - self.signal_button_confirm(cr, uid, [pick.id]) - move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed'] + self.action_confirm(cr, uid, [pick.id], context=context) + pick.refresh() + #skip the moves that don't need to be checked + move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')] if not move_ids: - raise osv.except_osv(_('Warning!'),_('Not enough stock, unable to reserve the products.')) - self.pool.get('stock.move').action_assign(cr, uid, move_ids) + raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.')) + self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context) return True - def force_assign(self, cr, uid, ids, *args): + def force_assign(self, cr, uid, ids, context=None): """ Changes state of picking to available if moves are confirmed or waiting. @return: True """ - for pick in self.browse(cr, uid, ids): - move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed','waiting']] - self.pool.get('stock.move').force_assign(cr, uid, move_ids) - workflow.trg_write(uid, 'stock.picking', pick.id, cr) - return True - - def draft_force_assign(self, cr, uid, ids, *args): - """ Confirms picking directly from draft state. - @return: True - """ - for pick in self.browse(cr, uid, ids): - if not pick.move_lines: - raise osv.except_osv(_('Error!'),_('You cannot process picking without stock moves.')) - self.signal_button_confirm(cr, uid, [pick.id]) - return True - - def draft_validate(self, cr, uid, ids, context=None): - """ Validates picking directly from draft state. - @return: True - """ - self.draft_force_assign(cr, uid, ids) for pick in self.browse(cr, uid, ids, context=context): - move_ids = [x.id for x in pick.move_lines] - self.pool.get('stock.move').force_assign(cr, uid, move_ids) - workflow.trg_write(uid, 'stock.picking', pick.id, cr) - return self.action_process( - cr, uid, ids, context=context) - def cancel_assign(self, cr, uid, ids, *args): - """ Cancels picking and moves. - @return: True - """ - for pick in self.browse(cr, uid, ids): - move_ids = [x.id for x in pick.move_lines] - self.pool.get('stock.move').cancel_assign(cr, uid, move_ids) - workflow.trg_write(uid, 'stock.picking', pick.id, cr) + move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']] + self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context) + #pack_operation might have changed and need to be recomputed + self.write(cr, uid, ids, {'recompute_pack_op': True}, context=context) return True - def action_assign_wkf(self, cr, uid, ids, context=None): - """ Changes picking state to assigned. - @return: True - """ - self.write(cr, uid, ids, {'state': 'assigned'}) - return True - - def test_finished(self, cr, uid, ids): - """ Tests whether the move is in done or cancel state or not. - @return: True or False - """ - move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)]) - for move in self.pool.get('stock.move').browse(cr, uid, move_ids): - if move.state not in ('done', 'cancel'): - - if move.product_qty != 0.0: - return False - else: - move.write({'state': 'done'}) - return True - - def test_assigned(self, cr, uid, ids): - """ Tests whether the move is in assigned state or not. - @return: True or False - """ - #TOFIX: assignment of move lines should be call before testing assigment otherwise picking never gone in assign state - ok = True - for pick in self.browse(cr, uid, ids): - mt = pick.move_type - # incomming shipments are always set as available if they aren't chained - if pick.type == 'in': - if all([x.state != 'waiting' for x in pick.move_lines]): - return True - for move in pick.move_lines: - if (move.state in ('confirmed', 'draft')) and (mt == 'one'): - return False - if (mt == 'direct') and (move.state == 'assigned') and (move.product_qty): - return True - ok = ok and (move.state in ('cancel', 'done', 'assigned')) - return ok - def action_cancel(self, cr, uid, ids, context=None): - """ Changes picking state to cancel. - @return: True - """ for pick in self.browse(cr, uid, ids, context=context): ids2 = [move.id for move in pick.move_lines] self.pool.get('stock.move').action_cancel(cr, uid, ids2, context) - self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'}) return True - # - # TODO: change and create a move if not parents - # def action_done(self, cr, uid, ids, context=None): - """Changes picking state to done. - - This method is called at the end of the workflow by the activity "done". - @return: True - """ - self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')}) - return True + """Changes picking state to done by processing the Stock Moves of the Picking - def action_move(self, cr, uid, ids, context=None): - """Process the Stock Moves of the Picking - - This method is called by the workflow by the activity "move". - Normally that happens when the signal button_done is received (button - "Done" pressed on a Picking view). + Normally that happens when the button "Done" is pressed on a Picking view. @return: True """ for pick in self.browse(cr, uid, ids, context=context): todo = [] for move in pick.move_lines: if move.state == 'draft': - self.pool.get('stock.move').action_confirm(cr, uid, [move.id], - context=context) - todo.append(move.id) - elif move.state in ('assigned','confirmed'): + todo.extend(self.pool.get('stock.move').action_confirm(cr, uid, [move.id], context=context)) + elif move.state in ('assigned', 'confirmed'): todo.append(move.id) if len(todo): - self.pool.get('stock.move').action_done(cr, uid, todo, - context=context) - return True - - def get_currency_id(self, cr, uid, picking): - return False - - def _get_partner_to_invoice(self, cr, uid, picking, context=None): - """ Gets the partner that will be invoiced - Note that this function is inherited in the sale and purchase modules - @param picking: object of the picking for which we are selecting the partner to invoice - @return: object of the partner to invoice - """ - return picking.partner_id and picking.partner_id.id - - def _get_comment_invoice(self, cr, uid, picking): - """ - @return: comment string for invoice - """ - return picking.note or '' - - def _get_price_unit_invoice(self, cr, uid, move_line, type, context=None): - """ Gets price unit for invoice - @param move_line: Stock move lines - @param type: Type of invoice - @return: The price unit for the move line - """ - if context is None: - context = {} - - if type in ('in_invoice', 'in_refund'): - # Take the user company and pricetype - context['currency_id'] = move_line.company_id.currency_id.id - amount_unit = move_line.product_id.price_get('standard_price', context=context)[move_line.product_id.id] - return amount_unit - else: - return move_line.product_id.list_price - - def _get_discount_invoice(self, cr, uid, move_line): - '''Return the discount for the move line''' - return 0.0 - - def _get_taxes_invoice(self, cr, uid, move_line, type): - """ Gets taxes on invoice - @param move_line: Stock move lines - @param type: Type of invoice - @return: Taxes Ids for the move line - """ - if type in ('in_invoice', 'in_refund'): - taxes = move_line.product_id.supplier_taxes_id - else: - taxes = move_line.product_id.taxes_id - - if move_line.picking_id and move_line.picking_id.partner_id and move_line.picking_id.partner_id.id: - return self.pool.get('account.fiscal.position').map_tax( - cr, - uid, - move_line.picking_id.partner_id.property_account_position, - taxes - ) - else: - return map(lambda x: x.id, taxes) - - def _get_account_analytic_invoice(self, cr, uid, picking, move_line): - return False - - def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id): - '''Call after the creation of the invoice line''' - return - - def _invoice_hook(self, cr, uid, picking, invoice_id): - '''Call after the creation of the invoice''' - return - - def _get_invoice_type(self, pick): - src_usage = dest_usage = None - inv_type = None - if pick.invoice_state == '2binvoiced': - if pick.move_lines: - src_usage = pick.move_lines[0].location_id.usage - dest_usage = pick.move_lines[0].location_dest_id.usage - if pick.type == 'out' and dest_usage == 'supplier': - inv_type = 'in_refund' - elif pick.type == 'out' and dest_usage == 'customer': - inv_type = 'out_invoice' - elif pick.type == 'in' and src_usage == 'supplier': - inv_type = 'in_invoice' - elif pick.type == 'in' and src_usage == 'customer': - inv_type = 'out_refund' - else: - inv_type = 'out_invoice' - return inv_type - - def _prepare_invoice_group(self, cr, uid, picking, partner, invoice, context=None): - """ Builds the dict for grouped invoices - @param picking: picking object - @param partner: object of the partner to invoice (not used here, but may be usefull if this function is inherited) - @param invoice: object of the invoice that we are updating - @return: dict that will be used to update the invoice - """ - comment = self._get_comment_invoice(cr, uid, picking) - return { - 'name': (invoice.name or '') + ', ' + (picking.name or ''), - 'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''), - 'comment': (comment and (invoice.comment and invoice.comment + "\n" + comment or comment)) or (invoice.comment and invoice.comment or ''), - 'date_invoice': context.get('date_inv', False), - 'user_id': uid, - } - - def _prepare_invoice(self, cr, uid, picking, partner, inv_type, journal_id, context=None): - """ Builds the dict containing the values for the invoice - @param picking: picking object - @param partner: object of the partner to invoice - @param inv_type: type of the invoice ('out_invoice', 'in_invoice', ...) - @param journal_id: ID of the accounting journal - @return: dict that will be used to create the invoice object - """ - if isinstance(partner, int): - partner = self.pool.get('res.partner').browse(cr, uid, partner, context=context) - if inv_type in ('out_invoice', 'out_refund'): - account_id = partner.property_account_receivable.id - payment_term = partner.property_payment_term.id or False - else: - account_id = partner.property_account_payable.id - payment_term = partner.property_supplier_payment_term.id or False - comment = self._get_comment_invoice(cr, uid, picking) - invoice_vals = { - 'name': picking.name, - 'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''), - 'type': inv_type, - 'account_id': account_id, - 'partner_id': partner.id, - 'comment': comment, - 'payment_term': payment_term, - 'fiscal_position': partner.property_account_position.id, - 'date_invoice': context.get('date_inv', False), - 'company_id': picking.company_id.id, - 'user_id': uid, - } - cur_id = self.get_currency_id(cr, uid, picking) - if cur_id: - invoice_vals['currency_id'] = cur_id - if journal_id: - invoice_vals['journal_id'] = journal_id - return invoice_vals - - def _prepare_invoice_line(self, cr, uid, group, picking, move_line, invoice_id, - invoice_vals, context=None): - """ Builds the dict containing the values for the invoice line - @param group: True or False - @param picking: picking object - @param: move_line: move_line object - @param: invoice_id: ID of the related invoice - @param: invoice_vals: dict used to created the invoice - @return: dict that will be used to create the invoice line - """ - if group: - name = (picking.name or '') + '-' + move_line.name - else: - name = move_line.name - origin = move_line.picking_id.name or '' - if move_line.picking_id.origin: - origin += ':' + move_line.picking_id.origin - - if invoice_vals['type'] in ('out_invoice', 'out_refund'): - account_id = move_line.product_id.property_account_income.id - if not account_id: - account_id = move_line.product_id.categ_id.\ - property_account_income_categ.id - else: - account_id = move_line.product_id.property_account_expense.id - if not account_id: - account_id = move_line.product_id.categ_id.\ - property_account_expense_categ.id - if invoice_vals['fiscal_position']: - fp_obj = self.pool.get('account.fiscal.position') - fiscal_position = fp_obj.browse(cr, uid, invoice_vals['fiscal_position'], context=context) - account_id = fp_obj.map_account(cr, uid, fiscal_position, account_id) - # set UoS if it's a sale and the picking doesn't have one - uos_id = move_line.product_uos and move_line.product_uos.id or False - if not uos_id and invoice_vals['type'] in ('out_invoice', 'out_refund'): - uos_id = move_line.product_uom.id - - return { - 'name': name, - 'origin': origin, - 'invoice_id': invoice_id, - 'uos_id': uos_id, - 'product_id': move_line.product_id.id, - 'account_id': account_id, - 'price_unit': self._get_price_unit_invoice(cr, uid, move_line, invoice_vals['type']), - 'discount': self._get_discount_invoice(cr, uid, move_line), - 'quantity': move_line.product_uos_qty or move_line.product_qty, - 'invoice_line_tax_id': [(6, 0, self._get_taxes_invoice(cr, uid, move_line, invoice_vals['type']))], - 'account_analytic_id': self._get_account_analytic_invoice(cr, uid, picking, move_line), - } - - def action_invoice_create(self, cr, uid, ids, journal_id=False, - group=False, type='out_invoice', context=None): - """ Creates invoice based on the invoice state selected for picking. - @param journal_id: Id of journal - @param group: Whether to create a group invoice or not - @param type: Type invoice to be created - @return: Ids of created invoices for the pickings - """ - if context is None: - context = {} - - invoice_obj = self.pool.get('account.invoice') - invoice_line_obj = self.pool.get('account.invoice.line') - partner_obj = self.pool.get('res.partner') - invoices_group = {} - res = {} - inv_type = type - for picking in self.browse(cr, uid, ids, context=context): - if picking.invoice_state != '2binvoiced': - continue - partner = self._get_partner_to_invoice(cr, uid, picking, context=context) - if isinstance(partner, int): - partner = partner_obj.browse(cr, uid, [partner], context=context)[0] - if not partner: - raise osv.except_osv(_('Error, no partner!'), - _('Please put a partner on the picking list if you want to generate invoice.')) - - if not inv_type: - inv_type = self._get_invoice_type(picking) - - if group and partner.id in invoices_group: - invoice_id = invoices_group[partner.id] - invoice = invoice_obj.browse(cr, uid, invoice_id) - invoice_vals_group = self._prepare_invoice_group(cr, uid, picking, partner, invoice, context=context) - invoice_obj.write(cr, uid, [invoice_id], invoice_vals_group, context=context) - else: - invoice_vals = self._prepare_invoice(cr, uid, picking, partner, inv_type, journal_id, context=context) - invoice_id = invoice_obj.create(cr, uid, invoice_vals, context=context) - invoices_group[partner.id] = invoice_id - res[picking.id] = invoice_id - for move_line in picking.move_lines: - if move_line.state == 'cancel': - continue - if move_line.scrapped: - # do no invoice scrapped products - continue - vals = self._prepare_invoice_line(cr, uid, group, picking, move_line, - invoice_id, invoice_vals, context=context) - if vals: - invoice_line_id = invoice_line_obj.create(cr, uid, vals, context=context) - self._invoice_line_hook(cr, uid, move_line, invoice_line_id) - - invoice_obj.button_compute(cr, uid, [invoice_id], context=context, - set_total=(inv_type in ('in_invoice', 'in_refund'))) - self.write(cr, uid, [picking.id], { - 'invoice_state': 'invoiced', - }, context=context) - self._invoice_hook(cr, uid, picking, invoice_id) - self.write(cr, uid, res.keys(), { - 'invoice_state': 'invoiced', - }, context=context) - return res - - def test_done(self, cr, uid, ids, context=None): - """ Test whether the move lines are done or not. - @return: True or False - """ - ok = False - for pick in self.browse(cr, uid, ids, context=context): - if not pick.move_lines: - return True - for move in pick.move_lines: - if move.state not in ('cancel','done'): - return False - if move.state=='done': - ok = True - return ok - - def test_cancel(self, cr, uid, ids, context=None): - """ Test whether the move lines are canceled or not. - @return: True or False - """ - for pick in self.browse(cr, uid, ids, context=context): - for move in pick.move_lines: - if move.state not in ('cancel',): - return False - return True - - def allow_cancel(self, cr, uid, ids, context=None): - for pick in self.browse(cr, uid, ids, context=context): - if not pick.move_lines: - return True - for move in pick.move_lines: - if move.state == 'done': - raise osv.except_osv(_('Error!'), _('You cannot cancel the picking as some moves have been done. You should cancel remaining moves of this picking.')) + self.pool.get('stock.move').action_done(cr, uid, todo, context=context) return True def unlink(self, cr, uid, ids, context=None): + #on picking deletion, cancel its move then unlink them too move_obj = self.pool.get('stock.move') - if context is None: - context = {} + context = context or {} for pick in self.browse(cr, uid, ids, context=context): - if pick.state in ['done','cancel']: - raise osv.except_osv(_('Error!'), _('You cannot remove the picking which is in %s state!')%(pick.state,)) - else: - ids2 = [move.id for move in pick.move_lines] - ctx = context.copy() - ctx.update({'call_unlink':True}) - if pick.state != 'draft': - #Cancelling the move in order to affect Virtual stock of product - move_obj.action_cancel(cr, uid, ids2, ctx) - #Removing the move - move_obj.unlink(cr, uid, ids2, ctx) - + move_ids = [move.id for move in pick.move_lines] + move_obj.action_cancel(cr, uid, move_ids, context=context) + move_obj.unlink(cr, uid, move_ids, context=context) return super(stock_picking, self).unlink(cr, uid, ids, context=context) - # FIXME: needs refactoring, this code is partially duplicated in stock_move.do_partial()! - def do_partial(self, cr, uid, ids, partial_datas, context=None): - """ Makes partial picking and moves done. - @param partial_datas : Dictionary containing details of partial picking - like partner_id, partner_id, delivery_date, - delivery moves with product_id, product_qty, uom - @return: Dictionary of values + def write(self, cr, uid, ids, vals, context=None): + res = super(stock_picking, self).write(cr, uid, ids, vals, context=context) + #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both + if 'move_lines' in vals or 'pack_operation_ids' in vals: + self.do_recompute_remaining_quantities(cr, uid, ids, context=context) + return res + + def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None): + """ Move all non-done lines into a new backorder picking. If the key 'do_only_split' is given in the context, then move all lines not in context.get('split', []) instead of all non-done lines. """ + if not backorder_moves: + backorder_moves = picking.move_lines + backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')] + if 'do_only_split' in context and context['do_only_split']: + backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])] + + if backorder_move_ids: + backorder_id = self.copy(cr, uid, picking.id, { + 'name': '/', + 'move_lines': [], + 'pack_operation_ids': [], + 'backorder_id': picking.id, + }) + back_order_name = self.browse(cr, uid, backorder_id, context=context).name + self.message_post(cr, uid, picking.id, body=_("Back order %s created.") % (back_order_name), context=context) + move_obj = self.pool.get("stock.move") + move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context) + + self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context) + self.action_confirm(cr, uid, [backorder_id], context=context) + return backorder_id + return False + + def recheck_availability(self, cr, uid, picking_ids, context=None): + self.action_assign(cr, uid, picking_ids, context=context) + self.do_prepare_partial(cr, uid, picking_ids, context=context) + + def _get_top_level_packages(self, cr, uid, quants_suggested_locations, context=None): + """This method searches for the higher level packages that can be moved as a single operation, given a list of quants + to move and their suggested destination, and returns the list of matching packages. + """ + # Try to find as much as possible top-level packages that can be moved + pack_obj = self.pool.get("stock.quant.package") + quant_obj = self.pool.get("stock.quant") + top_lvl_packages = set() + quants_to_compare = quants_suggested_locations.keys() + for pack in list(set([x.package_id for x in quants_suggested_locations.keys() if x and x.package_id])): + loop = True + test_pack = pack + good_pack = False + pack_destination = False + while loop: + pack_quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context) + all_in = True + for quant in quant_obj.browse(cr, uid, pack_quants, context=context): + # If the quant is not in the quants to compare and not in the common location + if not quant in quants_to_compare: + all_in = False + break + else: + #if putaway strat apply, the destination location of each quant may be different (and thus the package should not be taken as a single operation) + if not pack_destination: + pack_destination = quants_suggested_locations[quant] + elif pack_destination != quants_suggested_locations[quant]: + all_in = False + break + if all_in: + good_pack = test_pack + if test_pack.parent_id: + test_pack = test_pack.parent_id + else: + #stop the loop when there's no parent package anymore + loop = False + else: + #stop the loop when the package test_pack is not totally reserved for moves of this picking + #(some quants may be reserved for other picking or not reserved at all) + loop = False + if good_pack: + top_lvl_packages.add(good_pack) + return list(top_lvl_packages) + + def _prepare_pack_ops(self, cr, uid, picking, quants, forced_qties, context=None): + """ returns a list of dict, ready to be used in create() of stock.pack.operation. + + :param picking: browse record (stock.picking) + :param quants: browse record list (stock.quant). List of quants associated to the picking + :param forced_qties: dictionary showing for each product (keys) its corresponding quantity (value) that is not covered by the quants associated to the picking + """ + def _picking_putaway_apply(product): + location = False + # Search putaway strategy + if product_putaway_strats.get(product.id): + location = product_putaway_strats[product.id] + else: + location = self.pool.get('stock.location').get_putaway_strategy(cr, uid, picking.location_dest_id, product, context=context) + product_putaway_strats[product.id] = location + return location or picking.location_dest_id.id + + pack_obj = self.pool.get("stock.quant.package") + quant_obj = self.pool.get("stock.quant") + vals = [] + qtys_grouped = {} + #for each quant of the picking, find the suggested location + quants_suggested_locations = {} + product_putaway_strats = {} + for quant in quants: + if quant.qty <= 0: + continue + suggested_location_id = _picking_putaway_apply(quant.product_id) + quants_suggested_locations[quant] = suggested_location_id + + #find the packages we can movei as a whole + top_lvl_packages = self._get_top_level_packages(cr, uid, quants_suggested_locations, context=context) + # and then create pack operations for the top-level packages found + for pack in top_lvl_packages: + pack_quant_ids = pack_obj.get_content(cr, uid, [pack.id], context=context) + pack_quants = quant_obj.browse(cr, uid, pack_quant_ids, context=context) + vals.append({ + 'picking_id': picking.id, + 'package_id': pack.id, + 'product_qty': 1.0, + 'location_id': pack.location_id.id, + 'location_dest_id': quants_suggested_locations[pack_quants[0]], + }) + #remove the quants inside the package so that they are excluded from the rest of the computation + for quant in pack_quants: + del quants_suggested_locations[quant] + + # Go through all remaining reserved quants and group by product, package, lot, owner, source location and dest location + for quant, dest_location_id in quants_suggested_locations.items(): + key = (quant.product_id.id, quant.package_id.id, quant.lot_id.id, quant.owner_id.id, quant.location_id.id, dest_location_id) + if qtys_grouped.get(key): + qtys_grouped[key] += quant.qty + else: + qtys_grouped[key] = quant.qty + + # Do the same for the forced quantities (in cases of force_assign or incomming shipment for example) + for product, qty in forced_qties.items(): + if qty <= 0: + continue + suggested_location_id = _picking_putaway_apply(product) + key = (product.id, False, False, False, picking.location_id.id, suggested_location_id) + if qtys_grouped.get(key): + qtys_grouped[key] += qty + else: + qtys_grouped[key] = qty + + # Create the necessary operations for the grouped quants and remaining qtys + for key, qty in qtys_grouped.items(): + vals.append({ + 'picking_id': picking.id, + 'product_qty': qty, + 'product_id': key[0], + 'package_id': key[1], + 'lot_id': key[2], + 'owner_id': key[3], + 'location_id': key[4], + 'location_dest_id': key[5], + 'product_uom_id': self.pool.get("product.product").browse(cr, uid, key[0], context=context).uom_id.id, + }) + return vals + + def open_barcode_interface(self, cr, uid, picking_ids, context=None): + final_url="/barcode/web/#action=stock.ui&picking_id="+str(picking_ids[0]) + return {'type': 'ir.actions.act_url', 'url':final_url, 'target': 'self',} + + def do_partial_open_barcode(self, cr, uid, picking_ids, context=None): + self.do_prepare_partial(cr, uid, picking_ids, context=context) + return self.open_barcode_interface(cr, uid, picking_ids, context=context) + + def do_prepare_partial(self, cr, uid, picking_ids, context=None): + context = context or {} + pack_operation_obj = self.pool.get('stock.pack.operation') + #used to avoid recomputing the remaining quantities at each new pack operation created + ctx = context.copy() + ctx['no_recompute'] = True + + #get list of existing operations and delete them + existing_package_ids = pack_operation_obj.search(cr, uid, [('picking_id', 'in', picking_ids)], context=context) + if existing_package_ids: + pack_operation_obj.unlink(cr, uid, existing_package_ids, context) + for picking in self.browse(cr, uid, picking_ids, context=context): + forced_qties = {} # Quantity remaining after calculating reserved quants + picking_quants = [] + #Calculate packages, reserved quants, qtys of this picking's moves + for move in picking.move_lines: + if move.state not in ('assigned', 'confirmed'): + continue + move_quants = move.reserved_quant_ids + picking_quants += move_quants + forced_qty = (move.state == 'assigned') and move.product_qty - sum([x.qty for x in move_quants]) or 0 + #if we used force_assign() on the move, or if the move is incomming, forced_qty > 0 + if forced_qty: + if forced_qties.get(move.product_id): + forced_qties[move.product_id] += forced_qty + else: + forced_qties[move.product_id] = forced_qty + for vals in self._prepare_pack_ops(cr, uid, picking, picking_quants, forced_qties, context=context): + pack_operation_obj.create(cr, uid, vals, context=ctx) + #recompute the remaining quantities all at once + self.do_recompute_remaining_quantities(cr, uid, picking_ids, context=context) + self.write(cr, uid, picking_ids, {'recompute_pack_op': False}, context=context) + + def do_unreserve(self, cr, uid, picking_ids, context=None): + """ + Will remove all quants for picking in picking_ids + """ + moves_to_unreserve = [] + pack_line_to_unreserve = [] + for picking in self.browse(cr, uid, picking_ids, context=context): + moves_to_unreserve += [m.id for m in picking.move_lines if m.state not in ('done', 'cancel')] + pack_line_to_unreserve += [p.id for p in picking.pack_operation_ids] + if moves_to_unreserve: + if pack_line_to_unreserve: + self.pool.get('stock.pack.operation').unlink(cr, uid, pack_line_to_unreserve, context=context) + self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context) + + def recompute_remaining_qty(self, cr, uid, picking, context=None): + def _create_link_for_index(operation_id, index, product_id, qty_to_assign, quant_id=False): + move_dict = prod2move_ids[product_id][index] + qty_on_link = min(move_dict['remaining_qty'], qty_to_assign) + self.pool.get('stock.move.operation.link').create(cr, uid, {'move_id': move_dict['move'].id, 'operation_id': operation_id, 'qty': qty_on_link, 'reserved_quant_id': quant_id}, context=context) + if move_dict['remaining_qty'] == qty_on_link: + prod2move_ids[product_id].pop(index) + else: + move_dict['remaining_qty'] -= qty_on_link + return qty_on_link + + def _create_link_for_quant(operation_id, quant, qty): + """create a link for given operation and reserved move of given quant, for the max quantity possible, and returns this quantity""" + if not quant.reservation_id.id: + return _create_link_for_product(operation_id, quant.product_id.id, qty) + qty_on_link = 0 + for i in range(0, len(prod2move_ids[quant.product_id.id])): + if prod2move_ids[quant.product_id.id][i]['move'].id != quant.reservation_id.id: + continue + qty_on_link = _create_link_for_index(operation_id, i, quant.product_id.id, qty, quant_id=quant.id) + break + return qty_on_link + + def _create_link_for_product(operation_id, product_id, qty): + '''method that creates the link between a given operation and move(s) of given product, for the given quantity. + Returns True if it was possible to create links for the requested quantity (False if there was not enough quantity on stock moves)''' + qty_to_assign = qty + if prod2move_ids.get(product_id): + while prod2move_ids[product_id] and qty_to_assign > 0: + qty_on_link = _create_link_for_index(operation_id, 0, product_id, qty_to_assign, quant_id=False) + qty_to_assign -= qty_on_link + return qty_to_assign == 0 + + uom_obj = self.pool.get('product.uom') + package_obj = self.pool.get('stock.quant.package') + quant_obj = self.pool.get('stock.quant') + quants_in_package_done = set() + prod2move_ids = {} + still_to_do = [] + #make a dictionary giving for each product, the moves and related quantity that can be used in operation links + for move in picking.move_lines: + if not prod2move_ids.get(move.product_id.id): + prod2move_ids[move.product_id.id] = [{'move': move, 'remaining_qty': move.product_qty}] + else: + prod2move_ids[move.product_id.id].append({'move': move, 'remaining_qty': move.product_qty}) + + need_rereserve = False + #sort the operations in order to give higher priority to those with a package, then a serial number + operations = picking.pack_operation_ids + operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0)) + #delete existing operations to start again from scratch + cr.execute("DELETE FROM stock_move_operation_link WHERE operation_id in %s", (tuple([x.id for x in operations]),)) + + #1) first, try to create links when quants can be identified without any doubt + for ops in operations: + #for each operation, create the links with the stock move by seeking on the matching reserved quants, + #and deffer the operation if there is some ambiguity on the move to select + if ops.package_id and not ops.product_id: + #entire package + quant_ids = package_obj.get_content(cr, uid, [ops.package_id.id], context=context) + for quant in quant_obj.browse(cr, uid, quant_ids, context=context): + remaining_qty_on_quant = quant.qty + if quant.reservation_id: + #avoid quants being counted twice + quants_in_package_done.add(quant.id) + qty_on_link = _create_link_for_quant(ops.id, quant, quant.qty) + remaining_qty_on_quant -= qty_on_link + if remaining_qty_on_quant: + still_to_do.append((ops, quant.product_id.id, remaining_qty_on_quant)) + need_rereserve = True + elif ops.product_id.id: + #Check moves with same product + qty_to_assign = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context) + for move_dict in prod2move_ids.get(ops.product_id.id, []): + move = move_dict['move'] + for quant in move.reserved_quant_ids: + if not qty_to_assign > 0: + break + if quant.id in quants_in_package_done: + continue + + #check if the quant is matching the operation details + if ops.package_id: + flag = quant.package_id and bool(package_obj.search(cr, uid, [('id', 'child_of', [ops.package_id.id]), ('id', '=', quant.package_id.id)], context=context)) or False + else: + flag = not quant.package_id.id + flag = flag and ((ops.lot_id and ops.lot_id.id == quant.lot_id.id) or not ops.lot_id) + flag = flag and (ops.owner_id.id == quant.owner_id.id) + if flag: + max_qty_on_link = min(quant.qty, qty_to_assign) + qty_on_link = _create_link_for_quant(ops.id, quant, max_qty_on_link) + qty_to_assign -= qty_on_link + if qty_to_assign > 0: + #qty reserved is less than qty put in operations. We need to create a link but it's deferred after we processed + #all the quants (because they leave no choice on their related move and needs to be processed with higher priority) + still_to_do += [(ops, ops.product_id.id, qty_to_assign)] + need_rereserve = True + + #2) then, process the remaining part + all_op_processed = True + for ops, product_id, remaining_qty in still_to_do: + all_op_processed = all_op_processed and _create_link_for_product(ops.id, product_id, remaining_qty) + return (need_rereserve, all_op_processed) + + def picking_recompute_remaining_quantities(self, cr, uid, picking, context=None): + need_rereserve = False + all_op_processed = True + if picking.pack_operation_ids: + need_rereserve, all_op_processed = self.recompute_remaining_qty(cr, uid, picking, context=context) + return need_rereserve, all_op_processed + + def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None): + for picking in self.browse(cr, uid, picking_ids, context=context): + if picking.pack_operation_ids: + self.recompute_remaining_qty(cr, uid, picking, context=context) + + def _create_extra_moves(self, cr, uid, picking, context=None): + '''This function creates move lines on a picking, at the time of do_transfer, based on + unexpected product transfers (or exceeding quantities) found in the pack operations. + ''' + move_obj = self.pool.get('stock.move') + operation_obj = self.pool.get('stock.pack.operation') + for op in picking.pack_operation_ids: + for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items(): + if remaining_qty > 0: + product = self.pool.get('product.product').browse(cr, uid, product_id, context=context) + vals = { + 'picking_id': picking.id, + 'location_id': picking.location_id.id, + 'location_dest_id': picking.location_dest_id.id, + 'product_id': product_id, + 'product_uom': product.uom_id.id, + 'product_uom_qty': remaining_qty, + 'name': _('Extra Move: ') + product.name, + 'state': 'confirmed', + } + move_obj.create(cr, uid, vals, context=context) + + def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None): + """ Unreserve quants then try to reassign quants.""" + stock_move_obj = self.pool.get('stock.move') + if not move_ids: + self.do_unreserve(cr, uid, [picking.id], context=context) + self.action_assign(cr, uid, [picking.id], context=context) + else: + stock_move_obj.do_unreserve(cr, uid, move_ids, context=context) + stock_move_obj.action_assign(cr, uid, move_ids, context=context) + + def do_transfer(self, cr, uid, picking_ids, context=None): + """ + If no pack operation, we do simple action_done of the picking + Otherwise, do the pack operations + """ + if not context: + context = {} + stock_move_obj = self.pool.get('stock.move') + for picking in self.browse(cr, uid, picking_ids, context=context): + if not picking.pack_operation_ids: + self.action_done(cr, uid, [picking.id], context=context) + continue + else: + need_rereserve, all_op_processed = self.picking_recompute_remaining_quantities(cr, uid, picking, context=context) + #create extra moves in the picking (unexpected product moves coming from pack operations) + if not all_op_processed: + self._create_extra_moves(cr, uid, picking, context=context) + picking.refresh() + #split move lines eventually + todo_move_ids = [] + toassign_move_ids = [] + for move in picking.move_lines: + remaining_qty = move.remaining_qty + if move.state in ('done', 'cancel'): + #ignore stock moves cancelled or already done + continue + elif move.state == 'draft': + toassign_move_ids.append(move.id) + if remaining_qty == 0: + if move.state in ('draft', 'assigned', 'confirmed'): + todo_move_ids.append(move.id) + elif remaining_qty > 0 and remaining_qty < move.product_qty: + new_move = stock_move_obj.split(cr, uid, move, remaining_qty, context=context) + todo_move_ids.append(move.id) + #Assign move as it was assigned before + toassign_move_ids.append(new_move) + if (need_rereserve or not all_op_processed) and not picking.location_id.usage in ("supplier", "production", "inventory"): + self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context) + self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context) + if todo_move_ids and not context.get('do_only_split'): + self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context) + elif context.get('do_only_split'): + context.update({'split': todo_move_ids}) + picking.refresh() + self._create_backorder(cr, uid, picking, context=context) + if toassign_move_ids: + stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context) + return True + + def do_split(self, cr, uid, picking_ids, context=None): + """ just split the picking (create a backorder) without making it 'done' """ if context is None: context = {} - else: - context = dict(context) - res = {} - move_obj = self.pool.get('stock.move') + ctx = context.copy() + ctx['do_only_split'] = True + return self.do_transfer(cr, uid, picking_ids, context=ctx) + + def get_next_picking_for_ui(self, cr, uid, context=None): + """ returns the next pickings to process. Used in the barcode scanner UI""" + if context is None: + context = {} + domain = [('state', 'in', ('assigned', 'partially_available'))] + if context.get('default_picking_type_id'): + domain.append(('picking_type_id', '=', context['default_picking_type_id'])) + return self.search(cr, uid, domain, context=context) + + def action_done_from_ui(self, cr, uid, picking_id, context=None): + """ called when button 'done' is pushed in the barcode scanner UI """ + #write qty_done into field product_qty for every package_operation before doing the transfer + pack_op_obj = self.pool.get('stock.pack.operation') + for operation in self.browse(cr, uid, picking_id, context=context).pack_operation_ids: + pack_op_obj.write(cr, uid, operation.id, {'product_qty': operation.qty_done}, context=context) + self.do_transfer(cr, uid, [picking_id], context=context) + #return id of next picking to work on + return self.get_next_picking_for_ui(cr, uid, context=context) + + def action_pack(self, cr, uid, picking_ids, operation_filter_ids=None, context=None): + """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack. + Used in the barcode scanner UI and the normal interface as well. + operation_filter_ids is used by barcode scanner interface to specify a subset of operation to pack""" + if operation_filter_ids == None: + operation_filter_ids = [] + stock_operation_obj = self.pool.get('stock.pack.operation') + package_obj = self.pool.get('stock.quant.package') + stock_move_obj = self.pool.get('stock.move') + for picking_id in picking_ids: + operation_search_domain = [('picking_id', '=', picking_id), ('result_package_id', '=', False)] + if operation_filter_ids != []: + operation_search_domain.append(('id', 'in', operation_filter_ids)) + operation_ids = stock_operation_obj.search(cr, uid, operation_search_domain, context=context) + pack_operation_ids = [] + if operation_ids: + for operation in stock_operation_obj.browse(cr, uid, operation_ids, context=context): + #If we haven't done all qty in operation, we have to split into 2 operation + op = operation + if (operation.qty_done < operation.product_qty): + new_operation = stock_operation_obj.copy(cr, uid, operation.id, {'product_qty': operation.qty_done,'qty_done': operation.qty_done}, context=context) + stock_operation_obj.write(cr, uid, operation.id, {'product_qty': operation.product_qty - operation.qty_done,'qty_done': 0}, context=context) + op = stock_operation_obj.browse(cr, uid, new_operation, context=context) + pack_operation_ids.append(op.id) + for record in op.linked_move_operation_ids: + stock_move_obj.check_tracking(cr, uid, record.move_id, op.package_id.id or op.lot_id.id, context=context) + package_id = package_obj.create(cr, uid, {}, context=context) + stock_operation_obj.write(cr, uid, pack_operation_ids, {'result_package_id': package_id}, context=context) + return True + + def process_product_id_from_ui(self, cr, uid, picking_id, product_id, op_id, increment=True, context=None): + return self.pool.get('stock.pack.operation')._search_and_increment(cr, uid, picking_id, [('product_id', '=', product_id),('id', '=', op_id)], increment=increment, context=context) + + def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, visible_op_ids, context=None): + '''This function is called each time there barcode scanner reads an input''' + lot_obj = self.pool.get('stock.production.lot') + package_obj = self.pool.get('stock.quant.package') product_obj = self.pool.get('product.product') - currency_obj = self.pool.get('res.currency') - uom_obj = self.pool.get('product.uom') - sequence_obj = self.pool.get('ir.sequence') - for pick in self.browse(cr, uid, ids, context=context): - new_picking = None - complete, too_many, too_few = [], [], [] - move_product_qty, prodlot_ids, product_avail, partial_qty, product_uoms = {}, {}, {}, {}, {} - for move in pick.move_lines: - if move.state in ('done', 'cancel'): - continue - partial_data = partial_datas.get('move%s'%(move.id), {}) - product_qty = partial_data.get('product_qty',0.0) - move_product_qty[move.id] = product_qty - product_uom = partial_data.get('product_uom',False) - product_price = partial_data.get('product_price',0.0) - product_currency = partial_data.get('product_currency',False) - prodlot_id = partial_data.get('prodlot_id') - prodlot_ids[move.id] = prodlot_id - product_uoms[move.id] = product_uom - partial_qty[move.id] = uom_obj._compute_qty(cr, uid, product_uoms[move.id], product_qty, move.product_uom.id) - if move.product_qty == partial_qty[move.id]: - complete.append(move) - elif move.product_qty > partial_qty[move.id]: - too_few.append(move) - else: - too_many.append(move) - - # Average price computation - if (pick.type == 'in') and (move.product_id.cost_method == 'average'): - product = product_obj.browse(cr, uid, move.product_id.id) - move_currency_id = move.company_id.currency_id.id - context['currency_id'] = move_currency_id - qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id) - - if product.id not in product_avail: - # keep track of stock on hand including processed lines not yet marked as done - product_avail[product.id] = product.qty_available - - if qty > 0: - new_price = currency_obj.compute(cr, uid, product_currency, - move_currency_id, product_price, round=False) - new_price = uom_obj._compute_price(cr, uid, product_uom, new_price, - product.uom_id.id) - if product_avail[product.id] <= 0: - product_avail[product.id] = 0 - new_std_price = new_price - else: - # Get the standard price - amount_unit = product.price_get('standard_price', context=context)[product.id] - new_std_price = ((amount_unit * product_avail[product.id])\ - + (new_price * qty))/(product_avail[product.id] + qty) - # Write the field according to price type field - product_obj.write(cr, uid, [product.id], {'standard_price': new_std_price}) - - # Record the values that were chosen in the wizard, so they can be - # used for inventory valuation if real-time valuation is enabled. - move_obj.write(cr, uid, [move.id], - {'price_unit': product_price, - 'price_currency_id': product_currency}) - - product_avail[product.id] += qty - - - - for move in too_few: - product_qty = move_product_qty[move.id] - if not new_picking: - new_picking_name = pick.name - self.write(cr, uid, [pick.id], - {'name': sequence_obj.get(cr, uid, - 'stock.picking.%s'%(pick.type)), - }) - new_picking = self.copy(cr, uid, pick.id, - { - 'name': new_picking_name, - 'move_lines' : [], - 'state':'draft', - }) - if product_qty != 0: - defaults = { - 'product_qty' : product_qty, - 'product_uos_qty': product_qty, #TODO: put correct uos_qty - 'picking_id' : new_picking, - 'state': 'assigned', - 'move_dest_id': False, - 'price_unit': move.price_unit, - 'product_uom': product_uoms[move.id] - } - prodlot_id = prodlot_ids[move.id] - if prodlot_id: - defaults.update(prodlot_id=prodlot_id) - move_obj.copy(cr, uid, move.id, defaults) - move_obj.write(cr, uid, [move.id], - { - 'product_qty': move.product_qty - partial_qty[move.id], - 'product_uos_qty': move.product_qty - partial_qty[move.id], #TODO: put correct uos_qty - 'prodlot_id': False, - 'tracking_id': False, - }) - - if new_picking: - move_obj.write(cr, uid, [c.id for c in complete], {'picking_id': new_picking}) - for move in complete: - defaults = {'product_uom': product_uoms[move.id], 'product_qty': move_product_qty[move.id]} - if prodlot_ids.get(move.id): - defaults.update({'prodlot_id': prodlot_ids[move.id]}) - move_obj.write(cr, uid, [move.id], defaults) - for move in too_many: - product_qty = move_product_qty[move.id] - defaults = { - 'product_qty' : product_qty, - 'product_uos_qty': product_qty, #TODO: put correct uos_qty - 'product_uom': product_uoms[move.id] - } - prodlot_id = prodlot_ids.get(move.id) - if prodlot_ids.get(move.id): - defaults.update(prodlot_id=prodlot_id) - if new_picking: - defaults.update(picking_id=new_picking) - move_obj.write(cr, uid, [move.id], defaults) - - # At first we confirm the new picking (if necessary) - if new_picking: - self.signal_button_confirm(cr, uid, [new_picking]) - # Then we finish the good picking - self.write(cr, uid, [pick.id], {'backorder_id': new_picking}) - self.action_move(cr, uid, [new_picking], context=context) - self.signal_button_done(cr, uid, [new_picking]) - workflow.trg_write(uid, 'stock.picking', pick.id, cr) - delivered_pack_id = pick.id - back_order_name = self.browse(cr, uid, delivered_pack_id, context=context).name - self.message_post(cr, uid, new_picking, body=_("Back order %s has been created.") % (back_order_name), context=context) - else: - self.action_move(cr, uid, [pick.id], context=context) - self.signal_button_done(cr, uid, [pick.id]) - delivered_pack_id = pick.id - - delivered_pack = self.browse(cr, uid, delivered_pack_id, context=context) - res[pick.id] = {'delivered_picking': delivered_pack.id or False} - - return res - - # views associated to each picking type - _VIEW_LIST = { - 'out': 'view_picking_out_form', - 'in': 'view_picking_in_form', - 'internal': 'view_picking_form', - } - def _get_view_id(self, cr, uid, type): - """Get the view id suiting the given type - - @param type: the picking type as a string - @return: view i, or False if no view found - """ - res = self.pool.get('ir.model.data').get_object_reference(cr, uid, - 'stock', self._VIEW_LIST.get(type, 'view_picking_form')) - return res and res[1] or False + stock_operation_obj = self.pool.get('stock.pack.operation') + stock_location_obj = self.pool.get('stock.location') + answer = {'filter_loc': False, 'operation_id': False} + #check if the barcode correspond to a location + matching_location_ids = stock_location_obj.search(cr, uid, [('loc_barcode', '=', barcode_str)], context=context) + if matching_location_ids: + #if we have a location, return immediatly with the location name + location = stock_location_obj.browse(cr, uid, matching_location_ids[0], context=None) + answer['filter_loc'] = stock_location_obj._name_get(cr, uid, location, context=None) + answer['filter_loc_id'] = matching_location_ids[0] + return answer + #check if the barcode correspond to a product + matching_product_ids = product_obj.search(cr, uid, ['|', ('ean13', '=', barcode_str), ('default_code', '=', barcode_str)], context=context) + if matching_product_ids: + op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', matching_product_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context) + answer['operation_id'] = op_id + return answer + #check if the barcode correspond to a lot + matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context) + if matching_lot_ids: + lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context) + op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', lot.product_id.id), ('lot_id', '=', lot.id)], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context) + answer['operation_id'] = op_id + return answer + #check if the barcode correspond to a package + matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context) + if matching_package_ids: + op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context) + answer['operation_id'] = op_id + return answer + return answer class stock_production_lot(osv.osv): - - def name_get(self, cr, uid, ids, context=None): - if not ids: - return [] - reads = self.read(cr, uid, ids, ['name', 'prefix', 'ref'], context) - res = [] - for record in reads: - name = record['name'] - prefix = record['prefix'] - if prefix: - name = prefix + '/' + name - if record['ref']: - name = '%s [%s]' % (name, record['ref']) - res.append((record['id'], name)) - return res - - def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): - args = args or [] - ids = [] - if name: - ids = self.search(cr, uid, [('prefix', '=', name)] + args, limit=limit, context=context) - if not ids: - ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context) - else: - ids = self.search(cr, uid, args, limit=limit, context=context) - return self.name_get(cr, uid, ids, context) - _name = 'stock.production.lot' - _description = 'Serial Number' - - def _get_stock(self, cr, uid, ids, field_name, arg, context=None): - """ Gets stock of products for locations - @return: Dictionary of values - """ - if context is None: - context = {} - if 'location_id' not in context: - locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context) - else: - locations = context['location_id'] and [context['location_id']] or [] - - if isinstance(ids, (int, long)): - ids = [ids] - - res = {}.fromkeys(ids, 0.0) - if locations: - cr.execute('''select - prodlot_id, - sum(qty) - from - stock_report_prodlots - where - location_id IN %s and prodlot_id IN %s group by prodlot_id''',(tuple(locations),tuple(ids),)) - res.update(dict(cr.fetchall())) - - return res - - def _stock_search(self, cr, uid, obj, name, args, context=None): - """ Searches Ids of products - @return: Ids of locations - """ - locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')]) - cr.execute('''select - prodlot_id, - sum(qty) - from - stock_report_prodlots - where - location_id IN %s group by prodlot_id - having sum(qty) '''+ str(args[0][1]) + str(args[0][2]),(tuple(locations),)) - res = cr.fetchall() - ids = [('id', 'in', map(lambda x: x[0], res))] - return ids - + _inherit = ['mail.thread'] + _description = 'Lot/Serial' _columns = { - 'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number, will be displayed as: PREFIX/SERIAL [INT_REF]"), + 'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number"), 'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"), - 'prefix': fields.char('Prefix', size=64, help="Optional prefix to prepend when displaying this serial number: PREFIX/SERIAL [INT_REF]"), 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]), - 'date': fields.datetime('Creation Date', required=True), - 'stock_available': fields.function(_get_stock, fnct_search=_stock_search, type="float", string="Available", select=True, - help="Current quantity of products with this Serial Number available in company warehouses", - digits_compute=dp.get_precision('Product Unit of Measure')), - 'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'), - 'company_id': fields.many2one('res.company', 'Company', select=True), - 'move_ids': fields.one2many('stock.move', 'prodlot_id', 'Moves for this serial number', readonly=True), + 'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants', readonly=True), + 'create_date': fields.datetime('Creation Date'), } _defaults = { - 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'), 'product_id': lambda x, y, z, c: c.get('product_id', False), } _sql_constraints = [ ('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'), ] + def action_traceability(self, cr, uid, ids, context=None): - """ It traces the information of a product + """ It traces the information of lots @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @@ -1491,82 +1438,42 @@ class stock_production_lot(osv.osv): @param context: A standard dictionary @return: A dictionary of values """ - value=self.pool.get('action.traceability').action_traceability(cr,uid,ids,context) - return value - - def copy(self, cr, uid, id, default=None, context=None): - context = context or {} - default = default and default.copy() or {} - default.update(date=time.strftime('%Y-%m-%d %H:%M:%S'), move_ids=[]) - return super(stock_production_lot, self).copy(cr, uid, id, default=default, context=context) - - -class stock_production_lot_revision(osv.osv): - _name = 'stock.production.lot.revision' - _description = 'Serial Number Revision' - - _columns = { - 'name': fields.char('Revision Name', size=64, required=True), - 'description': fields.text('Description'), - 'date': fields.date('Revision Date'), - 'indice': fields.char('Revision Number', size=16), - 'author_id': fields.many2one('res.users', 'Author'), - 'lot_id': fields.many2one('stock.production.lot', 'Serial Number', select=True, ondelete='cascade'), - 'company_id': fields.related('lot_id','company_id',type='many2one',relation='res.company',string='Company', store=True, readonly=True), - } - - _defaults = { - 'author_id': lambda x, y, z, c: z, - 'date': fields.date.context_today, - } + quant_obj = self.pool.get("stock.quant") + quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context) + moves = set() + for quant in quant_obj.browse(cr, uid, quants, context=context): + moves |= {move.id for move in quant.history_ids} + if moves: + return { + 'domain': "[('id','in',[" + ','.join(map(str, list(moves))) + "])]", + 'name': _('Traceability'), + 'view_mode': 'tree,form', + 'view_type': 'form', + 'context': {'tree_view_ref': 'stock.view_move_tree'}, + 'res_model': 'stock.move', + 'type': 'ir.actions.act_window', + } + return False # ---------------------------------------------------- # Move # ---------------------------------------------------- -# -# Fields: -# location_dest_id is only used for predicting futur stocks -# class stock_move(osv.osv): - - def _getSSCC(self, cr, uid, context=None): - cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,)) - res = cr.fetchone() - return (res and res[0]) or False - _name = "stock.move" _description = "Stock Move" _order = 'date_expected desc, id' _log_create = False - def action_partial_move(self, cr, uid, ids, context=None): - if context is None: context = {} - if context.get('active_model') != self._name: - context.update(active_ids=ids, active_model=self._name) - partial_id = self.pool.get("stock.partial.move").create( - cr, uid, {}, context=context) - return { - 'name':_("Products to Process"), - 'view_mode': 'form', - 'view_id': False, - 'view_type': 'form', - 'res_model': 'stock.partial.move', - 'res_id': partial_id, - 'type': 'ir.actions.act_window', - 'nodestroy': True, - 'target': 'new', - 'domain': '[]', - 'context': context - } - + def get_price_unit(self, cr, uid, move, context=None): + """ Returns the unit price to store on the quant """ + return move.price_unit or move.product_id.standard_price def name_get(self, cr, uid, ids, context=None): res = [] for line in self.browse(cr, uid, ids, context=context): - name = line.location_id.name+' > '+line.location_dest_id.name - # optional prefixes + name = line.location_id.name + ' > ' + line.location_dest_id.name if line.product_id.code: name = line.product_id.code + ': ' + name if line.picking_id.origin: @@ -1574,42 +1481,129 @@ class stock_move(osv.osv): res.append((line.id, name)) return res - def _check_tracking(self, cr, uid, ids, context=None): - """ Checks if serial number is assigned to stock move or not. - @return: True or False - """ - for move in self.browse(cr, uid, ids, context=context): - if not move.prodlot_id and \ - (move.state == 'done' and \ - ( \ - (move.product_id.track_production and move.location_id.usage == 'production') or \ - (move.product_id.track_production and move.location_dest_id.usage == 'production') or \ - (move.product_id.track_incoming and move.location_id.usage == 'supplier') or \ - (move.product_id.track_outgoing and move.location_dest_id.usage == 'customer') or \ - (move.product_id.track_incoming and move.location_id.usage == 'inventory') \ - )): - return False - return True + def create(self, cr, uid, vals, context=None): + if vals.get('product_id') and not vals.get('price_unit'): + prod_obj = self.pool.get('product.product') + vals['price_unit'] = prod_obj.browse(cr, uid, vals['product_id'], context=context).standard_price + return super(stock_move, self).create(cr, uid, vals, context=context) - def _check_product_lot(self, cr, uid, ids, context=None): - """ Checks whether move is done or not and production lot is assigned to that move. - @return: True or False - """ + def _quantity_normalize(self, cr, uid, ids, name, args, context=None): + uom_obj = self.pool.get('product.uom') + res = {} + for m in self.browse(cr, uid, ids, context=context): + res[m.id] = uom_obj._compute_qty_obj(cr, uid, m.product_uom, m.product_uom_qty, m.product_id.uom_id, round=False, context=context) + return res + + def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None): + uom_obj = self.pool.get('product.uom') + res = {} for move in self.browse(cr, uid, ids, context=context): - if move.prodlot_id and move.state == 'done' and (move.prodlot_id.product_id.id != move.product_id.id): - return False - return True + qty = move.product_qty + for record in move.linked_move_operation_ids: + qty -= record.qty + #converting the remaining quantity in the move UoM + res[move.id] = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom, round=False, context=context) + return res + + def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None): + res = dict.fromkeys(ids, False) + for move in self.browse(cr, uid, ids, context=context): + if move.state == 'done': + res[move.id] = [q.id for q in move.quant_ids] + else: + res[move.id] = [q.id for q in move.reserved_quant_ids] + return res + + def _get_product_availability(self, cr, uid, ids, field_name, args, context=None): + quant_obj = self.pool.get('stock.quant') + res = dict.fromkeys(ids, False) + for move in self.browse(cr, uid, ids, context=context): + if move.state == 'done': + res[move.id] = move.product_qty + else: + sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context) + quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context) + availability = 0 + for quant in quant_obj.browse(cr, uid, quant_ids, context=context): + availability += quant.qty + res[move.id] = min(move.product_qty, availability) + return res + + def _get_string_qty_information(self, cr, uid, ids, field_name, args, context=None): + settings_obj = self.pool.get('stock.config.settings') + uom_obj = self.pool.get('product.uom') + res = dict.fromkeys(ids, '') + for move in self.browse(cr, uid, ids, context=context): + if move.state in ('draft', 'done', 'cancel') or move.location_id.usage != 'internal': + res[move.id] = '' # 'not applicable' or 'n/a' could work too + continue + total_available = min(move.product_qty, move.reserved_availability + move.availability) + total_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, total_available, move.product_uom, context=context) + info = str(total_available) + #look in the settings if we need to display the UoM name or not + config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context) + if config_ids: + stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context) + if stock_settings.group_uom: + info += ' ' + move.product_uom.name + if move.reserved_availability: + if move.reserved_availability != total_available: + #some of the available quantity is assigned and some are available but not reserved + reserved_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, move.reserved_availability, move.product_uom, context=context) + info += _(' (%s reserved)') % str(reserved_available) + else: + #all available quantity is assigned + info += _(' (reserved)') + res[move.id] = info + return res + + def _get_reserved_availability(self, cr, uid, ids, field_name, args, context=None): + res = dict.fromkeys(ids, 0) + for move in self.browse(cr, uid, ids, context=context): + res[move.id] = sum([quant.qty for quant in move.reserved_quant_ids]) + return res + + def _get_move(self, cr, uid, ids, context=None): + res = set() + for quant in self.browse(cr, uid, ids, context=context): + if quant.reservation_id: + res.add(quant.reservation_id.id) + return list(res) + + def _get_move_ids(self, cr, uid, ids, context=None): + res = [] + for picking in self.browse(cr, uid, ids, context=context): + res += [x.id for x in picking.move_lines] + return res + + def _get_moves_from_prod(self, cr, uid, ids, context=None): + if ids: + return self.pool.get('stock.move').search(cr, uid, [('product_id', 'in', ids)], context=context) + return [] + + def _set_product_qty(self, cr, uid, id, field, value, arg, context=None): + """ The meaning of product_qty field changed lately and is now a functional field computing the quantity + in the default product UoM. This code has been added to raise an error if a write is made given a value + for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to + detect errors. + """ + raise osv.except_osv(_('Programming Error!'), _('The requested operation cannot be processed because of a programming error setting the `product_qty` field instead of the `product_uom_qty`.')) _columns = { 'name': fields.char('Description', required=True, select=True), 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'), 'create_date': fields.datetime('Creation Date', readonly=True, select=True), 'date': fields.datetime('Date', required=True, select=True, help="Move date: scheduled date until move is done, then date of actual move processing", states={'done': [('readonly', True)]}), - 'date_expected': fields.datetime('Scheduled Date', states={'done': [('readonly', True)]},required=True, select=True, help="Scheduled date for the processing of this move"), - 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type','<>','service')],states={'done': [('readonly', True)]}), - - 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), - required=True,states={'done': [('readonly', True)]}, + 'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"), + 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}), + 'product_qty': fields.function(_quantity_normalize, fnct_inv=_set_product_qty, _type='float', store={ + 'stock.move': (lambda self, cr, uid, ids, ctx: ids, ['product_id', 'product_uom_qty', 'product_uom'], 20), + 'product.product': (_get_moves_from_prod, ['uom_id'], 20), + }, string='Quantity', + digits_compute=dp.get_precision('Product Unit of Measure'), + help='Quantity in the default UoM of the product'), + 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), + required=True, states={'done': [('readonly', True)]}, help="This is the quantity of products from an inventory " "point of view. For moves in the state 'done', this is the " "quantity of products that were actually moved. For other " @@ -1618,24 +1612,23 @@ class stock_move(osv.osv): "backorder. Changing this quantity on assigned moves affects " "the product reservation, and should be done with care." ), - 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True,states={'done': [('readonly', True)]}), + 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}), 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}), 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}), - 'product_packaging': fields.many2one('product.packaging', 'Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."), - 'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True,states={'done': [('readonly', True)]}, help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations."), - 'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True,states={'done': [('readonly', True)]}, select=True, help="Location where the system will stock the finished products."), + 'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."), + + 'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True, states={'done': [('readonly', True)]}, help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations."), + 'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True, states={'done': [('readonly', True)]}, select=True, help="Location where the system will stock the finished products."), + 'partner_id': fields.many2one('res.partner', 'Destination Address ', states={'done': [('readonly', True)]}, help="Optional address where goods are to be delivered, specifically used for allotment"), - 'prodlot_id': fields.many2one('stock.production.lot', 'Serial Number', states={'done': [('readonly', True)]}, help="Serial number is used to put a serial number on the production", select=True), - 'tracking_id': fields.many2one('stock.tracking', 'Pack', select=True, states={'done': [('readonly', True)]}, help="Logistical shipping unit: pallet, box, pack ..."), - - 'auto_validate': fields.boolean('Auto Validate'), 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True), - 'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History (child moves)'), - 'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History (parent moves)'), - 'picking_id': fields.many2one('stock.picking', 'Reference', select=True,states={'done': [('readonly', True)]}), + 'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True), + + 'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}), + 'picking_priority': fields.related('picking_id', 'priority', type='selection', selection=[('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Picking Priority', store={'stock.picking': (_get_move_ids, ['priority'], 10)}), 'note': fields.text('Notes'), 'state': fields.selection([('draft', 'New'), ('cancel', 'Cancelled'), @@ -1649,200 +1642,220 @@ class stock_move(osv.osv): "* Waiting Availability: This state is reached when the procurement resolution is not straight forward. It may need the scheduler to run, a component to me manufactured...\n"\ "* Available: When products are reserved, it is set to \'Available\'.\n"\ "* Done: When the shipment is processed, the state is \'Done\'."), - 'price_unit': fields.float('Unit Price', digits_compute= dp.get_precision('Product Price'), help="Technical field used to record the product cost set by the user during a picking confirmation (when average price costing method is used)"), - 'price_currency_id': fields.many2one('res.currency', 'Currency for average price', help="Technical field used to record the currency chosen by the user during a picking confirmation (when average price costing method is used)"), + 'partially_available': fields.boolean('Partially Available', readonly=True, help="Checks if the move has some stock reserved"), + 'price_unit': fields.float('Unit Price', help="Technical field used to record the product cost set by the user during a picking confirmation (when costing method used is 'average price' or 'real'). Value given in company currency and in product uom."), # as it's a technical field, we intentionally don't provide the digits attribute + 'company_id': fields.many2one('res.company', 'Company', required=True, select=True), - 'backorder_id': fields.related('picking_id','backorder_id',type='many2one', relation="stock.picking", string="Back Order of", select=True), - 'origin': fields.related('picking_id','origin',type='char', size=64, relation="stock.picking", string="Source", store=True), + 'split_from': fields.many2one('stock.move', string="Move Split From", help="Technical field used to track the origin of a split move, which can be useful in case of debug"), + 'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True), + 'origin': fields.char("Source"), + 'procure_method': fields.selection([('make_to_stock', 'Default: Take From Stock'), ('make_to_order', 'Advanced: Apply Procurement Rules')], 'Supply Method', required=True, + help="""By default, the system will take from the stock in the source location and passively wait for availability. The other possibility allows you to directly create a procurement on the source location (and thus ignore its current stock) to gather products. If we want to chain moves and have this one to wait for the previous, this second option should be chosen."""), # used for colors in tree views: - 'scrapped': fields.related('location_dest_id','scrap_location',type='boolean',relation='stock.location',string='Scrapped', readonly=True), - 'type': fields.related('picking_id', 'type', type='selection', selection=[('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], string='Shipping Type'), + 'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True), + + 'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'), + 'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'), + 'linked_move_operation_ids': fields.one2many('stock.move.operation.link', 'move_id', string='Linked Operations', readonly=True, help='Operations that impact this move for the computation of the remaining quantities'), + 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity', + digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},), + 'procurement_id': fields.many2one('procurement.order', 'Procurement'), + 'group_id': fields.many2one('procurement.group', 'Procurement Group'), + 'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'), + 'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'), + 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'), + 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'), + 'inventory_id': fields.many2one('stock.inventory', 'Inventory'), + 'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.quant', string='Lots'), + 'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move'), + 'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'), + 'reserved_availability': fields.function(_get_reserved_availability, type='float', string='Quantity Reserved', readonly=True, help='Quantity that has already been reserved for this move'), + 'availability': fields.function(_get_product_availability, type='float', string='Quantity Available', readonly=True, help='Quantity in stock that can still be reserved for this move'), + 'string_availability_info': fields.function(_get_string_qty_information, type='text', string='Availability', readonly=True, help='Show various information on stock availability for this move'), + 'restrict_lot_id': fields.many2one('stock.production.lot', 'Lot', help="Technical field used to depict a restriction on the lot of quants to consider when marking this move as 'done'"), + 'restrict_partner_id': fields.many2one('res.partner', 'Owner ', help="Technical field used to depict a restriction on the ownership of quants to consider when marking this move as 'done'"), + 'route_ids': fields.many2many('stock.location.route', 'stock_location_route_move', 'move_id', 'route_id', 'Destination route', help="Preferred route to be followed by the procurement order"), + 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', help="Technical field depicting the warehouse to consider for the route selection on the next procurement (if any)."), } - def _check_location(self, cr, uid, ids, context=None): - for record in self.browse(cr, uid, ids, context=context): - if (record.state=='done') and (record.location_id.usage == 'view'): - raise osv.except_osv(_('Error'), _('You cannot move product %s from a location of type view %s.')% (record.product_id.name, record.location_id.name)) - if (record.state=='done') and (record.location_dest_id.usage == 'view' ): - raise osv.except_osv(_('Error'), _('You cannot move product %s to a location of type view %s.')% (record.product_id.name, record.location_dest_id.name)) - return True - - _constraints = [ - (_check_tracking, - 'You must assign a serial number for this product.', - ['prodlot_id']), - (_check_location, 'You cannot move products from or to a location of the type view.', - ['location_id','location_dest_id']), - (_check_product_lot, - 'You try to assign a lot which is not from the same product.', - ['prodlot_id'])] - def _default_location_destination(self, cr, uid, context=None): - """ Gets default address of partner for destination location - @return: Address id or False - """ - mod_obj = self.pool.get('ir.model.data') - picking_type = context.get('picking_type') - location_id = False - if context is None: - context = {} - if context.get('move_line', []): - if context['move_line'][0]: - if isinstance(context['move_line'][0], (tuple, list)): - location_id = context['move_line'][0][2] and context['move_line'][0][2].get('location_dest_id',False) - else: - move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id']) - location_id = move_list and move_list['location_dest_id'][0] or False - elif context.get('address_out_id', False): - property_out = self.pool.get('res.partner').browse(cr, uid, context['address_out_id'], context).property_stock_customer - location_id = property_out and property_out.id or False - else: - location_xml_id = False - if picking_type in ('in', 'internal'): - location_xml_id = 'stock_location_stock' - elif picking_type == 'out': - location_xml_id = 'stock_location_customers' - if location_xml_id: - try: - location_model, location_id = mod_obj.get_object_reference(cr, uid, 'stock', location_xml_id) - with tools.mute_logger('openerp.osv.orm'): - self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context) - except (orm.except_orm, ValueError): - location_id = False - - return location_id + context = context or {} + if context.get('default_picking_type_id', False): + pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context) + return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False + return False def _default_location_source(self, cr, uid, context=None): - """ Gets default address of partner for source location - @return: Address id or False - """ - mod_obj = self.pool.get('ir.model.data') - picking_type = context.get('picking_type') - location_id = False - - if context is None: - context = {} - if context.get('move_line', []): - try: - location_id = context['move_line'][0][2]['location_id'] - except: - pass - elif context.get('address_in_id', False): - part_obj_add = self.pool.get('res.partner').browse(cr, uid, context['address_in_id'], context=context) - if part_obj_add: - location_id = part_obj_add.property_stock_supplier.id - else: - location_xml_id = False - if picking_type == 'in': - location_xml_id = 'stock_location_suppliers' - elif picking_type in ('out', 'internal'): - location_xml_id = 'stock_location_stock' - if location_xml_id: - try: - location_model, location_id = mod_obj.get_object_reference(cr, uid, 'stock', location_xml_id) - with tools.mute_logger('openerp.osv.orm'): - self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context) - except (orm.except_orm, ValueError): - location_id = False - - return location_id + context = context or {} + if context.get('default_picking_type_id', False): + pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context) + return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False + return False def _default_destination_address(self, cr, uid, context=None): user = self.pool.get('res.users').browse(cr, uid, uid, context=context) return user.company_id.partner_id.id - def _default_move_type(self, cr, uid, context=None): - """ Gets default type of move - @return: type - """ - if context is None: - context = {} - picking_type = context.get('picking_type') - type = 'internal' - if picking_type == 'in': - type = 'in' - elif picking_type == 'out': - type = 'out' - return type - _defaults = { 'location_id': _default_location_source, 'location_dest_id': _default_location_destination, 'partner_id': _default_destination_address, - 'type': _default_move_type, 'state': 'draft', 'priority': '1', - 'product_qty': 1.0, - 'scrapped' : False, - 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), - 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c), - 'date_expected': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), + 'product_uom_qty': 1.0, + 'scrapped': False, + 'date': fields.datetime.now, + 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c), + 'date_expected': fields.datetime.now, + 'procure_method': 'make_to_stock', + 'propagate': True, } - def write(self, cr, uid, ids, vals, context=None): - if isinstance(ids, (int, long)): - ids = [ids] - if uid != 1: - frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id']) - for move in self.browse(cr, uid, ids, context=context): - if move.state == 'done': - if frozen_fields.intersection(vals): - raise osv.except_osv(_('Operation Forbidden!'), - _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).')) - return super(stock_move, self).write(cr, uid, ids, vals, context=context) + def _check_uom(self, cr, uid, ids, context=None): + for move in self.browse(cr, uid, ids, context=context): + if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id: + return False + return True + + _constraints = [ + (_check_uom, + 'You try to move a product using a UoM that is not compatible with the UoM of the product moved. Please use an UoM in the same UoM category.', + ['product_uom']), + ] def copy_data(self, cr, uid, id, default=None, context=None): if default is None: default = {} default = default.copy() - default.setdefault('tracking_id', False) - default.setdefault('prodlot_id', False) - default.setdefault('move_history_ids', []) - default.setdefault('move_history_ids2', []) - return super(stock_move, self).copy_data(cr, uid, id, default, context=context) + default['move_orig_ids'] = [] + default['quant_ids'] = [] + default['move_dest_id'] = False + default['reserved_quant_ids'] = [] + default['returned_move_ids'] = [] + default['linked_move_operation_ids'] = [] + default['partially_available'] = False + if not default.get('origin_returned_move_id'): + default['origin_returned_move_id'] = False + default['state'] = 'draft' + return super(stock_move, self).copy_data(cr, uid, id, default, context) - def _auto_init(self, cursor, context=None): - res = super(stock_move, self)._auto_init(cursor, context=context) - cursor.execute('SELECT indexname \ - FROM pg_indexes \ - WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'') - if not cursor.fetchone(): - cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \ - ON stock_move (product_id, state, location_id, location_dest_id)') - return res + def do_unreserve(self, cr, uid, move_ids, context=None): + quant_obj = self.pool.get("stock.quant") + for move in self.browse(cr, uid, move_ids, context=context): + if move.state in ('done', 'cancel'): + raise osv.except_osv(_('Operation Forbidden!'), _('Cannot unreserve a done move')) + quant_obj.quants_unreserve(cr, uid, move, context=context) + if self.find_move_ancestors(cr, uid, move, context=context): + self.write(cr, uid, [move.id], {'state': 'waiting'}, context=context) + else: + self.write(cr, uid, [move.id], {'state': 'confirmed'}, context=context) - def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, - loc_id=False, product_id=False, uom_id=False, context=None): - """ On change of production lot gives a warning message. - @param prodlot_id: Changed production lot id - @param product_qty: Quantity of product - @param loc_id: Location id - @param product_id: Product id - @return: Warning message - """ - if not prodlot_id or not loc_id: - return {} - ctx = context and context.copy() or {} - ctx['location_id'] = loc_id - ctx.update({'raise-exception': True}) - uom_obj = self.pool.get('product.uom') - product_obj = self.pool.get('product.product') - product_uom = product_obj.browse(cr, uid, product_id, context=ctx).uom_id - prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, context=ctx) - location = self.pool.get('stock.location').browse(cr, uid, loc_id, context=ctx) - uom = uom_obj.browse(cr, uid, uom_id, context=ctx) - amount_actual = uom_obj._compute_qty_obj(cr, uid, product_uom, prodlot.stock_available, uom, context=ctx) - warning = {} - if (location.usage == 'internal') and (product_qty > (amount_actual or 0.0)): - warning = { - 'title': _('Insufficient Stock for Serial Number !'), - 'message': _('You are moving %.2f %s but only %.2f %s available for this serial number.') % (product_qty, uom.name, amount_actual, uom.name) - } - return {'warning': warning} + def _prepare_procurement_from_move(self, cr, uid, move, context=None): + origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or "/") + group_id = move.group_id and move.group_id.id or False + if move.rule_id: + if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id: + group_id = move.rule_id.group_id.id + elif move.rule_id.group_propagation_option == 'none': + group_id = False + return { + 'name': move.rule_id and move.rule_id.name or "/", + 'origin': origin, + 'company_id': move.company_id and move.company_id.id or False, + 'date_planned': move.date, + 'product_id': move.product_id.id, + 'product_qty': move.product_qty, + 'product_uom': move.product_uom.id, + 'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty, + 'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id, + 'location_id': move.location_id.id, + 'move_dest_id': move.id, + 'group_id': group_id, + 'route_ids': [(4, x.id) for x in move.route_ids], + 'warehouse_id': move.warehouse_id and move.warehouse_id.id or False, + } - def onchange_quantity(self, cr, uid, ids, product_id, product_qty, - product_uom, product_uos): + def _push_apply(self, cr, uid, moves, context=None): + push_obj = self.pool.get("stock.location.path") + for move in moves: + #1) if the move is already chained, there is no need to check push rules + #2) if the move is a returned move, we don't want to check push rules, as returning a returned move is the only decent way + # to receive goods without triggering the push rules again (which would duplicate chained operations) + if not move.move_dest_id and not move.origin_returned_move_id: + domain = [('location_from_id', '=', move.location_dest_id.id)] + #priority goes to the route defined on the product and product category + route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids] + rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context) + if not rules: + #then we search on the warehouse if a rule can apply + wh_route_ids = [] + if move.warehouse_id: + wh_route_ids = [x.id for x in move.warehouse_id.route_ids] + elif move.picking_type_id and move.picking_type_id.warehouse_id: + wh_route_ids = [x.id for x in move.picking_type_id.warehouse_id.route_ids] + if wh_route_ids: + rules = push_obj.search(cr, uid, domain + [('route_id', 'in', wh_route_ids)], order='route_sequence, sequence', context=context) + if not rules: + #if no specialized push rule has been found yet, we try to find a general one + rules = push_obj.search(cr, uid, domain, order='route_sequence, sequence', context=context) + if rules: + rule = push_obj.browse(cr, uid, rules[0], context=context) + push_obj._apply(cr, uid, rule, move, context=context) + return True + + def _create_procurement(self, cr, uid, move, context=None): + """ This will create a procurement order """ + return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context)) + + def write(self, cr, uid, ids, vals, context=None): + if context is None: + context = {} + if isinstance(ids, (int, long)): + ids = [ids] + # Check that we do not modify a stock.move which is done + frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id']) + for move in self.browse(cr, uid, ids, context=context): + if move.state == 'done': + if frozen_fields.intersection(vals): + raise osv.except_osv(_('Operation Forbidden!'), + _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).')) + propagated_changes_dict = {} + #propagation of quantity change + if vals.get('product_uom_qty'): + propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty'] + if vals.get('product_uom_id'): + propagated_changes_dict['product_uom_id'] = vals['product_uom_id'] + #propagation of expected date: + propagated_date_field = False + if vals.get('date_expected'): + #propagate any manual change of the expected date + propagated_date_field = 'date_expected' + elif (vals.get('state', '') == 'done' and vals.get('date')): + #propagate also any delta observed when setting the move as done + propagated_date_field = 'date' + + if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict): + #any propagation is (maybe) needed + for move in self.browse(cr, uid, ids, context=context): + if move.move_dest_id and move.propagate: + if 'date_expected' in propagated_changes_dict: + propagated_changes_dict.pop('date_expected') + if propagated_date_field: + current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT) + delta = new_date - current_date + if abs(delta.days) >= move.company_id.propagation_minimum_delta: + old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT) + propagated_changes_dict['date_expected'] = new_move_date + #For pushed moves as well as for pulled moves, propagate by recursive call of write(). + #Note that, for pulled moves we intentionally don't propagate on the procurement. + if propagated_changes_dict: + self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context) + return super(stock_move, self).write(cr, uid, ids, vals, context=context) + + def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos): """ On change of product quantity finds UoM and UoS quantities @param product_id: Product id @param product_qty: Changed Quantity of product @@ -1851,26 +1864,26 @@ class stock_move(osv.osv): @return: Dictionary of values """ result = { - 'product_uos_qty': 0.00 - } + 'product_uos_qty': 0.00 + } warning = {} - if (not product_id) or (product_qty <=0.0): + if (not product_id) or (product_qty <= 0.0): result['product_qty'] = 0.0 return {'value': result} product_obj = self.pool.get('product.product') uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff']) - - # Warn if the quantity was decreased + + # Warn if the quantity was decreased if ids: for move in self.read(cr, uid, ids, ['product_qty']): if product_qty < move['product_qty']: warning.update({ - 'title': _('Information'), - 'message': _("By changing this quantity here, you accept the " + 'title': _('Information'), + 'message': _("By changing this quantity here, you accept the " "new quantity as complete: OpenERP will not " - "automatically generate a back order.") }) + "automatically generate a back order.")}) break if product_uos and product_uom and (product_uom != product_uos): @@ -1890,35 +1903,34 @@ class stock_move(osv.osv): @return: Dictionary of values """ result = { - 'product_qty': 0.00 - } + 'product_uom_qty': 0.00 + } warning = {} - if (not product_id) or (product_uos_qty <=0.0): + if (not product_id) or (product_uos_qty <= 0.0): result['product_uos_qty'] = 0.0 return {'value': result} product_obj = self.pool.get('product.product') uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff']) - - # Warn if the quantity was decreased + + # Warn if the quantity was decreased for move in self.read(cr, uid, ids, ['product_uos_qty']): if product_uos_qty < move['product_uos_qty']: warning.update({ - 'title': _('Warning: No Back Order'), - 'message': _("By changing the quantity here, you accept the " + 'title': _('Warning: No Back Order'), + 'message': _("By changing the quantity here, you accept the " "new quantity as complete: OpenERP will not " - "automatically generate a Back Order.") }) + "automatically generate a Back Order.")}) break if product_uos and product_uom and (product_uom != product_uos): - result['product_qty'] = product_uos_qty / uos_coeff['uos_coeff'] + result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff'] else: - result['product_qty'] = product_uos_qty + result['product_uom_qty'] = product_uos_qty return {'value': result, 'warning': warning} - def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, - loc_dest_id=False, partner_id=False): + def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False): """ On change of product id, if finds UoM, UoS, quantity and UoS quantity. @param prod_id: Changed Product id @param loc_id: Source location id @@ -1937,13 +1949,12 @@ class stock_move(osv.osv): ctx = {'lang': lang} product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0] - uos_id = product.uos_id and product.uos_id.id or False + uos_id = product.uos_id and product.uos_id.id or False result = { 'product_uom': product.uom_id.id, 'product_uos': uos_id, - 'product_qty': 1.00, - 'product_uos_qty' : self.pool.get('stock.move').onchange_quantity(cr, uid, ids, prod_id, 1.00, product.uom_id.id, uos_id)['value']['product_uos_qty'], - 'prodlot_id' : False, + 'product_uom_qty': 1.00, + 'product_uos_qty': self.pool.get('stock.move').onchange_quantity(cr, uid, ids, prod_id, 1.00, product.uom_id.id, uos_id)['value']['product_uos_qty'], } if not ids: result['name'] = product.partner_ref @@ -1953,33 +1964,29 @@ class stock_move(osv.osv): result['location_dest_id'] = loc_dest_id return {'value': result} - def onchange_move_type(self, cr, uid, ids, type, context=None): - """ On change of move type gives sorce and destination location. - @param type: Move Type - @return: Dictionary of values + def _picking_assign(self, cr, uid, move_ids, procurement_group, location_from, location_to, context=None): + """Assign a picking on the given move_ids, which is a list of move supposed to share the same procurement_group, location_from and location_to + (and company). Those attributes are also given as parameters. """ - mod_obj = self.pool.get('ir.model.data') - location_source_id = 'stock_location_stock' - location_dest_id = 'stock_location_stock' - if type == 'in': - location_source_id = 'stock_location_suppliers' - location_dest_id = 'stock_location_stock' - elif type == 'out': - location_source_id = 'stock_location_stock' - location_dest_id = 'stock_location_customers' - try: - source_location = mod_obj.get_object_reference(cr, uid, 'stock', location_source_id) - with tools.mute_logger('openerp.osv.orm'): - self.pool.get('stock.location').check_access_rule(cr, uid, [source_location[1]], 'read', context=context) - except (orm.except_orm, ValueError): - source_location = False - try: - dest_location = mod_obj.get_object_reference(cr, uid, 'stock', location_dest_id) - with tools.mute_logger('openerp.osv.orm'): - self.pool.get('stock.location').check_access_rule(cr, uid, [dest_location[1]], 'read', context=context) - except (orm.except_orm, ValueError): - dest_location = False - return {'value':{'location_id': source_location and source_location[1] or False, 'location_dest_id': dest_location and dest_location[1] or False}} + pick_obj = self.pool.get("stock.picking") + picks = pick_obj.search(cr, uid, [ + ('group_id', '=', procurement_group), + ('location_id', '=', location_from), + ('location_dest_id', '=', location_to), + ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context) + if picks: + pick = picks[0] + else: + move = self.browse(cr, uid, move_ids, context=context)[0] + values = { + 'origin': move.origin, + 'company_id': move.company_id and move.company_id.id or False, + 'move_type': move.group_id and move.group_id.move_type or 'one', + 'partner_id': move.partner_id.id or False, + 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False, + } + pick = pick_obj.create(cr, uid, values, context=context) + return self.write(cr, uid, move_ids, {'picking_id': pick}, context=context) def onchange_date(self, cr, uid, ids, date, date_expected, context=None): """ On change of Scheduled Date gives a Move date. @@ -1988,510 +1995,306 @@ class stock_move(osv.osv): @return: Move Date """ if not date_expected: - date_expected = time.strftime('%Y-%m-%d %H:%M:%S') - return {'value':{'date': date_expected}} + date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + return {'value': {'date': date_expected}} - def _chain_compute(self, cr, uid, moves, context=None): - """ Finds whether the location has chained location type or not. - @param moves: Stock moves - @return: Dictionary containing destination location with chained location type. - """ - result = {} - for m in moves: - dest = self.pool.get('stock.location').chained_location_get( - cr, - uid, - m.location_dest_id, - m.picking_id and m.picking_id.partner_id and m.picking_id.partner_id, - m.product_id, - context - ) - if dest: - if dest[1] == 'transparent': - newdate = (datetime.strptime(m.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d') - self.write(cr, uid, [m.id], { - 'date': newdate, - 'location_dest_id': dest[0].id}) - if m.picking_id and (dest[3] or dest[5]): - self.pool.get('stock.picking').write(cr, uid, [m.picking_id.id], { - 'stock_journal_id': dest[3] or m.picking_id.stock_journal_id.id, - 'type': dest[5] or m.picking_id.type - }, context=context) - m.location_dest_id = dest[0] - res2 = self._chain_compute(cr, uid, [m], context=context) - for pick_id in res2.keys(): - result.setdefault(pick_id, []) - result[pick_id] += res2[pick_id] - else: - result.setdefault(m.picking_id, []) - result[m.picking_id].append( (m, dest) ) - return result - - def _prepare_chained_picking(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None): - """Prepare the definition (values) to create a new chained picking. - - :param str picking_name: desired new picking name - :param browse_record picking: source picking (being chained to) - :param str picking_type: desired new picking type - :param list moves_todo: specification of the stock moves to be later included in this - picking, in the form:: - - [[move, (dest_location, auto_packing, chained_delay, chained_journal, - chained_company_id, chained_picking_type)], - ... - ] - - See also :meth:`stock_location.chained_location_get`. - """ - res_company = self.pool.get('res.company') - return { - 'name': picking_name, - 'origin': tools.ustr(picking.origin or ''), - 'type': picking_type, - 'note': picking.note, - 'move_type': picking.move_type, - 'auto_picking': moves_todo[0][1][1] == 'auto', - 'stock_journal_id': moves_todo[0][1][3], - 'company_id': moves_todo[0][1][4] or res_company._company_default_get(cr, uid, 'stock.company', context=context), - 'partner_id': picking.partner_id.id, - 'invoice_state': 'none', - 'date': picking.date, - } - - def _create_chained_picking(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None): - picking_obj = self.pool.get('stock.picking') - return picking_obj.create(cr, uid, self._prepare_chained_picking(cr, uid, picking_name, picking, picking_type, moves_todo, context=context)) - - def create_chained_picking(self, cr, uid, moves, context=None): - res_obj = self.pool.get('res.company') - location_obj = self.pool.get('stock.location') - move_obj = self.pool.get('stock.move') - new_moves = [] - if context is None: - context = {} - seq_obj = self.pool.get('ir.sequence') - for picking, chained_moves in self._chain_compute(cr, uid, moves, context=context).items(): - # We group the moves by automatic move type, so it creates different pickings for different types - moves_by_type = {} - for move in chained_moves: - moves_by_type.setdefault(move[1][1], []).append(move) - for todo in moves_by_type.values(): - ptype = todo[0][1][5] and todo[0][1][5] or location_obj.picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0]) - if picking: - # name of new picking according to its type - if ptype == 'internal': - new_pick_name = seq_obj.get(cr, uid,'stock.picking') - else : - new_pick_name = seq_obj.get(cr, uid, 'stock.picking.' + ptype) - pickid = self._create_chained_picking(cr, uid, new_pick_name, picking, ptype, todo, context=context) - # Need to check name of old picking because it always considers picking as "OUT" when created from Sales Order - old_ptype = location_obj.picking_type_get(cr, uid, picking.move_lines[0].location_id, picking.move_lines[0].location_dest_id) - if old_ptype != picking.type: - old_pick_name = seq_obj.get(cr, uid, 'stock.picking.' + old_ptype) - self.pool.get('stock.picking').write(cr, uid, [picking.id], {'name': old_pick_name, 'type': old_ptype}, context=context) - else: - pickid = False - for move, (loc, dummy, delay, dummy, company_id, ptype, invoice_state) in todo: - new_id = move_obj.copy(cr, uid, move.id, { - 'location_id': move.location_dest_id.id, - 'location_dest_id': loc.id, - 'date': time.strftime('%Y-%m-%d'), - 'picking_id': pickid, - 'state': 'waiting', - 'company_id': company_id or res_obj._company_default_get(cr, uid, 'stock.company', context=context) , - 'move_history_ids': [], - 'date_expected': (datetime.strptime(move.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'), - 'move_history_ids2': []} - ) - move_obj.write(cr, uid, [move.id], { - 'move_dest_id': new_id, - 'move_history_ids': [(4, new_id)] - }) - new_moves.append(self.browse(cr, uid, [new_id])[0]) - if pickid: - self.pool.get('stock.picking').signal_button_confirm(cr, uid, [pickid]) - if new_moves: - new_moves += self.create_chained_picking(cr, uid, new_moves, context) - return new_moves def action_confirm(self, cr, uid, ids, context=None): - """ Confirms stock move. + """ Confirms stock move or put it in waiting if it's linked to another move. @return: List of ids. """ - moves = self.browse(cr, uid, ids, context=context) - self.write(cr, uid, ids, {'state': 'confirmed'}) - self.create_chained_picking(cr, uid, moves, context) - return [] + if isinstance(ids, (int, long)): + ids = [ids] + states = { + 'confirmed': [], + 'waiting': [] + } + to_assign = {} + for move in self.browse(cr, uid, ids, context=context): + state = 'confirmed' + #if the move is preceeded, then it's waiting (if preceeding move is done, then action_assign has been called already and its state is already available) + if move.move_orig_ids: + state = 'waiting' + #if the move is split and some of the ancestor was preceeded, then it's waiting as well + elif move.split_from: + move2 = move.split_from + while move2 and state != 'waiting': + if move2.move_orig_ids: + state = 'waiting' + move2 = move2.split_from + states[state].append(move.id) - def action_assign(self, cr, uid, ids, *args): - """ Changes state to confirmed or waiting. - @return: List of values - """ - todo = [] - for move in self.browse(cr, uid, ids): - if move.state in ('confirmed', 'waiting'): - todo.append(move.id) - res = self.check_assign(cr, uid, todo) - return res + if not move.picking_id and move.picking_type_id: + key = (move.group_id.id, move.location_id.id, move.location_dest_id.id) + if key not in to_assign: + to_assign[key] = [] + to_assign[key].append(move.id) + + for move in self.browse(cr, uid, states['confirmed'], context=context): + if move.procure_method == 'make_to_order': + self._create_procurement(cr, uid, move, context=context) + states['waiting'].append(move.id) + states['confirmed'].remove(move.id) + + for state, write_ids in states.items(): + if len(write_ids): + self.write(cr, uid, write_ids, {'state': state}) + #assign picking in batch for all confirmed move that share the same details + for key, move_ids in to_assign.items(): + procurement_group, location_from, location_to = key + self._picking_assign(cr, uid, move_ids, procurement_group, location_from, location_to, context=context) + moves = self.browse(cr, uid, ids, context=context) + self._push_apply(cr, uid, moves, context=context) + return ids def force_assign(self, cr, uid, ids, context=None): """ Changes the state to assigned. @return: True """ - self.write(cr, uid, ids, {'state': 'assigned'}) - for move in self.browse(cr, uid, ids, context): - if move.picking_id: - workflow.trg_write(uid, 'stock.picking', move.picking_id.id, cr) - return True + return self.write(cr, uid, ids, {'state': 'assigned'}, context=context) - def cancel_assign(self, cr, uid, ids, context=None): - """ Changes the state to confirmed. - @return: True + def check_tracking(self, cr, uid, move, lot_id, context=None): + """ Checks if serial number is assigned to stock move or not and raise an error if it had to. """ - self.write(cr, uid, ids, {'state': 'confirmed'}) + check = False + if move.product_id.track_all and not move.location_dest_id.usage == 'inventory': + check = True + elif move.product_id.track_incoming and move.location_id.usage in ('supplier', 'transit', 'inventory') and move.location_dest_id.usage == 'internal': + check = True + elif move.product_id.track_outgoing and move.location_dest_id.usage in ('customer', 'transit') and move.location_id.usage == 'internal': + check = True + if check and not lot_id: + raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (move.product_id.name)) - # fix for bug lp:707031 - # called write of related picking because changing move availability does - # not trigger workflow of picking in order to change the state of picking - for move in self.browse(cr, uid, ids, context): - if move.picking_id: - workflow.trg_write(uid, 'stock.picking', move.picking_id.id, cr) - return True - - # - # Duplicate stock.move - # - def check_assign(self, cr, uid, ids, context=None): + def action_assign(self, cr, uid, ids, context=None): """ Checks the product type and accordingly writes the state. - @return: No. of moves done """ - done = [] - count = 0 - pickings = {} - if context is None: - context = {} + context = context or {} + quant_obj = self.pool.get("stock.quant") + to_assign_moves = [] + main_domain = {} + todo_moves = [] + operations = set() for move in self.browse(cr, uid, ids, context=context): - if move.product_id.type == 'consu' or move.location_id.usage == 'supplier': - if move.state in ('confirmed', 'waiting'): - done.append(move.id) - pickings[move.picking_id.id] = 1 + if move.state not in ('confirmed', 'waiting', 'assigned'): + continue + if move.location_id.usage in ('supplier', 'inventory', 'production'): + to_assign_moves.append(move.id) + #in case the move is returned, we want to try to find quants before forcing the assignment + if not move.origin_returned_move_id: + continue + if move.product_id.type == 'consu': + to_assign_moves.append(move.id) continue - if move.state in ('confirmed', 'waiting'): - # Important: we must pass lock=True to _product_reserve() to avoid race conditions and double reservations - res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id}, lock=True) - if res: - #_product_available_test depends on the next status for correct functioning - #the test does not work correctly if the same product occurs multiple times - #in the same order. This is e.g. the case when using the button 'split in two' of - #the stock outgoing form - self.write(cr, uid, [move.id], {'state':'assigned'}) - done.append(move.id) - pickings[move.picking_id.id] = 1 - r = res.pop(0) - product_uos_qty = self.pool.get('stock.move').onchange_quantity(cr, uid, ids, move.product_id.id, r[0], move.product_id.uom_id.id, move.product_id.uos_id.id)['value']['product_uos_qty'] - cr.execute('update stock_move set location_id=%s, product_qty=%s, product_uos_qty=%s where id=%s', (r[1], r[0],product_uos_qty, move.id)) - - while res: - r = res.pop(0) - product_uos_qty = self.pool.get('stock.move').onchange_quantity(cr, uid, ids, move.product_id.id, r[0], move.product_id.uom_id.id, move.product_id.uos_id.id)['value']['product_uos_qty'] - move_id = self.copy(cr, uid, move.id, {'product_uos_qty': product_uos_qty, 'product_qty': r[0], 'location_id': r[1]}) - done.append(move_id) - if done: - count += len(done) - self.write(cr, uid, done, {'state': 'assigned'}) - - if count: - for pick_id in pickings: - workflow.trg_write(uid, 'stock.picking', pick_id, cr) - return count - - def setlast_tracking(self, cr, uid, ids, context=None): - tracking_obj = self.pool.get('stock.tracking') - picking = self.browse(cr, uid, ids, context=context)[0].picking_id - if picking: - last_track = [line.tracking_id.id for line in picking.move_lines if line.tracking_id] - if not last_track: - last_track = tracking_obj.create(cr, uid, {}, context=context) else: - last_track.sort() - last_track = last_track[-1] - self.write(cr, uid, ids, {'tracking_id': last_track}) - return True + todo_moves.append(move) + + #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only + main_domain[move.id] = [('reservation_id', '=', False), ('qty', '>', 0)] + + #if the move is preceeded, restrict the choice of quants in the ones moved previously in original move + ancestors = self.find_move_ancestors(cr, uid, move, context=context) + if move.state == 'waiting' and not ancestors: + #if the waiting move hasn't yet any ancestor (PO/MO not confirmed yet), don't find any quant available in stock + main_domain[move.id] += [('id', '=', False)] + elif ancestors: + main_domain[move.id] += [('history_ids', 'in', ancestors)] + + #if the move is returned from another, restrict the choice of quants to the ones that follow the returned move + if move.origin_returned_move_id: + main_domain[move.id] += [('history_ids', 'in', move.origin_returned_move_id.id)] + for link in move.linked_move_operation_ids: + operations.add(link.operation_id) + # Check all ops and sort them: we want to process first the packages, then operations with lot then the rest + operations = list(operations) + operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0)) + for ops in operations: + #first try to find quants based on specific domains given by linked operations + for record in ops.linked_move_operation_ids: + move = record.move_id + if move.id in main_domain: + domain = main_domain[move.id] + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context) + qty = record.qty + if qty: + quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, qty, domain=domain, prefered_domain_list=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context) + quant_obj.quants_reserve(cr, uid, quants, move, record, context=context) + for move in todo_moves: + move.refresh() + #then if the move isn't totally assigned, try to find quants without any specific domain + if move.state != 'assigned': + qty_already_assigned = move.reserved_availability + qty = move.product_qty - qty_already_assigned + quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain[move.id], prefered_domain_list=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context) + quant_obj.quants_reserve(cr, uid, quants, move, context=context) + + #force assignation of consumable products and incoming from supplier/inventory/production + if to_assign_moves: + self.force_assign(cr, uid, to_assign_moves, context=context) - # - # Cancel move => cancel others move and pickings - # def action_cancel(self, cr, uid, ids, context=None): """ Cancels the moves and if all moves are cancelled it cancels the picking. @return: True """ - if not len(ids): - return True - if context is None: - context = {} - pickings = set() + procurement_obj = self.pool.get('procurement.order') + context = context or {} for move in self.browse(cr, uid, ids, context=context): - if move.state in ('confirmed', 'waiting', 'assigned', 'draft'): - if move.picking_id: - pickings.add(move.picking_id.id) - if move.move_dest_id and move.move_dest_id.state == 'waiting': - self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context) - if context.get('call_unlink',False) and move.move_dest_id.picking_id: - workflow.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr) - self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context) - if not context.get('call_unlink',False): - for pick in self.pool.get('stock.picking').browse(cr, uid, list(pickings), context=context): - if all(move.state == 'cancel' for move in pick.move_lines): - self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'}, context=context) + if move.state == 'done': + raise osv.except_osv(_('Operation Forbidden!'), + _('You cannot cancel a stock move that has been set to \'Done\'.')) + if move.reserved_quant_ids: + self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context) + if context.get('cancel_procurement'): + if move.propagate: + procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context) + procurement_obj.cancel(cr, uid, procurement_ids, context=context) + elif move.move_dest_id: + #cancel chained moves + if move.propagate: + self.action_cancel(cr, uid, [move.move_dest_id.id], context=context) + # If we have a long chain of moves to be cancelled, it is easier for the user to handle + # only the last procurement which will go into exception, instead of all procurements + # along the chain going into exception. We need to check if there are no split moves not cancelled however + if move.procurement_id: + proc = move.procurement_id + if all([x.state == 'cancel' for x in proc.move_ids if x.id != move.id]): + procurement_obj.write(cr, uid, [proc.id], {'state': 'cancel'}) - for id in ids: - workflow.trg_trigger(uid, 'stock.move', id, cr) - return True + elif move.move_dest_id.state == 'waiting': + self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context) + return self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context) - def _get_accounting_data_for_valuation(self, cr, uid, move, context=None): - """ - Return the accounts and journal to use to post Journal Entries for the real-time - valuation of the move. + def _check_package_from_moves(self, cr, uid, ids, context=None): + pack_obj = self.pool.get("stock.quant.package") + packs = set() + for move in self.browse(cr, uid, ids, context=context): + packs |= set([q.package_id for q in move.quant_ids if q.package_id and q.qty > 0]) + return pack_obj._check_location_constraint(cr, uid, list(packs), context=context) - :param context: context dictionary that can explicitly mention the company to consider via the 'force_company' key - :raise: osv.except_osv() is any mandatory account or journal is not defined. - """ - product_obj=self.pool.get('product.product') - accounts = product_obj.get_product_accounts(cr, uid, move.product_id.id, context) - if move.location_id.valuation_out_account_id: - acc_src = move.location_id.valuation_out_account_id.id - else: - acc_src = accounts['stock_account_input'] + def find_move_ancestors(self, cr, uid, move, context=None): + '''Find the first level ancestors of given move ''' + ancestors = [] + move2 = move + while move2: + ancestors += [x.id for x in move2.move_orig_ids] + #loop on the split_from to find the ancestor of split moves only if the move has not direct ancestor (priority goes to them) + move2 = not move2.move_orig_ids and move2.split_from or False + return ancestors - if move.location_dest_id.valuation_in_account_id: - acc_dest = move.location_dest_id.valuation_in_account_id.id - else: - acc_dest = accounts['stock_account_output'] - - acc_valuation = accounts.get('property_stock_valuation_account_id', False) - journal_id = accounts['stock_journal'] - - if acc_dest == acc_valuation: - raise osv.except_osv(_('Error!'), _('Cannot create Journal Entry, Output Account of this product and Valuation account on category of this product are same.')) - - if acc_src == acc_valuation: - raise osv.except_osv(_('Error!'), _('Cannot create Journal Entry, Input Account of this product and Valuation account on category of this product are same.')) - - if not acc_src: - raise osv.except_osv(_('Error!'), _('Please define stock input account for this product or its category: "%s" (id: %d)') % \ - (move.product_id.name, move.product_id.id,)) - if not acc_dest: - raise osv.except_osv(_('Error!'), _('Please define stock output account for this product or its category: "%s" (id: %d)') % \ - (move.product_id.name, move.product_id.id,)) - if not journal_id: - raise osv.except_osv(_('Error!'), _('Please define journal on the product category: "%s" (id: %d)') % \ - (move.product_id.categ_id.name, move.product_id.categ_id.id,)) - if not acc_valuation: - raise osv.except_osv(_('Error!'), _('Please define inventory valuation account on the product category: "%s" (id: %d)') % \ - (move.product_id.categ_id.name, move.product_id.categ_id.id,)) - return journal_id, acc_src, acc_dest, acc_valuation - - def _get_reference_accounting_values_for_valuation(self, cr, uid, move, context=None): - """ - Return the reference amount and reference currency representing the inventory valuation for this move. - These reference values should possibly be converted before being posted in Journals to adapt to the primary - and secondary currencies of the relevant accounts. - """ - product_uom_obj = self.pool.get('product.uom') - - # by default the reference currency is that of the move's company - reference_currency_id = move.company_id.currency_id.id - - default_uom = move.product_id.uom_id.id - qty = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom) - - # if product is set to average price and a specific value was entered in the picking wizard, - # we use it - if move.location_dest_id.usage != 'internal' and move.product_id.cost_method == 'average': - reference_amount = qty * move.product_id.standard_price - elif move.product_id.cost_method == 'average' and move.price_unit: - reference_amount = qty * move.price_unit - reference_currency_id = move.price_currency_id.id or reference_currency_id - - # Otherwise we default to the company's valuation price type, considering that the values of the - # valuation field are expressed in the default currency of the move's company. - else: - if context is None: - context = {} - currency_ctx = dict(context, currency_id = move.company_id.currency_id.id) - amount_unit = move.product_id.price_get('standard_price', context=currency_ctx)[move.product_id.id] - reference_amount = amount_unit * qty - - return reference_amount, reference_currency_id - - - def _create_product_valuation_moves(self, cr, uid, move, context=None): - """ - Generate the appropriate accounting moves if the product being moves is subject - to real_time valuation tracking, and the source or destination location is - a transit location or is outside of the company. - """ - if move.product_id.valuation == 'real_time': # FIXME: product valuation should perhaps be a property? - if context is None: - context = {} - src_company_ctx = dict(context,force_company=move.location_id.company_id.id) - dest_company_ctx = dict(context,force_company=move.location_dest_id.company_id.id) - account_moves = [] - # Outgoing moves (or cross-company output part) - if move.location_id.company_id \ - and (move.location_id.usage == 'internal' and move.location_dest_id.usage != 'internal'\ - or move.location_id.company_id != move.location_dest_id.company_id): - journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation(cr, uid, move, src_company_ctx) - reference_amount, reference_currency_id = self._get_reference_accounting_values_for_valuation(cr, uid, move, src_company_ctx) - #returning goods to supplier - if move.location_dest_id.usage == 'supplier': - account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_valuation, acc_src, reference_amount, reference_currency_id, context))] + def recalculate_move_state(self, cr, uid, move_ids, context=None): + '''Recompute the state of moves given because their reserved quants were used to fulfill another operation''' + for move in self.browse(cr, uid, move_ids, context=context): + vals = {} + reserved_quant_ids = move.reserved_quant_ids + if len(reserved_quant_ids) > 0 and not move.partially_available: + vals['partially_available'] = True + if len(reserved_quant_ids) == 0 and move.partially_available: + vals['partially_available'] = False + if move.state == 'assigned': + if self.find_move_ancestors(cr, uid, move, context=context): + vals['state'] = 'waiting' else: - account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_valuation, acc_dest, reference_amount, reference_currency_id, context))] - - # Incoming moves (or cross-company input part) - if move.location_dest_id.company_id \ - and (move.location_id.usage != 'internal' and move.location_dest_id.usage == 'internal'\ - or move.location_id.company_id != move.location_dest_id.company_id): - journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation(cr, uid, move, dest_company_ctx) - reference_amount, reference_currency_id = self._get_reference_accounting_values_for_valuation(cr, uid, move, src_company_ctx) - #goods return from customer - if move.location_id.usage == 'customer': - account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_dest, acc_valuation, reference_amount, reference_currency_id, context))] - else: - account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_src, acc_valuation, reference_amount, reference_currency_id, context))] - - move_obj = self.pool.get('account.move') - for j_id, move_lines in account_moves: - move_obj.create(cr, uid, - { - 'journal_id': j_id, - 'line_id': move_lines, - 'ref': move.picking_id and move.picking_id.name}, context=context) + vals['state'] = 'confirmed' + if vals: + self.write(cr, uid, [move.id], vals, context=context) def action_done(self, cr, uid, ids, context=None): - """ Makes the move done and if all moves are done, it will finish the picking. - @return: + """ Process completly the moves given as ids and if all moves are done, it will finish the picking. """ - picking_ids = [] - move_ids = [] - if context is None: - context = {} - - todo = [] - for move in self.browse(cr, uid, ids, context=context): - if move.state=="draft": - todo.append(move.id) + context = context or {} + picking_obj = self.pool.get("stock.picking") + quant_obj = self.pool.get("stock.quant") + todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"] if todo: - self.action_confirm(cr, uid, todo, context=context) - todo = [] - + ids = self.action_confirm(cr, uid, todo, context=context) + pickings = set() + procurement_ids = [] + #Search operations that are linked to the moves + operations = set() + move_qty = {} for move in self.browse(cr, uid, ids, context=context): - if move.state in ['done','cancel']: - continue - move_ids.append(move.id) + move_qty[move.id] = move.product_qty + for link in move.linked_move_operation_ids: + operations.add(link.operation_id) - if move.picking_id: - picking_ids.append(move.picking_id.id) - if move.move_dest_id.id and (move.state != 'done'): - # Downstream move should only be triggered if this move is the last pending upstream move - other_upstream_move_ids = self.search(cr, uid, [('id','!=',move.id),('state','not in',['done','cancel']), - ('move_dest_id','=',move.move_dest_id.id)], context=context) - if not other_upstream_move_ids: - self.write(cr, uid, [move.id], {'move_history_ids': [(4, move.move_dest_id.id)]}) - if move.move_dest_id.state in ('waiting', 'confirmed'): - self.force_assign(cr, uid, [move.move_dest_id.id], context=context) - if move.move_dest_id.picking_id: - workflow.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr) - if move.move_dest_id.auto_validate: - self.action_done(cr, uid, [move.move_dest_id.id], context=context) + #Sort operations according to entire packages first, then package + lot, package only, lot only + operations = list(operations) + operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0)) - self._create_product_valuation_moves(cr, uid, move, context=context) - if move.state not in ('confirmed','done','assigned'): - todo.append(move.id) + for ops in operations: + if ops.picking_id: + pickings.add(ops.picking_id.id) + main_domain = [('qty', '>', 0)] + for record in ops.linked_move_operation_ids: + move = record.move_id + self.check_tracking(cr, uid, move, ops.package_id.id or ops.lot_id.id, context=context) + prefered_domain = [('reservation_id', '=', move.id)] + fallback_domain = [('reservation_id', '=', False)] + fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)] + prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2] + dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context) + quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, record.qty, domain=dom, prefered_domain_list=prefered_domain_list, + restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context) + if ops.result_package_id.id: + #if a result package is given, all quants go there + quant_dest_package_id = ops.result_package_id.id + elif ops.product_id and ops.package_id: + #if a package and a product is given, we will remove quants from the pack. + quant_dest_package_id = False + else: + #otherwise we keep the current pack of the quant, which may mean None + quant_dest_package_id = ops.package_id.id + quant_obj.quants_move(cr, uid, quants, move, ops.location_dest_id, location_from=ops.location_id, lot_id=ops.lot_id.id, owner_id=ops.owner_id.id, src_package_id=ops.package_id.id, dest_package_id=quant_dest_package_id, context=context) + # Handle pack in pack + if not ops.product_id and ops.package_id and ops.result_package_id.id != ops.package_id.parent_id.id: + self.pool.get('stock.quant.package').write(cr, SUPERUSER_ID, [ops.package_id.id], {'parent_id': ops.result_package_id.id}, context=context) + move_qty[move.id] -= record.qty + #Check for remaining qtys and unreserve/check move_dest_id in + for move in self.browse(cr, uid, ids, context=context): + if move_qty[move.id] > 0: # (=In case no pack operations in picking) + main_domain = [('qty', '>', 0)] + prefered_domain = [('reservation_id', '=', move.id)] + fallback_domain = [('reservation_id', '=', False)] + fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)] + prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2] + self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context) + qty = move_qty[move.id] + quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain, prefered_domain_list=prefered_domain_list, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context) + quant_obj.quants_move(cr, uid, quants, move, move.location_dest_id, lot_id=move.restrict_lot_id.id, owner_id=move.restrict_partner_id.id, context=context) + #unreserve the quants and make them available for other operations/moves + quant_obj.quants_unreserve(cr, uid, move, context=context) - if todo: - self.action_confirm(cr, uid, todo, context=context) - - self.write(cr, uid, move_ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context) - for id in move_ids: - workflow.trg_trigger(uid, 'stock.move', id, cr) - - for pick_id in picking_ids: - workflow.trg_write(uid, 'stock.picking', pick_id, cr) + #Check moves that were pushed + if move.move_dest_id.state in ('waiting', 'confirmed'): + other_upstream_move_ids = self.search(cr, uid, [('id', '!=', move.id), ('state', 'not in', ['done', 'cancel']), + ('move_dest_id', '=', move.move_dest_id.id)], context=context) + #If no other moves for the move that got pushed: + if not other_upstream_move_ids and move.move_dest_id.state in ('waiting', 'confirmed'): + self.action_assign(cr, uid, [move.move_dest_id.id], context=context) + if move.procurement_id: + procurement_ids.append(move.procurement_id.id) + # Check the packages have been placed in the correct locations + self._check_package_from_moves(cr, uid, ids, context=context) + #set the move as done + self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context) + self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context) + #check picking state to set the date_done is needed + done_picking = [] + for picking in picking_obj.browse(cr, uid, list(pickings), context=context): + if picking.state == 'done' and not picking.date_done: + done_picking.append(picking.id) + if done_picking: + picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context) return True - def _create_account_move_line(self, cr, uid, move, src_account_id, dest_account_id, reference_amount, reference_currency_id, context=None): - """ - Generate the account.move.line values to post to track the stock valuation difference due to the - processing of the given stock move. - """ - # prepare default values considering that the destination accounts have the reference_currency_id as their main currency - partner_id = (move.picking_id.partner_id and self.pool.get('res.partner')._find_accounting_partner(move.picking_id.partner_id).id) or False - debit_line_vals = { - 'name': move.name, - 'product_id': move.product_id and move.product_id.id or False, - 'quantity': move.product_qty, - 'ref': move.picking_id and move.picking_id.name or False, - 'date': time.strftime('%Y-%m-%d'), - 'partner_id': partner_id, - 'debit': reference_amount, - 'account_id': dest_account_id, - } - credit_line_vals = { - 'name': move.name, - 'product_id': move.product_id and move.product_id.id or False, - 'quantity': move.product_qty, - 'ref': move.picking_id and move.picking_id.name or False, - 'date': time.strftime('%Y-%m-%d'), - 'partner_id': partner_id, - 'credit': reference_amount, - 'account_id': src_account_id, - } - - # if we are posting to accounts in a different currency, provide correct values in both currencies correctly - # when compatible with the optional secondary currency on the account. - # Financial Accounts only accept amounts in secondary currencies if there's no secondary currency on the account - # or if it's the same as that of the secondary amount being posted. - account_obj = self.pool.get('account.account') - src_acct, dest_acct = account_obj.browse(cr, uid, [src_account_id, dest_account_id], context=context) - src_main_currency_id = src_acct.company_id.currency_id.id - dest_main_currency_id = dest_acct.company_id.currency_id.id - cur_obj = self.pool.get('res.currency') - if reference_currency_id != src_main_currency_id: - # fix credit line: - credit_line_vals['credit'] = cur_obj.compute(cr, uid, reference_currency_id, src_main_currency_id, reference_amount, context=context) - if (not src_acct.currency_id) or src_acct.currency_id.id == reference_currency_id: - credit_line_vals.update(currency_id=reference_currency_id, amount_currency=-reference_amount) - if reference_currency_id != dest_main_currency_id: - # fix debit line: - debit_line_vals['debit'] = cur_obj.compute(cr, uid, reference_currency_id, dest_main_currency_id, reference_amount, context=context) - if (not dest_acct.currency_id) or dest_acct.currency_id.id == reference_currency_id: - debit_line_vals.update(currency_id=reference_currency_id, amount_currency=reference_amount) - - return [(0, 0, debit_line_vals), (0, 0, credit_line_vals)] - def unlink(self, cr, uid, ids, context=None): - if context is None: - context = {} - ctx = context.copy() + context = context or {} for move in self.browse(cr, uid, ids, context=context): - if move.state != 'draft' and not ctx.get('call_unlink', False): + if move.state not in ('draft', 'cancel'): raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.')) - return super(stock_move, self).unlink( - cr, uid, ids, context=ctx) + return super(stock_move, self).unlink(cr, uid, ids, context=context) - # _create_lot function is not used anywhere - def _create_lot(self, cr, uid, ids, product_id, prefix=False): - """ Creates production lot - @return: Production lot id - """ - prodlot_obj = self.pool.get('stock.production.lot') - prodlot_id = prodlot_obj.create(cr, uid, {'prefix': prefix, 'product_id': product_id}) - return prodlot_id - - def action_scrap(self, cr, uid, ids, quantity, location_id, context=None): + def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None): """ Move the scrap/damaged product into scrap location @param cr: the database cursor @param uid: the user id @@ -2501,7 +2304,7 @@ class stock_move(osv.osv): @param context: context arguments @return: Scraped lines """ - #quantity should in MOVE UOM + #quantity should be given in MOVE UOM if quantity <= 0: raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.')) res = [] @@ -2509,20 +2312,21 @@ class stock_move(osv.osv): source_location = move.location_id if move.state == 'done': source_location = move.location_dest_id - if source_location.usage != 'internal': + #Previously used to prevent scraping from virtual location but not necessary anymore + #if source_location.usage != 'internal': #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere) - raise osv.except_osv(_('Error!'), _('Operation Forbidden! it is not allowed to scrap products from a virtual location: %s' %(move.location_id.complete_name))) + #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.')) move_qty = move.product_qty uos_qty = quantity / move_qty * move.product_uos_qty default_val = { 'location_id': source_location.id, - 'product_qty': quantity, + 'product_uom_qty': quantity, 'product_uos_qty': uos_qty, 'state': move.state, 'scrapped': True, 'location_dest_id': location_id, - 'tracking_id': move.tracking_id.id, - 'prodlot_id': move.prodlot_id.id, + 'restrict_lot_id': restrict_lot_id, + 'restrict_partner_id': restrict_partner_id, } new_move = self.copy(cr, uid, move.id, default_val) @@ -2537,269 +2341,154 @@ class stock_move(osv.osv): self.action_done(cr, uid, res, context=context) return res - # action_split function is not used anywhere - # FIXME: deprecate this method - def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None): - """ Split Stock Move lines into production lot which specified split by quantity. - @param cr: the database cursor - @param uid: the user id - @param ids: ids of stock move object to be splited - @param split_by_qty : specify split by qty - @param prefix : specify prefix of production lot - @param with_lot : if true, prodcution lot will assign for split line otherwise not. - @param context: context arguments - @return: Splited move lines + def split(self, cr, uid, move, qty, restrict_lot_id=False, restrict_partner_id=False, context=None): + """ Splits qty from move move into a new move + :param move: browse record + :param qty: float. quantity to split (given in product UoM) + :param restrict_lot_id: optional production lot that can be given in order to force the new move to restrict its choice of quants to this lot. + :param restrict_partner_id: optional partner that can be given in order to force the new move to restrict its choice of quants to the ones belonging to this partner. + :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move + + returns the ID of the backorder move created """ + if move.state in ('done', 'cancel'): + raise osv.except_osv(_('Error'), _('You cannot split a move done')) + if move.state == 'draft': + #we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in + #case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode. + raise osv.except_osv(_('Error'), _('You cannot split a draft move. It needs to be confirmed first.')) - if context is None: - context = {} - if quantity <= 0: - raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.')) + if move.product_qty <= qty or qty == 0: + return move.id - res = [] - - for move in self.browse(cr, uid, ids, context=context): - if split_by_qty <= 0 or quantity == 0: - return res - - uos_qty = split_by_qty / move.product_qty * move.product_uos_qty - - quantity_rest = quantity % split_by_qty - uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty - - update_val = { - 'product_qty': split_by_qty, - 'product_uos_qty': uos_qty, - } - for idx in range(int(quantity//split_by_qty)): - if not idx and move.product_qty<=quantity: - current_move = move.id - else: - current_move = self.copy(cr, uid, move.id, {'state': move.state}) - res.append(current_move) - if with_lot: - update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id) - - self.write(cr, uid, [current_move], update_val) - - - if quantity_rest > 0: - idx = int(quantity//split_by_qty) - update_val['product_qty'] = quantity_rest - update_val['product_uos_qty'] = uos_qty_rest - if not idx and move.product_qty<=quantity: - current_move = move.id - else: - current_move = self.copy(cr, uid, move.id, {'state': move.state}) - - res.append(current_move) - - - if with_lot: - update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id) - - self.write(cr, uid, [current_move], update_val) - return res - - def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None): - """ Consumed product with specific quatity from specific source location - @param cr: the database cursor - @param uid: the user id - @param ids: ids of stock move object to be consumed - @param quantity : specify consume quantity - @param location_id : specify source location - @param context: context arguments - @return: Consumed lines - """ - #quantity should in MOVE UOM - if context is None: - context = {} - if quantity <= 0: - raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.')) - res = [] - for move in self.browse(cr, uid, ids, context=context): - move_qty = move.product_qty - if move_qty <= 0: - raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.')) - quantity_rest = move.product_qty - quantity_rest -= quantity - uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty - if quantity_rest <= 0: - quantity_rest = 0 - uos_qty_rest = 0 - quantity = move.product_qty - - uos_qty = quantity / move_qty * move.product_uos_qty - if float_compare(quantity_rest, 0, precision_rounding=move.product_id.uom_id.rounding): - default_val = { - 'product_qty': quantity, - 'product_uos_qty': uos_qty, - 'state': move.state, - 'location_id': location_id or move.location_id.id, - } - current_move = self.copy(cr, uid, move.id, default_val) - res += [current_move] - update_val = {} - update_val['product_qty'] = quantity_rest - update_val['product_uos_qty'] = uos_qty_rest - self.write(cr, uid, [move.id], update_val) - - else: - quantity_rest = quantity - uos_qty_rest = uos_qty - res += [move.id] - update_val = { - 'product_qty' : quantity_rest, - 'product_uos_qty' : uos_qty_rest, - 'location_id': location_id or move.location_id.id, - } - self.write(cr, uid, [move.id], update_val) - - self.action_done(cr, uid, res, context=context) - - return res - - # FIXME: needs refactoring, this code is partially duplicated in stock_picking.do_partial()! - def do_partial(self, cr, uid, ids, partial_datas, context=None): - """ Makes partial pickings and moves done. - @param partial_datas: Dictionary containing details of partial picking - like partner_id, delivery_date, delivery - moves with product_id, product_qty, uom - """ - res = {} - picking_obj = self.pool.get('stock.picking') - product_obj = self.pool.get('product.product') - currency_obj = self.pool.get('res.currency') uom_obj = self.pool.get('product.uom') + context = context or {} - if context is None: - context = {} + uom_qty = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom) + uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty - complete, too_many, too_few = [], [], [] - move_product_qty = {} - prodlot_ids = {} - for move in self.browse(cr, uid, ids, context=context): - if move.state in ('done', 'cancel'): - continue - partial_data = partial_datas.get('move%s'%(move.id), False) - assert partial_data, _('Missing partial picking data for move #%s.') % (move.id) - product_qty = partial_data.get('product_qty',0.0) - move_product_qty[move.id] = product_qty - product_uom = partial_data.get('product_uom',False) - product_price = partial_data.get('product_price',0.0) - product_currency = partial_data.get('product_currency',False) - prodlot_ids[move.id] = partial_data.get('prodlot_id') - if move.product_qty == product_qty: - complete.append(move) - elif move.product_qty > product_qty: - too_few.append(move) - else: - too_many.append(move) + defaults = { + 'product_uom_qty': uom_qty, + 'product_uos_qty': uos_qty, + 'state': move.state, + 'procure_method': 'make_to_stock', + 'restrict_lot_id': restrict_lot_id, + 'restrict_partner_id': restrict_partner_id, + 'split_from': move.id, + 'move_dest_id': move.move_dest_id.id, + } + if context.get('source_location_id'): + defaults['location_id'] = context['source_location_id'] + new_move = self.copy(cr, uid, move.id, defaults) - # Average price computation - if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'): - product = product_obj.browse(cr, uid, move.product_id.id) - move_currency_id = move.company_id.currency_id.id - context['currency_id'] = move_currency_id - qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id) - if qty > 0: - new_price = currency_obj.compute(cr, uid, product_currency, - move_currency_id, product_price, round=False) - new_price = uom_obj._compute_price(cr, uid, product_uom, new_price, - product.uom_id.id) - if product.qty_available <= 0: - new_std_price = new_price - else: - # Get the standard price - amount_unit = product.price_get('standard_price', context=context)[product.id] - new_std_price = ((amount_unit * product.qty_available)\ - + (new_price * qty))/(product.qty_available + qty) + ctx = context.copy() + ctx['do_not_propagate'] = True + self.write(cr, uid, [move.id], { + 'product_uom_qty': move.product_uom_qty - uom_qty, + 'product_uos_qty': move.product_uos_qty - uos_qty, + }, context=ctx) - product_obj.write(cr, uid, [product.id],{'standard_price': new_std_price}) - - # Record the values that were chosen in the wizard, so they can be - # used for inventory valuation if real-time valuation is enabled. - self.write(cr, uid, [move.id], - {'price_unit': product_price, - 'price_currency_id': product_currency, - }) - - for move in too_few: - product_qty = move_product_qty[move.id] - if product_qty != 0: - defaults = { - 'product_qty' : product_qty, - 'product_uos_qty': product_qty, - 'picking_id' : move.picking_id.id, - 'state': 'assigned', - 'move_dest_id': False, - 'price_unit': move.price_unit, - } - prodlot_id = prodlot_ids[move.id] - if prodlot_id: - defaults.update(prodlot_id=prodlot_id) - new_move = self.copy(cr, uid, move.id, defaults) - complete.append(self.browse(cr, uid, new_move)) - self.write(cr, uid, [move.id], - { - 'product_qty': move.product_qty - product_qty, - 'product_uos_qty': move.product_qty - product_qty, - 'prodlot_id': False, - 'tracking_id': False, - }) - - - for move in too_many: - self.write(cr, uid, [move.id], - { - 'product_qty': move.product_qty, - 'product_uos_qty': move.product_qty, - }) - complete.append(move) - - for move in complete: - if prodlot_ids.get(move.id): - self.write(cr, uid, [move.id],{'prodlot_id': prodlot_ids.get(move.id)}) - self.action_done(cr, uid, [move.id], context=context) - if move.picking_id.id : - # TOCHECK : Done picking if all moves are done - cr.execute(""" - SELECT move.id FROM stock_picking pick - RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s - WHERE pick.id = %s""", - ('done', move.picking_id.id)) - res = cr.fetchall() - if len(res) == len(move.picking_id.move_lines): - picking_obj.action_move(cr, uid, [move.picking_id.id]) - picking_obj.signal_button_done(cr, uid, [move.picking_id.id]) - - return [move.id for move in complete] + if move.move_dest_id and move.propagate: + new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context) + self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context) + #returning the first element of list returned by action_confirm is ok because we checked it wouldn't be exploded (and + #thus the result of action_confirm should always be a list of 1 element length) + return self.action_confirm(cr, uid, [new_move], context=context)[0] class stock_inventory(osv.osv): _name = "stock.inventory" _description = "Inventory" - _columns = { - 'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}), - 'date': fields.datetime('Creation Date', required=True, readonly=True, states={'draft': [('readonly', False)]}), - 'date_done': fields.datetime('Date done'), - 'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=True, states={'draft': [('readonly', False)]}), - 'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'), - 'state': fields.selection( (('draft', 'Draft'), ('cancel','Cancelled'), ('confirm','Confirmed'), ('done', 'Done')), 'Status', readonly=True, select=True), - 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft':[('readonly',False)]}), + def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None): + res = {} + for inv in self.browse(cr, uid, ids, context=context): + res[inv.id] = False + if inv.move_ids: + res[inv.id] = True + return res + + def _get_available_filters(self, cr, uid, context=None): + """ + This function will return the list of filter allowed according to the options checked + in 'Settings\Warehouse'. + + :rtype: list of tuple + """ + #default available choices + res_filter = [('none', _('All products')), ('product', _('One product only'))] + settings_obj = self.pool.get('stock.config.settings') + config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context) + #If we don't have updated config until now, all fields are by default false and so should be not dipslayed + if not config_ids: + return res_filter + + stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context) + if stock_settings.group_stock_tracking_owner: + res_filter.append(('owner', _('One owner only'))) + res_filter.append(('product_owner', _('One product for a specific owner'))) + if stock_settings.group_stock_tracking_lot: + res_filter.append(('lot', _('One Lot/Serial Number'))) + if stock_settings.group_stock_packaging: + res_filter.append(('pack', _('A Pack'))) + return res_filter + + def _get_total_qty(self, cr, uid, ids, field_name, args, context=None): + res = {} + for inv in self.browse(cr, uid, ids, context=context): + res[inv.id] = sum([x.product_qty for x in inv.line_ids]) + return res + + INVENTORY_STATE_SELECTION = [ + ('draft', 'Draft'), + ('cancel', 'Cancelled'), + ('confirm', 'In Progress'), + ('done', 'Validated'), + ] + + _columns = { + 'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."), + 'date': fields.datetime('Inventory Date', required=True, readonly=True, help="The date that will be used for the stock level check of the products and the validation of the stock move related to this inventory."), + 'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines."), + 'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves.", states={'done': [('readonly', True)]}), + 'state': fields.selection(INVENTORY_STATE_SELECTION, 'Status', readonly=True, select=True), + 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}), + 'location_id': fields.many2one('stock.location', 'Inventoried Location', required=True, readonly=True, states={'draft': [('readonly', False)]}), + 'product_id': fields.many2one('product.product', 'Inventoried Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."), + 'package_id': fields.many2one('stock.quant.package', 'Inventoried Pack', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Pack to focus your inventory on a particular Pack."), + 'partner_id': fields.many2one('res.partner', 'Inventoried Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."), + 'lot_id': fields.many2one('stock.production.lot', 'Inventoried Lot/Serial Number', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Lot/Serial Number to focus your inventory on a particular Lot/Serial Number."), + 'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'), + 'filter': fields.selection(_get_available_filters, 'Selection Filter', required=True), + 'total_qty': fields.function(_get_total_qty, type="float"), } + + def _default_stock_location(self, cr, uid, context=None): + try: + warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0') + return warehouse.lot_stock_id.id + except: + return False + _defaults = { - 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), + 'date': fields.datetime.now, 'state': 'draft', - 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c) + 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c), + 'location_id': _default_stock_location, + 'filter': 'none', } + def reset_real_qty(self, cr, uid, ids, context=None): + inventory = self.browse(cr, uid, ids[0], context=context) + line_ids = [line.id for line in inventory.line_ids] + self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0}) + return True + def copy(self, cr, uid, id, default=None, context=None): if default is None: default = {} default = default.copy() - default.update({'move_ids': [], 'date_done': False}) + default.update({'move_ids': []}) return super(stock_inventory, self).copy(cr, uid, id, default, context=context) def _inventory_line_hook(self, cr, uid, inventory_line, move_vals): @@ -2814,59 +2503,64 @@ class stock_inventory(osv.osv): """ Finish the inventory @return: True """ - if context is None: - context = {} - move_obj = self.pool.get('stock.move') for inv in self.browse(cr, uid, ids, context=context): - move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context) - self.write(cr, uid, [inv.id], {'state':'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context) + for inventory_line in inv.line_ids: + if inventory_line.product_qty < 0 and inventory_line.product_qty != inventory_line.theoretical_qty: + raise osv.except_osv(_('Warning'), _('You cannot set a negative product quantity in an inventory line:\n\t%s - qty: %s' % (inventory_line.product_id.name, inventory_line.product_qty))) + self.action_check(cr, uid, [inv.id], context=context) + inv.refresh() + self.write(cr, uid, [inv.id], {'state': 'done'}, context=context) + self.post_inventory(cr, uid, inv, context=context) return True - def action_confirm(self, cr, uid, ids, context=None): - """ Confirm the inventory and writes its finished date + def post_inventory(self, cr, uid, inv, context=None): + #The inventory is posted as a single step which means quants cannot be moved from an internal location to another using an inventory + #as they will be moved to inventory loss, and other quants will be created to the encoded quant location. This is a normal behavior + #as quants cannot be reuse from inventory location (users can still manually move the products before/after the inventory if they want). + move_obj = self.pool.get('stock.move') + move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context) + + def _create_stock_move(self, cr, uid, inventory, todo_line, context=None): + stock_move_obj = self.pool.get('stock.move') + product_obj = self.pool.get('product.product') + inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id + vals = { + 'name': _('INV:') + (inventory.name or ''), + 'product_id': todo_line['product_id'], + 'product_uom': todo_line['product_uom_id'], + 'date': inventory.date, + 'company_id': inventory.company_id.id, + 'inventory_id': inventory.id, + 'state': 'assigned', + 'restrict_lot_id': todo_line.get('prod_lot_id'), + 'restrict_partner_id': todo_line.get('partner_id'), + } + + if todo_line['product_qty'] < 0: + #found more than expected + vals['location_id'] = inventory_location_id + vals['location_dest_id'] = todo_line['location_id'] + vals['product_uom_qty'] = -todo_line['product_qty'] + else: + #found less than expected + vals['location_id'] = todo_line['location_id'] + vals['location_dest_id'] = inventory_location_id + vals['product_uom_qty'] = todo_line['product_qty'] + return stock_move_obj.create(cr, uid, vals, context=context) + + def action_check(self, cr, uid, ids, context=None): + """ Checks the inventory and computes the stock move to do @return: True """ - if context is None: - context = {} - # to perform the correct inventory corrections we need analyze stock location by - # location, never recursively, so we use a special context - product_context = dict(context, compute_child=False) - - location_obj = self.pool.get('stock.location') - for inv in self.browse(cr, uid, ids, context=context): - move_ids = [] - for line in inv.inventory_line_id: - pid = line.product_id.id - product_context.update(uom=line.product_uom.id, to_date=inv.date, date=inv.date, prodlot_id=line.prod_lot_id.id) - amount = location_obj._product_get(cr, uid, line.location_id.id, [pid], product_context)[pid] - change = line.product_qty - amount - lot_id = line.prod_lot_id.id - if change: - location_id = line.product_id.property_stock_inventory.id - value = { - 'name': _('INV:') + (line.inventory_id.name or ''), - 'product_id': line.product_id.id, - 'product_uom': line.product_uom.id, - 'prodlot_id': lot_id, - 'date': inv.date, - } - - if change > 0: - value.update( { - 'product_qty': change, - 'location_id': location_id, - 'location_dest_id': line.location_id.id, - }) - else: - value.update( { - 'product_qty': -change, - 'location_id': line.location_id.id, - 'location_dest_id': location_id, - }) - move_ids.append(self._inventory_line_hook(cr, uid, line, value)) - self.write(cr, uid, [inv.id], {'state': 'confirm', 'move_ids': [(6, 0, move_ids)]}) - self.pool.get('stock.move').action_confirm(cr, uid, move_ids, context=context) - return True + inventory_line_obj = self.pool.get('stock.inventory.line') + stock_move_obj = self.pool.get('stock.move') + for inventory in self.browse(cr, uid, ids, context=context): + #first remove the existing stock moves linked to this inventory + move_ids = [move.id for move in inventory.move_ids] + stock_move_obj.unlink(cr, uid, move_ids, context=context) + for line in inventory.line_ids: + #compare the checked quantities on inventory lines to the theorical one + inventory_line_obj._resolve_inventory_line(cr, uid, line, context=context) def action_cancel_draft(self, cr, uid, ids, context=None): """ Cancels the stock move and change inventory state to draft. @@ -2874,72 +2568,170 @@ class stock_inventory(osv.osv): """ for inv in self.browse(cr, uid, ids, context=context): self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context) - self.write(cr, uid, [inv.id], {'state':'draft'}, context=context) + self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context) return True def action_cancel_inventory(self, cr, uid, ids, context=None): - """ Cancels both stock move and inventory - @return: True - """ - move_obj = self.pool.get('stock.move') - account_move_obj = self.pool.get('account.move') - for inv in self.browse(cr, uid, ids, context=context): - move_obj.action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context) - for move in inv.move_ids: - account_move_ids = account_move_obj.search(cr, uid, [('name', '=', move.name)]) - if account_move_ids: - account_move_data_l = account_move_obj.read(cr, uid, account_move_ids, ['state'], context=context) - for account_move in account_move_data_l: - if account_move['state'] == 'posted': - raise osv.except_osv(_('User Error!'), - _('In order to cancel this inventory, you must first unpost related journal entries.')) - account_move_obj.unlink(cr, uid, [account_move['id']], context=context) - self.write(cr, uid, [inv.id], {'state': 'cancel'}, context=context) - return True + self.action_cancel_draft(cr, uid, ids, context=context) + + def prepare_inventory(self, cr, uid, ids, context=None): + inventory_line_obj = self.pool.get('stock.inventory.line') + for inventory in self.browse(cr, uid, ids, context=context): + #clean the existing inventory lines before redoing an inventory proposal + line_ids = [line.id for line in inventory.line_ids] + inventory_line_obj.unlink(cr, uid, line_ids, context=context) + #compute the inventory lines and create them + vals = self._get_inventory_lines(cr, uid, inventory, context=context) + for product_line in vals: + inventory_line_obj.create(cr, uid, product_line, context=context) + return self.write(cr, uid, ids, {'state': 'confirm', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) + + def _get_inventory_lines(self, cr, uid, inventory, context=None): + location_obj = self.pool.get('stock.location') + product_obj = self.pool.get('product.product') + location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context) + domain = ' location_id in %s' + args = (tuple(location_ids),) + if inventory.partner_id: + domain += ' and owner_id = %s' + args += (inventory.partner_id.id,) + if inventory.lot_id: + domain += ' and lot_id = %s' + args += (inventory.lot_id.id,) + if inventory.product_id: + domain += 'and product_id = %s' + args += (inventory.product_id.id,) + if inventory.package_id: + domain += ' and package_id = %s' + args += (inventory.package_id.id,) + + cr.execute(''' + SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id + FROM stock_quant WHERE''' + domain + ''' + GROUP BY product_id, location_id, lot_id, package_id, partner_id + ''', args) + vals = [] + for product_line in cr.dictfetchall(): + #replace the None the dictionary by False, because falsy values are tested later on + for key, value in product_line.items(): + if not value: + product_line[key] = False + product_line['inventory_id'] = inventory.id + product_line['theoretical_qty'] = product_line['product_qty'] + if product_line['product_id']: + product = product_obj.browse(cr, uid, product_line['product_id'], context=context) + product_line['product_uom_id'] = product.uom_id.id + vals.append(product_line) + return vals class stock_inventory_line(osv.osv): _name = "stock.inventory.line" _description = "Inventory Line" - _rec_name = "inventory_id" + _order = "inventory_id, location_name, product_code, product_name, prodlot_name" + + def _get_product_name_change(self, cr, uid, ids, context=None): + return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context) + + def _get_location_change(self, cr, uid, ids, context=None): + return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context) + + def _get_prodlot_change(self, cr, uid, ids, context=None): + return self.pool.get('stock.inventory.line').search(cr, uid, [('prod_lot_id', 'in', ids)], context=context) + _columns = { 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True), - 'location_id': fields.many2one('stock.location', 'Location', required=True), + 'location_id': fields.many2one('stock.location', 'Location', required=True, select=True), 'product_id': fields.many2one('product.product', 'Product', required=True, select=True), - 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True), - 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure')), - 'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True, select=True, readonly=True), + 'package_id': fields.many2one('stock.quant.package', 'Pack', select=True), + 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True), + 'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')), + 'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True), 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"), - 'state': fields.related('inventory_id','state',type='char',string='Status',readonly=True), + 'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True), + 'theoretical_qty': fields.float('Theoretical Quantity', readonly=True), + 'partner_id': fields.many2one('res.partner', 'Owner'), + 'product_name': fields.related('product_id', 'name', type='char', string='Product Name', store={ + 'product.product': (_get_product_name_change, ['name', 'default_code'], 20), + 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}), + 'product_code': fields.related('product_id', 'default_code', type='char', string='Product Code', store={ + 'product.product': (_get_product_name_change, ['name', 'default_code'], 20), + 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}), + 'location_name': fields.related('location_id', 'complete_name', type='char', string='Location Name', store={ + 'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20), + 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}), + 'prodlot_name': fields.related('prod_lot_id', 'name', type='char', string='Serial Number Name', store={ + 'stock.production.lot': (_get_prodlot_change, ['name'], 20), + 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['prod_lot_id'], 20),}), } - def _default_stock_location(self, cr, uid, context=None): - try: - location_model, location_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_stock') - with tools.mute_logger('openerp.osv.orm'): - self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context) - except (orm.except_orm, ValueError): - location_id = False - return location_id - _defaults = { - 'location_id': _default_stock_location + 'product_qty': 1, } - def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False, to_date=False): - """ Changes UoM and name if product_id changes. + def _resolve_inventory_line(self, cr, uid, inventory_line, context=None): + stock_move_obj = self.pool.get('stock.move') + diff = inventory_line.theoretical_qty - inventory_line.product_qty + if not diff: + return + #each theorical_lines where difference between theoretical and checked quantities is not 0 is a line for which we need to create a stock move + vals = { + 'name': _('INV:') + (inventory_line.inventory_id.name or ''), + 'product_id': inventory_line.product_id.id, + 'product_uom': inventory_line.product_uom_id.id, + 'date': inventory_line.inventory_id.date, + 'company_id': inventory_line.inventory_id.company_id.id, + 'inventory_id': inventory_line.inventory_id.id, + 'state': 'confirmed', + 'restrict_lot_id': inventory_line.prod_lot_id.id, + 'restrict_partner_id': inventory_line.partner_id.id, + } + inventory_location_id = inventory_line.product_id.property_stock_inventory.id + if diff < 0: + #found more than expected + vals['location_id'] = inventory_location_id + vals['location_dest_id'] = inventory_line.location_id.id + vals['product_uom_qty'] = -diff + else: + #found less than expected + vals['location_id'] = inventory_line.location_id.id + vals['location_dest_id'] = inventory_location_id + vals['product_uom_qty'] = diff + return stock_move_obj.create(cr, uid, vals, context=context) + + def restrict_change(self, cr, uid, ids, theoretical_qty, context=None): + if ids and theoretical_qty: + #if the user try to modify a line prepared by openerp, reject the change and display an error message explaining how he should do + old_value = self.browse(cr, uid, ids[0], context=context) + return { + 'value': { + 'product_id': old_value.product_id.id, + 'product_uom_id': old_value.product_uom_id.id, + 'location_id': old_value.location_id.id, + 'prod_lot_id': old_value.prod_lot_id.id, + 'package_id': old_value.package_id.id, + 'partner_id': old_value.partner_id.id, + }, + 'warning': { + 'title': _('Error'), + 'message': _('You can only change the checked quantity of an existing inventory line. If you want modify a data, please set the checked quantity to 0 and create a new inventory line.') + } + } + return {} + + def on_change_product_id(self, cr, uid, ids, product, uom, theoretical_qty, context=None): + """ Changes UoM @param location_id: Location id @param product: Changed product_id @param uom: UoM product @return: Dictionary of changed values """ + if ids and theoretical_qty: + return self.restrict_change(cr, uid, ids, theoretical_qty, context=context) if not product: - return {'value': {'product_qty': 0.0, 'product_uom': False, 'prod_lot_id': False}} - obj_product = self.pool.get('product.product').browse(cr, uid, product) - uom = uom or obj_product.uom_id.id - amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom, 'to_date': to_date, 'compute_child': False})[product] - result = {'product_qty': amount, 'product_uom': uom, 'prod_lot_id': False} - return {'value': result} + return {'value': {'product_uom_id': False}} + obj_product = self.pool.get('product.product').browse(cr, uid, product, context=context) + return {'value': {'product_uom_id': uom or obj_product.uom_id.id}} #---------------------------------------------------------- @@ -2948,211 +2740,1453 @@ class stock_inventory_line(osv.osv): class stock_warehouse(osv.osv): _name = "stock.warehouse" _description = "Warehouse" + _columns = { - 'name': fields.char('Name', size=128, required=True, select=True), + 'name': fields.char('Warehouse Name', size=128, required=True, select=True), 'company_id': fields.many2one('res.company', 'Company', required=True, select=True), - 'partner_id': fields.many2one('res.partner', 'Owner Address'), - 'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True, domain=[('usage','<>','view')]), - 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage','=','internal')]), - 'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True, domain=[('usage','<>','view')]), + 'partner_id': fields.many2one('res.partner', 'Address'), + 'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]), + 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage', '=', 'internal')]), + 'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"), + 'route_ids': fields.many2many('stock.location.route', 'stock_route_warehouse', 'warehouse_id', 'route_id', 'Routes', domain="[('warehouse_selectable', '=', True)]", help='Defaults routes through the warehouse'), + 'reception_steps': fields.selection([ + ('one_step', 'Receive goods directly in stock (1 step)'), + ('two_steps', 'Unload in input location then go to stock (2 steps)'), + ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments', + help="Default incoming route to follow", required=True), + 'delivery_steps': fields.selection([ + ('ship_only', 'Ship directly from stock (Ship only)'), + ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'), + ('pick_pack_ship', 'Make packages into a dedicated location, then bring them to the output location for shipping (Pick + Pack + Ship)')], 'Outgoing Shippings', + help="Default outgoing route to follow", required=True), + 'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'), + 'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'), + 'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'), + 'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'), + 'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'), + 'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'), + 'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'), + 'out_type_id': fields.many2one('stock.picking.type', 'Out Type'), + 'in_type_id': fields.many2one('stock.picking.type', 'In Type'), + 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'), + 'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'), + 'reception_route_id': fields.many2one('stock.location.route', 'Reception Route'), + 'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'), + 'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'), + 'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'), + 'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes', + help="Routes will be created for these resupply warehouses and you can select them on products and product categories"), + 'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse', help="Goods will always be resupplied from this warehouse"), } - def _default_lot_input_stock_id(self, cr, uid, context=None): - try: - lot_input_stock_model, lot_input_stock_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_stock') - with tools.mute_logger('openerp.osv.orm'): - self.pool.get('stock.location').check_access_rule(cr, uid, [lot_input_stock_id], 'read', context=context) - except (ValueError, orm.except_orm): - # the user does not have read access on the location or it does not exists - lot_input_stock_id = False - return lot_input_stock_id + def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None): + resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))]) + if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id + resupply_wh_ids.add(default_resupply_wh_id) + resupply_wh_ids = list(resupply_wh_ids) + return {'value': {'resupply_wh_ids': resupply_wh_ids}} - def _default_lot_output_id(self, cr, uid, context=None): + def _get_external_transit_location(self, cr, uid, warehouse, context=None): + ''' returns browse record of inter company transit location, if found''' + data_obj = self.pool.get('ir.model.data') + location_obj = self.pool.get('stock.location') try: - lot_output_model, lot_output_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_output') - with tools.mute_logger('openerp.osv.orm'): - self.pool.get('stock.location').check_access_rule(cr, uid, [lot_output_id], 'read', context=context) - except (ValueError, orm.except_orm): - # the user does not have read access on the location or it does not exists - lot_output_id = False - return lot_output_id + inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1] + except: + return False + return location_obj.browse(cr, uid, inter_wh_loc, context=context) + + def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None): + return { + 'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name), + 'warehouse_selectable': False, + 'product_selectable': True, + 'product_categ_selectable': True, + 'supplied_wh_id': warehouse.id, + 'supplier_wh_id': wh.id, + } + + def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None): + route_obj = self.pool.get('stock.location.route') + pull_obj = self.pool.get('procurement.rule') + #create route selectable on the product to resupply the warehouse from another one + external_transit_location = self._get_external_transit_location(cr, uid, warehouse, context=context) + internal_transit_location = warehouse.company_id.internal_transit_location_id + input_loc = warehouse.wh_input_stock_loc_id + if warehouse.reception_steps == 'one_step': + input_loc = warehouse.lot_stock_id + for wh in supplier_warehouses: + transit_location = wh.company_id.id == warehouse.company_id.id and internal_transit_location or external_transit_location + if transit_location: + output_loc = wh.wh_output_stock_loc_id + if wh.delivery_steps == 'ship_only': + output_loc = wh.lot_stock_id + # Create extra MTO rule (only for 'ship only' because in the other cases MTO rules already exists) + mto_pull_vals = self._get_mto_pull_rule(cr, uid, wh, [(output_loc, transit_location, wh.out_type_id.id)], context=context) + pull_obj.create(cr, uid, mto_pull_vals, context=context) + inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context) + inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context) + values = [(output_loc, transit_location, wh.out_type_id.id, wh), (transit_location, input_loc, warehouse.in_type_id.id, warehouse)] + pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context) + for pull_rule in pull_rules_list: + pull_obj.create(cr, uid, vals=pull_rule, context=context) + #if the warehouse is also set as default resupply method, assign this route automatically to the warehouse + if default_resupply_wh and default_resupply_wh.id == wh.id: + self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context) + + def _default_stock_id(self, cr, uid, context=None): + #lot_input_stock = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock') + try: + warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0') + return warehouse.lot_stock_id.id + except: + return False _defaults = { 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c), - 'lot_input_id': _default_lot_input_stock_id, - 'lot_stock_id': _default_lot_input_stock_id, - 'lot_output_id': _default_lot_output_id, + 'lot_stock_id': _default_stock_id, + 'reception_steps': 'one_step', + 'delivery_steps': 'ship_only', } + _sql_constraints = [ + ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'), + ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'), + ] + def _get_partner_locations(self, cr, uid, ids, context=None): + ''' returns a tuple made of the browse record of customer location and the browse record of supplier location''' + data_obj = self.pool.get('ir.model.data') + location_obj = self.pool.get('stock.location') + try: + customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1] + supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1] + except: + customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context) + customer_loc = customer_loc and customer_loc[0] or False + supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context) + supplier_loc = supplier_loc and supplier_loc[0] or False + if not (customer_loc and supplier_loc): + raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.')) + return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context) -#---------------------------------------------------------- -# "Empty" Classes that are used to vary from the original stock.picking (that are dedicated to the internal pickings) -# in order to offer a different usability with different views, labels, available reports/wizards... -#---------------------------------------------------------- -class stock_picking_in(osv.osv): - _name = "stock.picking.in" - _inherit = "stock.picking" - _table = "stock_picking" - _description = "Incoming Shipments" + def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None): + location_obj = self.pool.get('stock.location') - def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False): - return self.pool.get('stock.picking').search(cr, user, args, offset, limit, order, context, count) + new_reception_step = new_reception_step or warehouse.reception_steps + new_delivery_step = new_delivery_step or warehouse.delivery_steps + if warehouse.reception_steps != new_reception_step: + location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context) + if new_reception_step != 'one_step': + location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context) + if new_reception_step == 'three_steps': + location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context) - def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): - return self.pool.get('stock.picking').read(cr, uid, ids, fields=fields, context=context, load=load) + if warehouse.delivery_steps != new_delivery_step: + location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context) + if new_delivery_step != 'ship_only': + location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context) + if new_delivery_step == 'pick_pack_ship': + location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context) + return True - def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False): - return self.pool['stock.picking'].read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby) + def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None): + return { + 'name': self._format_routename(cr, uid, warehouse, route_name, context=context), + 'product_categ_selectable': True, + 'product_selectable': False, + 'sequence': 10, + } - def check_access_rights(self, cr, uid, operation, raise_exception=True): - #override in order to redirect the check of acces rights on the stock.picking object - return self.pool.get('stock.picking').check_access_rights(cr, uid, operation, raise_exception=raise_exception) + def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None): + pull_rules_list = [] + for from_loc, dest_loc, pick_type_id, warehouse in values: + pull_rules_list.append({ + 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context), + 'location_src_id': from_loc.id, + 'location_id': dest_loc.id, + 'route_id': new_route_id, + 'action': 'move', + 'picking_type_id': pick_type_id, + 'procure_method': warehouse.lot_stock_id.id != from_loc.id and 'make_to_order' or 'make_to_stock', # first part of the resuply route is MTS + 'warehouse_id': supplied_warehouse.id, + 'propagate_warehouse_id': warehouse.id, + }) + return pull_rules_list - def check_access_rule(self, cr, uid, ids, operation, context=None): - #override in order to redirect the check of acces rules on the stock.picking object - return self.pool.get('stock.picking').check_access_rule(cr, uid, ids, operation, context=context) + def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None): + first_rule = True + push_rules_list = [] + pull_rules_list = [] + for from_loc, dest_loc, pick_type_id in values: + push_rules_list.append({ + 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context), + 'location_from_id': from_loc.id, + 'location_dest_id': dest_loc.id, + 'route_id': new_route_id, + 'auto': 'manual', + 'picking_type_id': pick_type_id, + 'active': active, + 'warehouse_id': warehouse.id, + }) + pull_rules_list.append({ + 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context), + 'location_src_id': from_loc.id, + 'location_id': dest_loc.id, + 'route_id': new_route_id, + 'action': 'move', + 'picking_type_id': pick_type_id, + 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order', + 'active': active, + 'warehouse_id': warehouse.id, + }) + first_rule = False + return push_rules_list, pull_rules_list - def create_workflow(self, cr, uid, ids, context=None): - # overridden in order to trigger the workflow of stock.picking at the end of create, - # write and unlink operation instead of its own workflow (which is not existing) - return self.pool.get('stock.picking').create_workflow(cr, uid, ids, context=context) + def _get_mto_route(self, cr, uid, context=None): + route_obj = self.pool.get('stock.location.route') + data_obj = self.pool.get('ir.model.data') + try: + mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1] + except: + mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context) + mto_route_id = mto_route_id and mto_route_id[0] or False + if not mto_route_id: + raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.')) + return mto_route_id - def delete_workflow(self, cr, uid, ids, context=None): - # overridden in order to trigger the workflow of stock.picking at the end of create, - # write and unlink operation instead of its own workflow (which is not existing) - return self.pool.get('stock.picking').delete_workflow(cr, uid, ids, context=context) + def _check_remove_mto_resupply_rules(self, cr, uid, warehouse, context=None): + """ Checks that the moves from the different """ + pull_obj = self.pool.get('procurement.rule') + mto_route_id = self._get_mto_route(cr, uid, context=context) + rules = pull_obj.search(cr, uid, ['&', ('location_src_id', '=', warehouse.lot_stock_id.id), ('location_id.usage', '=', 'transit')], context=context) + pull_obj.unlink(cr, uid, rules, context=context) - def step_workflow(self, cr, uid, ids, context=None): - # overridden in order to trigger the workflow of stock.picking at the end of create, - # write and unlink operation instead of its own workflow (which is not existing) - return self.pool.get('stock.picking').step_workflow(cr, uid, ids, context=context) + def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None): + mto_route_id = self._get_mto_route(cr, uid, context=context) + from_loc, dest_loc, pick_type_id = values[0] + return { + 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'), + 'location_src_id': from_loc.id, + 'location_id': dest_loc.id, + 'route_id': mto_route_id, + 'action': 'move', + 'picking_type_id': pick_type_id, + 'procure_method': 'make_to_order', + 'active': True, + 'warehouse_id': warehouse.id, + } - def signal_workflow(self, cr, uid, ids, signal, context=None): - # overridden in order to fire the workflow signal on given stock.picking workflow instance - # instead of its own workflow (which is not existing) - return self.pool.get('stock.picking').signal_workflow(cr, uid, ids, signal, context=context) + def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None): + return { + 'name': self._format_routename(cr, uid, warehouse, route_name, context=context), + 'warehouse_selectable': False, + 'product_selectable': True, + 'product_categ_selectable': True, + 'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step', + 'sequence': 20, + } - def message_post(self, *args, **kwargs): - """Post the message on stock.picking to be able to see it in the form view when using the chatter""" - return self.pool.get('stock.picking').message_post(*args, **kwargs) + def create_routes(self, cr, uid, ids, warehouse, context=None): + wh_route_ids = [] + route_obj = self.pool.get('stock.location.route') + pull_obj = self.pool.get('procurement.rule') + push_obj = self.pool.get('stock.location.path') + routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context) + #create reception route and rules + route_name, values = routes_dict[warehouse.reception_steps] + route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context) + reception_route_id = route_obj.create(cr, uid, route_vals, context=context) + wh_route_ids.append((4, reception_route_id)) + push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context) + #create the push/pull rules + for push_rule in push_rules_list: + push_obj.create(cr, uid, vals=push_rule, context=context) + for pull_rule in pull_rules_list: + #all pull rules in reception route are mto, because we don't want to wait for the scheduler to trigger an orderpoint on input location + pull_rule['procure_method'] = 'make_to_order' + pull_obj.create(cr, uid, vals=pull_rule, context=context) - def message_subscribe(self, *args, **kwargs): - """Send the subscribe action on stock.picking model as it uses _name in request""" - return self.pool.get('stock.picking').message_subscribe(*args, **kwargs) + #create MTS route and pull rules for delivery and a specific route MTO to be set on the product + route_name, values = routes_dict[warehouse.delivery_steps] + route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context) + #create the route and its pull rules + delivery_route_id = route_obj.create(cr, uid, route_vals, context=context) + wh_route_ids.append((4, delivery_route_id)) + dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context) + for pull_rule in pull_rules_list: + pull_obj.create(cr, uid, vals=pull_rule, context=context) + #create MTO pull rule and link it to the generic MTO route + mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context) + mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context) - def message_unsubscribe(self, *args, **kwargs): - """Send the unsubscribe action on stock.picking model to match with subscribe""" - return self.pool.get('stock.picking').message_unsubscribe(*args, **kwargs) + #create a route for cross dock operations, that can be set on products and product categories + route_name, values = routes_dict['crossdock'] + crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context) + crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context) + wh_route_ids.append((4, crossdock_route_id)) + dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step', values, crossdock_route_id, context=context) + for pull_rule in pull_rules_list: + # Fixed cross-dock is logically mto + pull_rule['procure_method'] = 'make_to_order' + pull_obj.create(cr, uid, vals=pull_rule, context=context) - def default_get(self, cr, uid, fields_list, context=None): - # merge defaults from stock.picking with possible defaults defined on stock.picking.in - defaults = self.pool['stock.picking'].default_get(cr, uid, fields_list, context=context) - in_defaults = super(stock_picking_in, self).default_get(cr, uid, fields_list, context=context) - defaults.update(in_defaults) - return defaults + #create route selectable on the product to resupply the warehouse from another one + self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context) + + #return routes and mto pull rule to store on the warehouse + return { + 'route_ids': wh_route_ids, + 'mto_pull_id': mto_pull_id, + 'reception_route_id': reception_route_id, + 'delivery_route_id': delivery_route_id, + 'crossdock_route_id': crossdock_route_id, + } + + def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None): + picking_type_obj = self.pool.get('stock.picking.type') + pull_obj = self.pool.get('procurement.rule') + push_obj = self.pool.get('stock.location.path') + route_obj = self.pool.get('stock.location.route') + new_reception_step = new_reception_step or warehouse.reception_steps + new_delivery_step = new_delivery_step or warehouse.delivery_steps + + #change the default source and destination location and (de)activate picking types + input_loc = warehouse.wh_input_stock_loc_id + if new_reception_step == 'one_step': + input_loc = warehouse.lot_stock_id + output_loc = warehouse.wh_output_stock_loc_id + if new_delivery_step == 'ship_only': + output_loc = warehouse.lot_stock_id + picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context) + picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context) + picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context) + picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context) + + routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context) + #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it + pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context) + route_name, values = routes_dict[new_delivery_step] + route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context) + dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context) + #create the pull rules + for pull_rule in pull_rules_list: + pull_obj.create(cr, uid, vals=pull_rule, context=context) + + #update reception route and rules: unlink the existing rules of the warehouse reception route and recreate it + pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context) + push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context) + route_name, values = routes_dict[new_reception_step] + route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context) + push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context) + #create the push/pull rules + for push_rule in push_rules_list: + push_obj.create(cr, uid, vals=push_rule, context=context) + for pull_rule in pull_rules_list: + #all pull rules in reception route are mto, because we don't want to wait for the scheduler to trigger an orderpoint on input location + pull_rule['procure_method'] = 'make_to_order' + pull_obj.create(cr, uid, vals=pull_rule, context=context) + + route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context) + + #change MTO rule + dummy, values = routes_dict[new_delivery_step] + mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context) + pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context) + return True + + def create(self, cr, uid, vals, context=None): + if context is None: + context = {} + if vals is None: + vals = {} + data_obj = self.pool.get('ir.model.data') + seq_obj = self.pool.get('ir.sequence') + picking_type_obj = self.pool.get('stock.picking.type') + location_obj = self.pool.get('stock.location') + + #create view location for warehouse + wh_loc_id = location_obj.create(cr, uid, { + 'name': _(vals.get('code')), + 'usage': 'view', + 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1] + }, context=context) + vals['view_location_id'] = wh_loc_id + #create all location + def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'}) + reception_steps = vals.get('reception_steps', def_values['reception_steps']) + delivery_steps = vals.get('delivery_steps', def_values['delivery_steps']) + context_with_inactive = context.copy() + context_with_inactive['active_test'] = False + sub_locations = [ + {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'}, + {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'}, + {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'}, + {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'}, + {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'}, + ] + for values in sub_locations: + location_id = location_obj.create(cr, uid, { + 'name': values['name'], + 'usage': 'internal', + 'location_id': wh_loc_id, + 'active': values['active'], + }, context=context_with_inactive) + vals[values['field']] = location_id + + #create new sequences + in_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence in'), 'prefix': vals.get('code', '') + '/IN/', 'padding': 5}, context=context) + out_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence out'), 'prefix': vals.get('code', '') + '/OUT/', 'padding': 5}, context=context) + pack_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence packing'), 'prefix': vals.get('code', '') + '/PACK/', 'padding': 5}, context=context) + pick_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence picking'), 'prefix': vals.get('code', '') + '/PICK/', 'padding': 5}, context=context) + int_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence internal'), 'prefix': vals.get('code', '') + '/INT/', 'padding': 5}, context=context) + + #create WH + new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context) + + warehouse = self.browse(cr, uid, new_id, context=context) + wh_stock_loc = warehouse.lot_stock_id + wh_input_stock_loc = warehouse.wh_input_stock_loc_id + wh_output_stock_loc = warehouse.wh_output_stock_loc_id + wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id + + #fetch customer and supplier locations, for references + customer_loc, supplier_loc = self._get_partner_locations(cr, uid, new_id, context=context) + + #create in, out, internal picking types for warehouse + input_loc = wh_input_stock_loc + if warehouse.reception_steps == 'one_step': + input_loc = wh_stock_loc + output_loc = wh_output_stock_loc + if warehouse.delivery_steps == 'ship_only': + output_loc = wh_stock_loc + + #choose the next available color for the picking types of this warehouse + color = 0 + available_colors = [c%9 for c in range(3, 12)] # put flashy colors first + all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color') + #don't use sets to preserve the list order + for x in all_used_colors: + if x['color'] in available_colors: + available_colors.remove(x['color']) + if available_colors: + color = available_colors[0] + + #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship. + max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc') + max_sequence = max_sequence and max_sequence[0]['sequence'] or 0 + + in_type_id = picking_type_obj.create(cr, uid, vals={ + 'name': _('Receptions'), + 'warehouse_id': new_id, + 'code': 'incoming', + 'sequence_id': in_seq_id, + 'default_location_src_id': supplier_loc.id, + 'default_location_dest_id': input_loc.id, + 'sequence': max_sequence + 1, + 'color': color}, context=context) + out_type_id = picking_type_obj.create(cr, uid, vals={ + 'name': _('Delivery Orders'), + 'warehouse_id': new_id, + 'code': 'outgoing', + 'sequence_id': out_seq_id, + 'return_picking_type_id': in_type_id, + 'default_location_src_id': output_loc.id, + 'default_location_dest_id': customer_loc.id, + 'sequence': max_sequence + 4, + 'color': color}, context=context) + picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context) + int_type_id = picking_type_obj.create(cr, uid, vals={ + 'name': _('Internal Transfers'), + 'warehouse_id': new_id, + 'code': 'internal', + 'sequence_id': int_seq_id, + 'default_location_src_id': wh_stock_loc.id, + 'default_location_dest_id': wh_stock_loc.id, + 'active': True, + 'sequence': max_sequence + 2, + 'color': color}, context=context) + pack_type_id = picking_type_obj.create(cr, uid, vals={ + 'name': _('Pack'), + 'warehouse_id': new_id, + 'code': 'internal', + 'sequence_id': pack_seq_id, + 'default_location_src_id': wh_pack_stock_loc.id, + 'default_location_dest_id': output_loc.id, + 'active': delivery_steps == 'pick_pack_ship', + 'sequence': max_sequence + 3, + 'color': color}, context=context) + pick_type_id = picking_type_obj.create(cr, uid, vals={ + 'name': _('Pick'), + 'warehouse_id': new_id, + 'code': 'internal', + 'sequence_id': pick_seq_id, + 'default_location_src_id': wh_stock_loc.id, + 'default_location_dest_id': wh_pack_stock_loc.id, + 'active': delivery_steps != 'ship_only', + 'sequence': max_sequence + 2, + 'color': color}, context=context) + + #write picking types on WH + vals = { + 'in_type_id': in_type_id, + 'out_type_id': out_type_id, + 'pack_type_id': pack_type_id, + 'pick_type_id': pick_type_id, + 'int_type_id': int_type_id, + } + super(stock_warehouse, self).write(cr, uid, new_id, vals=vals, context=context) + warehouse.refresh() + + #create routes and push/pull rules + new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context) + self.write(cr, uid, warehouse.id, new_objects_dict, context=context) + return new_id + + def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None): + return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name + + def _format_routename(self, cr, uid, obj, name, context=None): + return obj.name + ': ' + name + + def get_routes_dict(self, cr, uid, ids, warehouse, context=None): + #fetch customer and supplier locations, for references + customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context) + + return { + 'one_step': (_('Reception in 1 step'), []), + 'two_steps': (_('Reception in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]), + 'three_steps': (_('Reception in 3 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.wh_qc_stock_loc_id, warehouse.int_type_id.id), (warehouse.wh_qc_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]), + 'crossdock': (_('Cross-Dock'), [(warehouse.wh_input_stock_loc_id, warehouse.wh_output_stock_loc_id, warehouse.int_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]), + 'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]), + 'pick_ship': (_('Pick + Ship'), [(warehouse.lot_stock_id, warehouse.wh_output_stock_loc_id, warehouse.pick_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]), + 'pick_pack_ship': (_('Pick + Pack + Ship'), [(warehouse.lot_stock_id, warehouse.wh_pack_stock_loc_id, warehouse.pick_type_id.id), (warehouse.wh_pack_stock_loc_id, warehouse.wh_output_stock_loc_id, warehouse.pack_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]), + } + + def _handle_renaming(self, cr, uid, warehouse, name, code, context=None): + location_obj = self.pool.get('stock.location') + route_obj = self.pool.get('stock.location.route') + pull_obj = self.pool.get('procurement.rule') + push_obj = self.pool.get('stock.location.path') + #rename location + location_id = warehouse.lot_stock_id.location_id.id + location_obj.write(cr, uid, location_id, {'name': code}, context=context) + #rename route and push-pull rules + for route in warehouse.route_ids: + route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context) + for pull in route.pull_ids: + pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context) + for push in route.push_ids: + push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context) + #change the mto pull rule name + pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context) + + def _check_delivery_resupply(self, cr, uid, warehouse, new_location, change_to_multiple, context=None): + """ Will check if the resupply routes from this warehouse follow the changes of number of delivery steps """ + #Check routes that are being delivered by this warehouse and change the rule going to transit location + route_obj = self.pool.get("stock.location.route") + pull_obj = self.pool.get("procurement.rule") + routes = route_obj.search(cr, uid, [('supplier_wh_id','=', warehouse.id)], context=context) + pulls= pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_id.usage', '=', 'transit')], context=context) + if pulls: + pull_obj.write(cr, uid, pulls, {'location_src_id': new_location, 'procure_method': change_to_multiple and "make_to_order" or "make_to_stock"}, context=context) + # Create or clean MTO rules + mto_route_id = self._get_mto_route(cr, uid, context=context) + if not change_to_multiple: + # If single delivery we should create the necessary MTO rules for the resupply + # pulls = pull_obj.search(cr, uid, ['&', ('route_id', '=', mto_route_id), ('location_id.usage', '=', 'transit'), ('location_src_id', '=', warehouse.lot_stock_id.id)], context=context) + pull_recs = pull_obj.browse(cr, uid, pulls, context=context) + transfer_locs = list(set([x.location_id for x in pull_recs])) + vals = [(warehouse.lot_stock_id , x, warehouse.out_type_id.id) for x in transfer_locs] + mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, vals, context=context) + pull_obj.create(cr, uid, mto_pull_vals, context=context) + else: + # We need to delete all the MTO pull rules, otherwise they risk to be used in the system + pulls = pull_obj.search(cr, uid, ['&', ('route_id', '=', mto_route_id), ('location_id.usage', '=', 'transit'), ('location_src_id', '=', warehouse.lot_stock_id.id)], context=context) + if pulls: + pull_obj.unlink(cr, uid, pulls, context=context) + + def _check_reception_resupply(self, cr, uid, warehouse, new_location, context=None): + """ + Will check if the resupply routes to this warehouse follow the changes of number of reception steps + """ + #Check routes that are being delivered by this warehouse and change the rule coming from transit location + route_obj = self.pool.get("stock.location.route") + pull_obj = self.pool.get("procurement.rule") + routes = route_obj.search(cr, uid, [('supplied_wh_id','=', warehouse.id)], context=context) + pulls= pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_src_id.usage', '=', 'transit')]) + if pulls: + pull_obj.write(cr, uid, pulls, {'location_id': new_location}, context=context) + + def _check_resupply(self, cr, uid, warehouse, reception_new, delivery_new, context=None): + if reception_new: + old_val = warehouse.reception_steps + new_val = reception_new + change_to_one = (old_val != 'one_step' and new_val == 'one_step') + change_to_multiple = (old_val == 'one_step' and new_val != 'one_step') + if change_to_one or change_to_multiple: + new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_input_stock_loc_id.id + self._check_reception_resupply(cr, uid, warehouse, new_location, context=context) + if delivery_new: + old_val = warehouse.delivery_steps + new_val = delivery_new + change_to_one = (old_val != 'ship_only' and new_val == 'ship_only') + change_to_multiple = (old_val == 'ship_only' and new_val != 'ship_only') + if change_to_one or change_to_multiple: + new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_output_stock_loc_id.id + self._check_delivery_resupply(cr, uid, warehouse, new_location, change_to_multiple, context=context) + + def write(self, cr, uid, ids, vals, context=None): + if context is None: + context = {} + if isinstance(ids, (int, long)): + ids = [ids] + seq_obj = self.pool.get('ir.sequence') + route_obj = self.pool.get('stock.location.route') + context_with_inactive = context.copy() + context_with_inactive['active_test'] = False + for warehouse in self.browse(cr, uid, ids, context=context_with_inactive): + #first of all, check if we need to delete and recreate route + if vals.get('reception_steps') or vals.get('delivery_steps'): + #activate and deactivate location according to reception and delivery option + self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context) + # switch between route + self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive) + # Check if we need to change something to resupply warehouses and associated MTO rules + self._check_resupply(cr, uid, warehouse, vals.get('reception_steps'), vals.get('delivery_steps'), context=context) + warehouse.refresh() + if vals.get('code') or vals.get('name'): + name = warehouse.name + #rename sequence + if vals.get('name'): + name = vals.get('name', warehouse.name) + self._handle_renaming(cr, uid, warehouse, name, vals.get('code', warehouse.code), context=context_with_inactive) + seq_obj.write(cr, uid, warehouse.in_type_id.sequence_id.id, {'name': name + _(' Sequence in'), 'prefix': vals.get('code', warehouse.code) + '\IN\\'}, context=context) + seq_obj.write(cr, uid, warehouse.out_type_id.sequence_id.id, {'name': name + _(' Sequence out'), 'prefix': vals.get('code', warehouse.code) + '\OUT\\'}, context=context) + seq_obj.write(cr, uid, warehouse.pack_type_id.sequence_id.id, {'name': name + _(' Sequence packing'), 'prefix': vals.get('code', warehouse.code) + '\PACK\\'}, context=context) + seq_obj.write(cr, uid, warehouse.pick_type_id.sequence_id.id, {'name': name + _(' Sequence picking'), 'prefix': vals.get('code', warehouse.code) + '\PICK\\'}, context=context) + seq_obj.write(cr, uid, warehouse.int_type_id.sequence_id.id, {'name': name + _(' Sequence internal'), 'prefix': vals.get('code', warehouse.code) + '\INT\\'}, context=context) + if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'): + for cmd in vals.get('resupply_wh_ids'): + if cmd[0] == 6: + new_ids = set(cmd[2]) + old_ids = set([wh.id for wh in warehouse.resupply_wh_ids]) + to_add_wh_ids = new_ids - old_ids + if to_add_wh_ids: + supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context) + self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context) + to_remove_wh_ids = old_ids - new_ids + if to_remove_wh_ids: + to_remove_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', 'in', list(to_remove_wh_ids))], context=context) + if to_remove_route_ids: + route_obj.unlink(cr, uid, to_remove_route_ids, context=context) + else: + #not implemented + pass + if 'default_resupply_wh_id' in vals: + if vals.get('default_resupply_wh_id') == warehouse.id: + raise osv.except_osv(_('Warning'),_('The default resupply warehouse should be different than the warehouse itself!')) + if warehouse.default_resupply_wh_id: + #remove the existing resupplying route on the warehouse + to_remove_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', '=', warehouse.default_resupply_wh_id.id)], context=context) + for inter_wh_route_id in to_remove_route_ids: + self.write(cr, uid, [warehouse.id], {'route_ids': [(3, inter_wh_route_id)]}) + if vals.get('default_resupply_wh_id'): + #assign the new resupplying route on all products + to_assign_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', '=', vals.get('default_resupply_wh_id'))], context=context) + for inter_wh_route_id in to_assign_route_ids: + self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}) + + return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context) + + def get_all_routes_for_wh(self, cr, uid, warehouse, context=None): + route_obj = self.pool.get("stock.location.route") + all_routes = [route.id for route in warehouse.route_ids] + all_routes += route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id)], context=context) + all_routes += [warehouse.mto_pull_id.route_id.id] + return all_routes + + def view_all_routes_for_wh(self, cr, uid, ids, context=None): + all_routes = [] + for wh in self.browse(cr, uid, ids, context=context): + all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context) + + domain = [('id', 'in', all_routes)] + return { + 'name': _('Warehouse\'s Routes'), + 'domain': domain, + 'res_model': 'stock.location.route', + 'type': 'ir.actions.act_window', + 'view_id': False, + 'view_mode': 'tree,form', + 'view_type': 'form', + 'limit': 20 + } + +class stock_location_path(osv.osv): + _name = "stock.location.path" + _description = "Pushed Flows" + _order = "name" + + def _get_rules(self, cr, uid, ids, context=None): + res = [] + for route in self.browse(cr, uid, ids, context=context): + res += [x.id for x in route.push_ids] + return res _columns = { - 'backorder_id': fields.many2one('stock.picking.in', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True), - 'state': fields.selection( - [('draft', 'Draft'), - ('auto', 'Waiting Another Operation'), - ('confirmed', 'Waiting Availability'), - ('assigned', 'Ready to Receive'), - ('done', 'Received'), - ('cancel', 'Cancelled'),], - 'Status', readonly=True, select=True, - help="""* Draft: not confirmed yet and will not be scheduled until confirmed\n - * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n - * Waiting Availability: still waiting for the availability of products\n - * Ready to Receive: products reserved, simply waiting for confirmation.\n - * Received: has been processed, can't be modified or cancelled anymore\n - * Cancelled: has been cancelled, can't be confirmed anymore"""), + 'name': fields.char('Operation Name', size=64, required=True), + 'company_id': fields.many2one('res.company', 'Company'), + 'route_id': fields.many2one('stock.location.route', 'Route'), + 'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True), + 'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True), + 'delay': fields.integer('Delay (days)', help="Number of days to do this transition"), + 'picking_type_id': fields.many2one('stock.picking.type', 'Type of the new Operation', required=True, help="This is the picking type associated with the different pickings"), + 'auto': fields.selection( + [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')], + 'Automatic Move', + required=True, select=1, + help="This is used to define paths the product has to follow within the location tree.\n" \ + "The 'Automatic Move' value will create a stock move after the current one that will be "\ + "validated automatically. With 'Manual Operation', the stock move has to be validated "\ + "by a worker. With 'Automatic No Step Added', the location is replaced in the original move." + ), + 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when the previous move is cancelled or split, the move generated by this move will too'), + 'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the rule without removing it."), + 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'), + 'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence', + store={ + 'stock.location.route': (_get_rules, ['sequence'], 10), + 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10), + }), + 'sequence': fields.integer('Sequence'), } _defaults = { - 'type': 'in', + 'auto': 'auto', + 'delay': 0, + 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c), + 'propagate': True, + 'active': True, } -class stock_picking_out(osv.osv): - _name = "stock.picking.out" - _inherit = "stock.picking" - _table = "stock_picking" - _description = "Delivery Orders" + def _apply(self, cr, uid, rule, move, context=None): + move_obj = self.pool.get('stock.move') + newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT) + if rule.auto == 'transparent': + old_dest_location = move.location_dest_id.id + move_obj.write(cr, uid, [move.id], { + 'date': newdate, + 'date_expected': newdate, + 'location_dest_id': rule.location_dest_id.id + }) + move.refresh() + #avoid looping if a push rule is not well configured + if rule.location_dest_id.id != old_dest_location: + #call again push_apply to see if a next step is defined + move_obj._push_apply(cr, uid, [move], context=context) + else: + move_id = move_obj.copy(cr, uid, move.id, { + 'location_id': move.location_dest_id.id, + 'location_dest_id': rule.location_dest_id.id, + 'date': newdate, + 'company_id': rule.company_id and rule.company_id.id or False, + 'date_expected': newdate, + 'picking_id': False, + 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False, + 'propagate': rule.propagate, + 'push_rule_id': rule.id, + 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False, + }) + move_obj.write(cr, uid, [move.id], { + 'move_dest_id': move_id, + }) + move_obj.action_confirm(cr, uid, [move_id], context=None) - def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False): - return self.pool.get('stock.picking').search(cr, user, args, offset, limit, order, context, count) - def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): - return self.pool.get('stock.picking').read(cr, uid, ids, fields=fields, context=context, load=load) +# ------------------------- +# Packaging related stuff +# ------------------------- - def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False): - return self.pool['stock.picking'].read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby) +from openerp.report import report_sxw +report_sxw.report_sxw('report.stock.quant.package.barcode', 'stock.quant.package', 'addons/stock/report/package_barcode.rml') - def check_access_rights(self, cr, uid, operation, raise_exception=True): - #override in order to redirect the check of acces rights on the stock.picking object - return self.pool.get('stock.picking').check_access_rights(cr, uid, operation, raise_exception=raise_exception) +class stock_package(osv.osv): + """ + These are the packages, containing quants and/or other packages + """ + _name = "stock.quant.package" + _description = "Physical Packages" + _parent_name = "parent_id" + _parent_store = True + _parent_order = 'name' + _order = 'parent_left' - def check_access_rule(self, cr, uid, ids, operation, context=None): - #override in order to redirect the check of acces rules on the stock.picking object - return self.pool.get('stock.picking').check_access_rule(cr, uid, ids, operation, context=context) + def name_get(self, cr, uid, ids, context=None): + res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context) + return res.items() - def create_workflow(self, cr, uid, ids, context=None): - # overridden in order to trigger the workflow of stock.picking at the end of create, - # write and unlink operation instead of its own workflow (which is not existing) - return self.pool.get('stock.picking').create_workflow(cr, uid, ids, context=context) + def _complete_name(self, cr, uid, ids, name, args, context=None): + """ Forms complete name of location from parent location to child location. + @return: Dictionary of values + """ + res = {} + for m in self.browse(cr, uid, ids, context=context): + res[m.id] = m.name + parent = m.parent_id + while parent: + res[m.id] = parent.name + ' / ' + res[m.id] + parent = parent.parent_id + return res - def delete_workflow(self, cr, uid, ids, context=None): - # overridden in order to trigger the workflow of stock.picking at the end of create, - # write and unlink operation instead of its own workflow (which is not existing) - return self.pool.get('stock.picking').delete_workflow(cr, uid, ids, context=context) + def _get_packages(self, cr, uid, ids, context=None): + """Returns packages from quants for store""" + res = set() + for quant in self.browse(cr, uid, ids, context=context): + if quant.package_id: + res.add(quant.package_id.id) + return list(res) - def step_workflow(self, cr, uid, ids, context=None): - # overridden in order to trigger the workflow of stock.picking at the end of create, - # write and unlink operation instead of its own workflow (which is not existing) - return self.pool.get('stock.picking').step_workflow(cr, uid, ids, context=context) + def _get_packages_to_relocate(self, cr, uid, ids, context=None): + res = set() + for pack in self.browse(cr, uid, ids, context=context): + res.add(pack.id) + if pack.parent_id: + res.add(pack.parent_id.id) + return list(res) - def signal_workflow(self, cr, uid, ids, signal, context=None): - # overridden in order to fire the workflow signal on given stock.picking workflow instance - # instead of its own workflow (which is not existing) - return self.pool.get('stock.picking').signal_workflow(cr, uid, ids, signal, context=context) + def _get_package_info(self, cr, uid, ids, name, args, context=None): + default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id + res = {}.fromkeys(ids, {'location_id': False, 'company_id': default_company_id, 'owner_id': False}) + for pack in self.browse(cr, uid, ids, context=context): + if pack.quant_ids: + res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id + res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False + res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id + elif pack.children_ids: + res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False + res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False + res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False + return res - def message_post(self, *args, **kwargs): - """Post the message on stock.picking to be able to see it in the form view when using the chatter""" - return self.pool.get('stock.picking').message_post(*args, **kwargs) - - def message_subscribe(self, *args, **kwargs): - """Send the subscribe action on stock.picking model as it uses _name in request""" - return self.pool.get('stock.picking').message_subscribe(*args, **kwargs) - - def message_unsubscribe(self, *args, **kwargs): - """Send the unsubscribe action on stock.picking model to match with subscribe""" - return self.pool.get('stock.picking').message_unsubscribe(*args, **kwargs) - - def default_get(self, cr, uid, fields_list, context=None): - # merge defaults from stock.picking with possible defaults defined on stock.picking.out - defaults = self.pool['stock.picking'].default_get(cr, uid, fields_list, context=context) - out_defaults = super(stock_picking_out, self).default_get(cr, uid, fields_list, context=context) - defaults.update(out_defaults) - return defaults - _columns = { - 'backorder_id': fields.many2one('stock.picking.out', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True), - 'state': fields.selection( - [('draft', 'Draft'), - ('auto', 'Waiting Another Operation'), - ('confirmed', 'Waiting Availability'), - ('assigned', 'Ready to Deliver'), - ('done', 'Delivered'), - ('cancel', 'Cancelled'),], - 'Status', readonly=True, select=True, - help="""* Draft: not confirmed yet and will not be scheduled until confirmed\n - * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n - * Waiting Availability: still waiting for the availability of products\n - * Ready to Deliver: products reserved, simply waiting for confirmation.\n - * Delivered: has been processed, can't be modified or cancelled anymore\n - * Cancelled: has been cancelled, can't be confirmed anymore"""), + 'name': fields.char('Package Reference', size=64, select=True), + 'complete_name': fields.function(_complete_name, type='char', string="Package Name",), + 'parent_left': fields.integer('Left Parent', select=1), + 'parent_right': fields.integer('Right Parent', select=1), + 'packaging_id': fields.many2one('product.packaging', 'Packaging', help="This field should be completed only if everything inside the package share the same product, otherwise it doesn't really makes sense."), + 'ul_id': fields.many2one('product.ul', 'Logistic Unit'), + 'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package", + store={ + 'stock.quant': (_get_packages, ['location_id'], 10), + 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10), + }, readonly=True), + 'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content', readonly=True), + 'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict', readonly=True), + 'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages', readonly=True), + 'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package", + store={ + 'stock.quant': (_get_packages, ['company_id'], 10), + 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10), + }, readonly=True), + 'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package", + store={ + 'stock.quant': (_get_packages, ['owner_id'], 10), + 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10), + }, readonly=True), } _defaults = { - 'type': 'out', + 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack') + } + + def _check_location_constraint(self, cr, uid, packs, context=None): + '''checks that all quants in a package are stored in the same location. This function cannot be used + as a constraint because it needs to be checked on pack operations (they may not call write on the + package) + ''' + quant_obj = self.pool.get('stock.quant') + for pack in packs: + parent = pack + while parent.parent_id: + parent = parent.parent_id + quant_ids = self.get_content(cr, uid, [parent.id], context=context) + quants = [x for x in quant_obj.browse(cr, uid, quant_ids, context=context) if x.qty > 0] + location_id = quants and quants[0].location_id.id or False + if not [quant.location_id.id == location_id for quant in quants]: + raise osv.except_osv(_('Error'), _('Everything inside a package should be in the same location')) + return True + + def action_print(self, cr, uid, ids, context=None): + if context is None: + context = {} + datas = { + 'ids': context.get('active_id') and [context.get('active_id')] or ids, + 'model': 'stock.quant.package', + 'form': self.read(cr, uid, ids)[0] + } + return { + 'type': 'ir.actions.report.xml', + 'report_name': 'stock.quant.package.barcode', + 'datas': datas + } + + def unpack(self, cr, uid, ids, context=None): + quant_obj = self.pool.get('stock.quant') + for package in self.browse(cr, uid, ids, context=context): + quant_ids = [quant.id for quant in package.quant_ids] + quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context) + children_package_ids = [child_package.id for child_package in package.children_ids] + self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context) + #delete current package since it contains nothing anymore + self.unlink(cr, uid, ids, context=context) + return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context) + + def get_content(self, cr, uid, ids, context=None): + child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context) + return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context) + + def get_content_package(self, cr, uid, ids, context=None): + quants_ids = self.get_content(cr, uid, ids, context=context) + res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context) + res['domain'] = [('id', 'in', quants_ids)] + return res + + def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None): + ''' find the total of given product 'product_id' inside the given package 'package_id''' + quant_obj = self.pool.get('stock.quant') + all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context) + total = 0 + for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context): + if quant.product_id.id == product_id: + total += quant.qty + return total + + def _get_all_products_quantities(self, cr, uid, package_id, context=None): + '''This function computes the different product quantities for the given package + ''' + quant_obj = self.pool.get('stock.quant') + res = {} + for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)): + if quant.product_id.id not in res: + res[quant.product_id.id] = 0 + res[quant.product_id.id] += quant.qty + return res + + def copy(self, cr, uid, id, default=None, context=None): + if default is None: + default = {} + if not default.get('name'): + default['name'] = self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack') + default['quant_ids'] = [] + default['children_ids'] = [] + return super(stock_package, self).copy(cr, uid, id, default, context=context) + + def copy_pack(self, cr, uid, id, default_pack_values=None, default=None, context=None): + stock_pack_operation_obj = self.pool.get('stock.pack.operation') + if default is None: + default = {} + new_package_id = self.copy(cr, uid, id, default_pack_values, context=context) + default['result_package_id'] = new_package_id + op_ids = stock_pack_operation_obj.search(cr, uid, [('result_package_id', '=', id)], context=context) + for op_id in op_ids: + stock_pack_operation_obj.copy(cr, uid, op_id, default, context=context) + + +class stock_pack_operation(osv.osv): + _name = "stock.pack.operation" + _description = "Packing Operation" + + def _get_remaining_prod_quantities(self, cr, uid, operation, context=None): + '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary''' + #if the operation doesn't concern a package, it's not relevant to call this function + if not operation.package_id or operation.product_id: + return {operation.product_id.id: operation.remaining_qty} + #get the total of products the package contains + res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context) + #reduce by the quantities linked to a move + for record in operation.linked_move_operation_ids: + if record.move_id.product_id.id not in res: + res[record.move_id.product_id.id] = 0 + res[record.move_id.product_id.id] -= record.qty + return res + + def _get_remaining_qty(self, cr, uid, ids, name, args, context=None): + uom_obj = self.pool.get('product.uom') + res = {} + for ops in self.browse(cr, uid, ids, context=context): + res[ops.id] = 0 + if ops.package_id and not ops.product_id: + #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products). + #should use _get_remaining_prod_quantities instead + continue + else: + qty = ops.product_qty + if ops.product_uom_id: + qty = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context) + for record in ops.linked_move_operation_ids: + qty -= record.qty + #converting the remaining quantity in the pack operation UoM + if ops.product_uom_id: + qty = uom_obj._compute_qty_obj(cr, uid, ops.product_id.uom_id, qty, ops.product_uom_id, context=context) + res[ops.id] = qty + return res + + def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None): + res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context) + if product_id and not product_uom_id: + product = self.pool.get('product.product').browse(cr, uid, product_id, context=context) + res['value']['product_uom_id'] = product.uom_id.id + return res + + def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None): + res = {'value': {}} + uom_obj = self.pool.get('product.uom') + if product_id: + product = self.pool.get('product.product').browse(cr, uid, product_id, context=context) + product_uom_id = product_uom_id or product.uom_id.id + selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context) + if selected_uom.category_id.id != product.uom_id.category_id.id: + res['warning'] = { + 'title': _('Warning: wrong UoM!'), + 'message': _('The selected UoM for product %s is not compatible with the UoM set on the product form. \nPlease choose an UoM within the same UoM category.') % (product.name) + } + if product_qty and 'warning' not in res: + rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True) + if rounded_qty != product_qty: + res['warning'] = { + 'title': _('Warning: wrong quantity!'), + 'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name) + } + return res + + _columns = { + 'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True), + 'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1 + 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'), + 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True), + 'qty_done': fields.float('Quantity Processed', digits_compute=dp.get_precision('Product Unit of Measure')), + 'package_id': fields.many2one('stock.quant.package', 'Package'), # 2 + 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'), + 'result_package_id': fields.many2one('stock.quant.package', 'Container Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'), + 'date': fields.datetime('Date', required=True), + 'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"), + #'update_cost': fields.boolean('Need cost update'), + 'cost': fields.float("Cost", help="Unit Cost for this product line"), + 'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'), + 'linked_move_operation_ids': fields.one2many('stock.move.operation.link', 'operation_id', string='Linked Moves', readonly=True, help='Moves impacted by this operation for the computation of the remaining quantities'), + 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'), + 'location_id': fields.many2one('stock.location', 'Location From', required=True), + 'location_dest_id': fields.many2one('stock.location', 'Location To', required=True), + 'processed': fields.selection([('true','Yes'), ('false','No')],'Has been processed?', required=True), + } + + _defaults = { + 'date': fields.date.context_today, + 'qty_done': 0, + 'processed': lambda *a: 'false', + } + + def write(self, cr, uid, ids, vals, context=None): + context = context or {} + res = super(stock_pack_operation, self).write(cr, uid, ids, vals, context=context) + if isinstance(ids, (int, long)): + ids = [ids] + if not context.get("no_recompute"): + pickings = vals.get('picking_id') and [vals['picking_id']] or list(set([x.picking_id.id for x in self.browse(cr, uid, ids, context=context)])) + self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, pickings, context=context) + return res + + def create(self, cr, uid, vals, context=None): + context = context or {} + res_id = super(stock_pack_operation, self).create(cr, uid, vals, context=context) + if vals.get("picking_id") and not context.get("no_recompute"): + self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, [vals['picking_id']], context=context) + return res_id + + def action_drop_down(self, cr, uid, ids, context=None): + ''' Used by barcode interface to say that pack_operation has been moved from src location + to destination location, if qty_done is less than product_qty than we have to split the + operation in two to process the one with the qty moved + ''' + processed_ids = [] + for pack_op in self.browse(cr, uid, ids, context=None): + op = pack_op.id + if pack_op.qty_done < pack_op.product_qty: + # we split the operation in two + op = self.copy(cr, uid, pack_op.id, {'product_qty': pack_op.qty_done, 'qty_done': pack_op.qty_done}, context=context) + self.write(cr, uid, ids, {'product_qty': pack_op.product_qty - pack_op.qty_done, 'qty_done': 0}, context=context) + processed_ids.append(op) + self.write(cr, uid, processed_ids, {'processed': 'true'}, context=context) + + def create_and_assign_lot(self, cr, uid, id, name, context=None): + ''' Used by barcode interface to create a new lot and assign it to the operation + ''' + obj = self.browse(cr,uid,id,context) + product_id = obj.product_id.id + val = {'product_id': product_id} + if name: + val.update({'name': name}) + if not obj.lot_id: + new_lot_id = self.pool.get('stock.production.lot').create(cr, uid, val, context=context) + self.write(cr, uid, id, {'lot_id': new_lot_id}, context=context) + + def _search_and_increment(self, cr, uid, picking_id, domain, filter_visible=False, visible_op_ids=False, increment=True, context=None): + '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it + + :param domain: list of tuple directly reusable as a domain + context can receive a key 'current_package_id' with the package to consider for this operation + returns True + ''' + if context is None: + context = {} + + #if current_package_id is given in the context, we increase the number of items in this package + package_clause = [('result_package_id', '=', context.get('current_package_id', False))] + existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context) + todo_operation_ids = [] + if existing_operation_ids: + if filter_visible: + todo_operation_ids = [val for val in existing_operation_ids if val in visible_op_ids] + else: + todo_operation_ids = existing_operation_ids + if todo_operation_ids: + #existing operation found for the given domain and picking => increment its quantity + operation_id = todo_operation_ids[0] + op_obj = self.browse(cr, uid, operation_id, context=context) + qty = op_obj.qty_done + if increment: + qty += 1 + else: + qty -= 1 if qty >= 1 else 0 + if qty == 0 and op_obj.product_qty == 0: + #we have a line with 0 qty set, so delete it + self.unlink(cr, uid, [operation_id], context=context) + return False + self.write(cr, uid, [operation_id], {'qty_done': qty}, context=context) + else: + #no existing operation found for the given domain and picking => create a new one + values = { + 'picking_id': picking_id, + 'product_qty': 0, + 'qty_done': 1, + } + for key in domain: + var_name, dummy, value = key + uom_id = False + if var_name == 'product_id': + uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id + update_dict = {var_name: value} + if uom_id: + update_dict['product_uom_id'] = uom_id + values.update(update_dict) + operation_id = self.create(cr, uid, values, context=context) + return operation_id + + +class stock_move_operation_link(osv.osv): + """ + Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects + """ + _name = "stock.move.operation.link" + _description = "Link between stock moves and pack operations" + + _columns = { + 'qty': fields.float('Quantity', help="Quantity of products to consider when talking about the contribution of this pack operation towards the remaining quantity of the move (and inverse). Given in the product main uom."), + 'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"), + 'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"), + 'reserved_quant_id': fields.many2one('stock.quant', 'Reserved Quant', help="Technical field containing the quant that created this link between an operation and a stock move. Used at the stock_move_obj.action_done() time to avoid seeking a matching quant again"), + } + + def get_specific_domain(self, cr, uid, record, context=None): + '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move, + having the record given as parameter making the link between the stock move and a pack operation''' + + op = record.operation_id + domain = [] + if op.package_id and op.product_id: + #if removing a product from a box, we restrict the choice of quants to this box + domain.append(('package_id', '=', op.package_id.id)) + elif op.package_id: + #if moving a box, we allow to take everything from inside boxes as well + domain.append(('package_id', 'child_of', [op.package_id.id])) + else: + #if not given any information about package, we don't open boxes + domain.append(('package_id', '=', False)) + #if lot info is given, we restrict choice to this lot otherwise we can take any + if op.lot_id: + domain.append(('lot_id', '=', op.lot_id.id)) + #if owner info is given, we restrict to this owner otherwise we restrict to no owner + if op.owner_id: + domain.append(('owner_id', '=', op.owner_id.id)) + else: + domain.append(('owner_id', '=', False)) + return domain + +class stock_warehouse_orderpoint(osv.osv): + """ + Defines Minimum stock rules. + """ + _name = "stock.warehouse.orderpoint" + _description = "Minimum Inventory Rule" + + def subtract_procurements(self, cr, uid, orderpoint, context=None): + '''This function returns quantity of product that needs to be deducted from the orderpoint computed quantity because there's already a procurement created with aim to fulfill it. + ''' + qty = 0 + uom_obj = self.pool.get("product.uom") + for procurement in orderpoint.procurement_ids: + if procurement.state in ('cancel', 'done'): + continue + procurement_qty = uom_obj._compute_qty_obj(cr, uid, procurement.product_uom, procurement.product_qty, procurement.product_id.uom_id, context=context) + for move in procurement.move_ids: + if move.state not in ('draft', 'cancel'): + #if move is already confirmed, assigned or done, the virtual stock is already taking this into account so it shouldn't be deducted + procurement_qty -= move.product_qty + qty += procurement_qty + return qty + + def _check_product_uom(self, cr, uid, ids, context=None): + ''' + Check if the UoM has the same category as the product standard UoM + ''' + if not context: + context = {} + + for rule in self.browse(cr, uid, ids, context=context): + if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id: + return False + + return True + + def action_view_proc_to_process(self, cr, uid, ids, context=None): + act_obj = self.pool.get('ir.actions.act_window') + mod_obj = self.pool.get('ir.model.data') + proc_ids = self.pool.get('procurement.order').search(cr, uid, [('orderpoint_id', 'in', ids), ('state', 'not in', ('done', 'cancel'))], context=context) + result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements') + if not result: + return False + + result = act_obj.read(cr, uid, [result[1]], context=context)[0] + result['domain'] = "[('id', 'in', [" + ','.join(map(str, proc_ids)) + "])]" + return result + + _columns = { + 'name': fields.char('Name', size=32, required=True), + 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."), + 'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True), + 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"), + 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"), + 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '=', 'product')]), + 'product_uom': fields.related('product_id', 'uom_id', type='many2one', relation='product.uom', string='Product Unit of Measure', readonly=True, required=True), + 'product_min_qty': fields.float('Minimum Quantity', required=True, + help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\ + "a procurement to bring the forecasted quantity to the Max Quantity."), + 'product_max_qty': fields.float('Maximum Quantity', required=True, + help="When the virtual stock goes below the Min Quantity, OpenERP generates "\ + "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."), + 'qty_multiple': fields.integer('Qty Multiple', required=True, + help="The procurement quantity will be rounded up to this multiple."), + 'procurement_ids': fields.one2many('procurement.order', 'orderpoint_id', 'Created Procurements'), + 'group_id': fields.many2one('procurement.group', 'Procurement Group', help="Moves created through this orderpoint will be put in this procurement group. If none is given, the moves generated by procurement rules will be grouped into one big picking."), + 'company_id': fields.many2one('res.company', 'Company', required=True), + } + _defaults = { + 'active': lambda *a: 1, + 'logic': lambda *a: 'max', + 'qty_multiple': lambda *a: 1, + 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '', + 'product_uom': lambda self, cr, uid, context: context.get('product_uom', False), + 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context) + } + _sql_constraints = [ + ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'), + ] + _constraints = [ + (_check_product_uom, 'You have to select a product unit of measure in the same category than the default unit of measure of the product', ['product_id', 'product_uom']), + ] + + def default_get(self, cr, uid, fields, context=None): + warehouse_obj = self.pool.get('stock.warehouse') + res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context) + # default 'warehouse_id' and 'location_id' + if 'warehouse_id' not in res: + warehouse_ids = res.get('company_id') and warehouse_obj.search(cr, uid, [('company_id', '=', res['company_id'])], limit=1, context=context) or [] + res['warehouse_id'] = warehouse_ids and warehouse_ids[0] or False + if 'location_id' not in res: + res['location_id'] = res.get('warehouse_id') and warehouse_obj.browse(cr, uid, res['warehouse_id'], context).lot_stock_id.id or False + return res + + def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None): + """ Finds location id for changed warehouse. + @param warehouse_id: Changed id of warehouse. + @return: Dictionary of values. + """ + if warehouse_id: + w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context) + v = {'location_id': w.lot_stock_id.id} + return {'value': v} + return {} + + def onchange_product_id(self, cr, uid, ids, product_id, context=None): + """ Finds UoM for changed product. + @param product_id: Changed id of product. + @return: Dictionary of values. + """ + if product_id: + prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context) + d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]} + v = {'product_uom': prod.uom_id.id} + return {'value': v, 'domain': d} + return {'domain': {'product_uom': []}} + + def copy_data(self, cr, uid, id, default=None, context=None): + if not default: + default = {} + default.update({ + 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '', + 'procurement_ids': [], + 'group_id': False + }) + return super(stock_warehouse_orderpoint, self).copy_data(cr, uid, id, default, context=context) + + +class stock_picking_type(osv.osv): + _name = "stock.picking.type" + _description = "The picking type determines the picking view" + _order = 'sequence' + + def open_barcode_interface(self, cr, uid, ids, context=None): + final_url = "/barcode/web/#action=stock.ui&picking_type_id=" + str(ids[0]) if len(ids) else '0' + return {'type': 'ir.actions.act_url', 'url': final_url, 'target': 'self'} + + def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None): + picking_obj = self.pool.get('stock.picking') + res = dict.fromkeys(ids, []) + for picking_type_id in ids: + #get last 10 pickings of this type + picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context) + tristates = [] + for picking in picking_obj.browse(cr, uid, picking_ids, context=context): + if picking.date_done > picking.date: + tristates.insert(0, {'tooltip': picking.name + _(': Late'), 'value': -1}) + elif picking.backorder_id: + tristates.insert(0, {'tooltip': picking.name + _(': Backorder exists'), 'value': 0}) + else: + tristates.insert(0, {'tooltip': picking.name + _(': OK'), 'value': 1}) + res[picking_type_id] = tristates + return res + + def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None): + obj = self.pool.get('stock.picking') + domains = { + 'count_picking_draft': [('state', '=', 'draft')], + 'count_picking_waiting': [('state', '=', 'confirmed')], + 'count_picking_ready': [('state', 'in', ('assigned', 'partially_available'))], + 'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))], + 'count_picking_late': [('min_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))], + 'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting', 'partially_available'))], + } + result = {} + for field in domains: + data = obj.read_group(cr, uid, domains[field] + + [('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', ids)], + ['picking_type_id'], ['picking_type_id'], context=context) + count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data)) + for tid in ids: + result.setdefault(tid, {})[field] = count.get(tid, 0) + for tid in ids: + if result[tid]['count_picking']: + result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] * 100 / result[tid]['count_picking'] + result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] * 100 / result[tid]['count_picking'] + else: + result[tid]['rate_picking_late'] = 0 + result[tid]['rate_picking_backorders'] = 0 + return result + + def onchange_picking_code(self, cr, uid, ids, picking_code=False): + if not picking_code: + return False + + obj_data = self.pool.get('ir.model.data') + stock_loc = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_stock') + + result = { + 'default_location_src_id': stock_loc, + 'default_location_dest_id': stock_loc, + } + if picking_code == 'incoming': + result['default_location_src_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_suppliers') + elif picking_code == 'outgoing': + result['default_location_dest_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_customers') + return {'value': result} + + def _get_name(self, cr, uid, ids, field_names, arg, context=None): + return dict(self.name_get(cr, uid, ids, context=context)) + + def name_get(self, cr, uid, ids, context=None): + """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """ + if context is None: + context = {} + if not isinstance(ids, list): + ids = [ids] + res = [] + if not ids: + return res + for record in self.browse(cr, uid, ids, context=context): + name = record.name + if record.warehouse_id: + name = record.warehouse_id.name + ': ' +name + if context.get('special_shortened_wh_name'): + if record.warehouse_id: + name = record.warehouse_id.name + else: + name = _('Customer') + ' (' + record.name + ')' + res.append((record.id, name)) + return res + + def _default_warehouse(self, cr, uid, context=None): + user = self.pool.get('res.users').browse(cr, uid, uid, context) + res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context) + return res and res[0] or False + + _columns = { + 'name': fields.char('Picking Type Name', translate=True, required=True), + 'complete_name': fields.function(_get_name, type='char', string='Name'), + 'color': fields.integer('Color'), + 'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"), + 'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True), + 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'), + 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'), + 'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True), + 'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'), + 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'), + 'active': fields.boolean('Active'), + + # Statistics for the kanban view + 'last_done_picking': fields.function(_get_tristate_values, + type='char', + string='Last 10 Done Pickings'), + + 'count_picking_draft': fields.function(_get_picking_count, + type='integer', multi='_get_picking_count'), + 'count_picking_ready': fields.function(_get_picking_count, + type='integer', multi='_get_picking_count'), + 'count_picking': fields.function(_get_picking_count, + type='integer', multi='_get_picking_count'), + 'count_picking_waiting': fields.function(_get_picking_count, + type='integer', multi='_get_picking_count'), + 'count_picking_late': fields.function(_get_picking_count, + type='integer', multi='_get_picking_count'), + 'count_picking_backorders': fields.function(_get_picking_count, + type='integer', multi='_get_picking_count'), + + 'rate_picking_late': fields.function(_get_picking_count, + type='integer', multi='_get_picking_count'), + 'rate_picking_backorders': fields.function(_get_picking_count, + type='integer', multi='_get_picking_count'), + + } + _defaults = { + 'warehouse_id': _default_warehouse, + 'active': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/stock/stock_data.xml b/addons/stock/stock_data.xml index 6a955d950bb..a6ebd0ab28f 100644 --- a/addons/stock/stock_data.xml +++ b/addons/stock/stock_data.xml @@ -1,58 +1,33 @@ - - - - mail.group - - notification - - Warehouse Management application installed! - Manage your product inventoy and stock locations: you can control stock moves history and planning, -watch your stock valuation, and track production lots upstream and downstream (based on serial numbers).

]]>
+ + + + First In First Out (FIFO) + fifo - - - Stock Journal Sequence - - STJ/%(year)s/ + + Last In First Out (LIFO) + lifo - - Stock Journal - STJ - general - - - - - - - Serial Number - stock.production.lot - - - Physical Locations view - terp-stock Partner Locations view - terp-partner 1 Virtual Locations view - terp-mrp 1 @@ -94,27 +69,44 @@ watch your stock valuation, and track production lots upstream and downstream (b customer - - - view - + + + Inter Company Transit + + transit + - - Delivery Orders + + + + + mail.group + + notification + + Warehouse Management application installed! + Manage your product inventoy and stock locations: you can control stock moves history and planning, +watch your stock valuation, and track production lots (based on serial numbers).

]]>
- - Output - - internal - customer - transparent - out - + + + + + Serial Number + stock.production.lot - - Stock - + + + + + + Make To Order + 10 + + - - - + + WH + + + Stock orderpoint + stock.orderpoint + + + + Stock orderpoint + stock.orderpoint + OP/ + 5 + 1 + 1 + +
diff --git a/addons/stock/stock_data.yml b/addons/stock/stock_data.yml new file mode 100644 index 00000000000..2e03bdf96b2 --- /dev/null +++ b/addons/stock/stock_data.yml @@ -0,0 +1,33 @@ +- + !python {model: res.partner}: | + main_warehouse = self.pool.get('stock.warehouse').browse(cr, uid, ref('warehouse0'), context=context) + self.write(cr, uid, ref('base.main_partner'), {'property_stock_customer':main_warehouse.lot_stock_id.id}) + +- + !python {model: ir.model.data}: | + main_warehouse = self.pool.get('stock.warehouse').browse(cr, uid, ref('warehouse0'), context=context) + + #create xml ids for demo data that are widely used in tests or in other codes, for more convenience + xml_references = [ + {'name': 'stock_location_stock', 'module': 'stock', 'model': 'stock.location', 'res_id': main_warehouse.lot_stock_id.id}, + {'name': 'stock_location_company', 'module': 'stock', 'model': 'stock.location', 'res_id': main_warehouse.wh_input_stock_loc_id.id}, + {'name':'stock_location_output','module':'stock', 'model':'stock.location','res_id':main_warehouse.wh_output_stock_loc_id.id}, + {'name':'location_pack_zone','module':'stock', 'model':'stock.location','res_id':main_warehouse.wh_pack_stock_loc_id.id}, + {'name':'picking_type_internal','module':'stock', 'model':'stock.picking.type','res_id':main_warehouse.int_type_id.id}, + {'name':'picking_type_in','module':'stock', 'model':'stock.picking.type','res_id':main_warehouse.in_type_id.id}, + {'name':'picking_type_out','module':'stock', 'model':'stock.picking.type','res_id':main_warehouse.out_type_id.id}, + ] + for xml_record in xml_references: + xml_ids = self.search(cr, uid, [('module', '=', xml_record['module']), ('model', '=', xml_record['model']), ('name', '=', xml_record['name'])], context=context) + if not xml_ids: + self.create(cr, uid, xml_record, context=context) + #avoid the xml id and the associated resource being dropped by the orm by manually making a hit on it + self._update_dummy(cr, uid, xml_record['model'], xml_record['module'], xml_record['name']) + +- + !python {model: res.company}: | + #create the transit location for each company existing + company_ids = self.search(cr, uid, [('internal_transit_location_id', '=', False)], context=context) + for company in self.browse(cr, uid, company_ids, context=context): + self.create_transit_location(cr, uid, company.id, company.name, context=context) + diff --git a/addons/stock/stock_demo.xml b/addons/stock/stock_demo.xml index d4e0f68cc78..64148c3485e 100644 --- a/addons/stock/stock_demo.xml +++ b/addons/stock/stock_demo.xml @@ -34,15 +34,7 @@ customer - - Shelf 2 - - - - Shelf 1 - - - + @@ -53,124 +45,112 @@ - - - - - 14.0 - - - - + 16.0 - + - + 16.0 - + - + 8.0 - + 18.0 - + 10.0 - + 22.0 - + 8.0 - + 26.0 - + 32.0 - + 37.0 - + 39.0 - + 45.0 - + 10.0 - + 2.0 - + 80.0 - - - - @@ -205,86 +185,14 @@ - Your Company - - - - - Your Company, Birmingham shop - - - - 1 - 82-85 Academy Avenue - Birmingham - B46 3AG - - +44 121 690 4596 - birmingham@yourcompany.com - www.yourcompany.com - - - - Donald Thompson - - - - - - - - - Your Company, Birmingham shop - - - - - - - - internal - none - Your Company, Chicago - manual - - - - - - internal - - Your Company, Birmingham shop - - - - - procurement - Internal Shippings - Chicago Warehouse - - - - - - Birmingham Warehouse - - - - - - - - property_stock_valuation_account_id - - - + Chic diff --git a/addons/stock/stock_demo.yml b/addons/stock/stock_demo.yml index d925ba4dc8e..a9a4d64c564 100644 --- a/addons/stock/stock_demo.yml +++ b/addons/stock/stock_demo.yml @@ -1,107 +1,306 @@ - - Only stock manager can create location,warehouse and product, so let's check data with giving the access rights of manager -- - !context - uid: 'res_users_stock_manager' -- - !record {model: stock.location, id: location_monitor}: - name: chicago shop - usage: internal -- - !record {model: stock.location, id: stock_location_output}: - name: Output - usage: internal -- - !record {model: stock.location, id: location_monitor_small}: - name: Small chicago shop - usage: internal - location_id: location_monitor -- - !record {model: stock.location, id: location_opening}: - name: opening - usage: inventory -- - !record {model: stock.location, id: stock_location_3}: - name: IT Suppliers - usage: supplier -- - !record {model: stock.warehouse, id: stock_warehouse_shop0}: - name: Chicago Warehouse - lot_input_id: location_monitor - lot_stock_id: location_monitor - lot_output_id: stock_location_output -- - !record {model: product.product, id: product_product_6}: - default_code: LCD15 - name: 15” LCD Monitor - type: consu - categ_id: product.product_category_8 - list_price: 1200.0 - standard_price: 800.0 - uom_id: product.product_uom_unit - uom_po_id: product.product_uom_unit - property_stock_inventory: location_opening - valuation: real_time - cost_method: average - property_stock_account_input: account.conf_o_income - property_stock_account_output: account.a_expense -- - Stock user can handled production lot,inventory and picking, so let's check data with giving the access rights of user -- - !context - uid: 'res_users_stock_user' -- - !record {model: stock.production.lot, id: lot_monitor_0}: - name: Lot0 for LCD Monitor - product_id: product_product_6 -- - !record {model: stock.production.lot, id: lot_monitor_1}: - name: Lot1 for LCD Monitor - product_id: product_product_6 -- - !record {model: stock.inventory, id: stock_inventory_0}: - name: Starting Inventory - state: draft -- - !record {model: stock.inventory.line, id: stock_inventory_line_3}: - product_id: product_product_6 - product_uom: product.product_uom_unit - inventory_id: stock_inventory_0 - product_qty: 50.0 - prod_lot_id: lot_monitor_0 - location_id: location_monitor -- - !record {model: stock.inventory.line, id: stock_inventory_line_monitor}: - product_id: product_product_6 - product_uom: product.product_uom_unit - inventory_id: stock_inventory_0 - product_qty: 40.0 - prod_lot_id: lot_monitor_1 - location_id: location_monitor + !python {model: ir.model.data}: | + chicago_warehouse = self.pool.get('stock.warehouse').browse(cr, uid, ref('stock_warehouse_shop0'), context=context) + #create xml ids for demo data that are widely used in tests or in other codes, for more convenience + xml_references = [ + {'name':'chi_picking_type_in','module':'stock', 'model':'stock.picking.type','res_id': chicago_warehouse.in_type_id.id}, + {'name':'chi_picking_type_out','module':'stock', 'model':'stock.picking.type','res_id': chicago_warehouse.out_type_id.id}, + {'name':'stock_location_shop0','module':'stock', 'model':'stock.location','res_id': chicago_warehouse.lot_stock_id.id}, + ] + for xml_record in xml_references: + xml_ids = self.search(cr, uid, [('module', '=', xml_record['module']), ('model', '=', xml_record['model']), ('name', '=', xml_record['name'])], context=context) + if not xml_ids: + self.create(cr, uid, xml_record, context=context) + #avoid the xml id and the associated resource being dropped by the orm by manually making a hit on it + self._update_dummy(cr, uid, xml_record['model'], xml_record['module'], xml_record['name']) - - !record {model: stock.picking, id: outgoing_shipment}: - type: out - location_dest_id: stock_location_output + !record {model: stock.location, id: location_refrigerator_small}: + name: Small Refrigerator + usage: internal + location_id: stock_location_14 - - !record {model: stock.move, id: outgoing_shipment_monitor}: - picking_id: outgoing_shipment - product_id: product_product_6 - product_uom: product.product_uom_unit - product_qty: 130.0 - location_id: location_monitor - location_dest_id: stock_location_output + !record {model: product.product, id: product_icecream}: + default_code: 001 + name: Ice Cream + type: product + categ_id: product.product_category_1 + list_price: 100.0 + standard_price: 70.0 + uom_id: product.product_uom_kgm + uom_po_id: product.product_uom_kgm + property_stock_inventory: location_inventory + description: Ice cream can be mass-produced and thus is widely available in developed parts of the world. Ice cream can be purchased in large cartons (vats and squrounds) from supermarkets and grocery stores, in smaller quantities from ice cream shops, convenience stores, and milk bars, and in individual servings from small carts or vans at public events. +- + !record {model: stock.production.lot, id: lot_icecream_0}: + name: Lot0 for Ice cream + product_id: product_icecream +- + !record {model: stock.production.lot, id: lot_icecream_1}: + name: Lot1 for Ice cream + product_id: product_icecream +- + !record {model: stock.inventory, id: stock_inventory_icecream}: + name: Inventory for icecream + filter: 'product' + product_id: product_icecream +- + !record {model: stock.inventory.line, id: stock_inventory_line_icecream_lot0}: + product_id: product_icecream + product_uom_id: product.product_uom_kgm + inventory_id: stock_inventory_icecream + product_qty: 50.0 + prod_lot_id: lot_icecream_0 + location_id: stock_location_14 +- + !record {model: stock.inventory.line, id: stock_inventory_line_icecream_lot1}: + product_id: product_icecream + product_uom_id: product.product_uom_kgm + inventory_id: stock_inventory_icecream + product_qty: 40.0 + prod_lot_id: lot_icecream_1 + location_id: stock_location_14 +- + Create STOCK_MOVE for OUT +- + !record {model: stock.picking, id: outgoing_shipment_main_warehouse}: + picking_type_id: stock.picking_type_out + origin: 'outgoing shipment main_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_27 + product_uom: product.product_uom_unit + product_uom_qty: 15.0 + picking_type_id: stock.picking_type_out + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers +- + !record {model: stock.picking, id: outgoing_shipment_main_warehouse1}: + picking_type_id: stock.picking_type_out + origin: 'outgoing shipment' + partner_id: base.res_partner_6 + date: !eval "'%s-%s-15' %((datetime.now()-timedelta(days=60)).year, (datetime.now()-timedelta(days=60)).month)" + move_lines: + - product_id: product.product_product_6 + product_uom: product.product_uom_unit + product_uom_qty: 180.0 + picking_type_id: stock.picking_type_out + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers + pack_operation_ids: + - product_id: product.product_product_6 + product_qty: 100 + product_uom_id: product.product_uom_unit + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers +- + !record {model: stock.picking, id: outgoing_shipment_main_warehouse2}: + picking_type_id: stock.picking_type_out + origin: 'outgoing shipment your_company warehouse' + partner_id: base.res_partner_6 + date: !eval "'%s-%s-15' % ((datetime.now()-timedelta(days=30)).month,(datetime.now()-timedelta(days=30)).month)" + move_lines: + - product_id: product.product_product_31 + product_uom: product.product_uom_unit + product_uom_qty: 45.0 + picking_type_id: stock.picking_type_out + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers +- + !record {model: stock.picking, id: outgoing_shipment_main_warehouse3}: + picking_type_id: stock.picking_type_out + origin: 'your company warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_5 + product_uom: product.product_uom_unit + product_uom_qty: 75.0 + picking_type_id: stock.picking_type_out + location_id: stock.stock_location_stock + location_dest_id: stock.stock_location_customers +- + Create STOCK_PICKING for IN - !record {model: stock.picking, id: incomming_shipment}: - type: in - invoice_state: 2binvoiced - partner_id: base.res_partner_address_9 - location_dest_id: location_monitor + picking_type_id: stock.picking_type_in + origin: 'incomming_shipment for test' - - !record {model: stock.move, id: incomming_shipment_monitor}: - picking_id: incomming_shipment - product_id: product_product_6 - product_uom: product.product_uom_unit - product_qty: 50.0 - location_id: stock_location_3 - location_dest_id: location_monitor + !record {model: stock.move, id: incomming_shipment_icecream}: + picking_id: stock.incomming_shipment + product_id: product_icecream + product_uom: product.product_uom_kgm + product_uom_qty: 50.0 + picking_type_id: stock.picking_type_in + location_id: stock_location_suppliers + location_dest_id: stock_location_14 +- + !record {model: stock.picking, id: incomming_shipment1}: + picking_type_id: stock.picking_type_in + origin: 'incomming_shipment' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_48 + product_uom: product.product_uom_unit + product_uom_qty: 35.0 + picking_type_id: stock.picking_type_in + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_stock +- + !record {model: stock.picking, id: incomming_shipment2}: + picking_type_id: stock.picking_type_in + origin: 'incomming_shipment main_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_22 + product_uom: product.product_uom_unit + product_uom_qty: 125.0 + picking_type_id: stock.picking_type_in + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_stock +- + !record {model: stock.picking, id: incomming_shipment3}: + picking_type_id: stock.picking_type_in + origin: 'incomming_shipment your_company warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_10 + product_uom: product.product_uom_unit + product_uom_qty: 120.0 + picking_type_id: stock.picking_type_in + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_stock +- + !record {model: stock.picking, id: incomming_shipment4}: + picking_type_id: stock.picking_type_in + origin: 'incomming_shipment_main_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_31 + product_uom: product.product_uom_unit + product_uom_qty: 50.0 + picking_type_id: stock.picking_type_in + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_stock +- + Create STOCK_PICKING_IN for Chicago Warehouse +- + !record {model: stock.picking, id: incomming_chicago_warehouse}: + picking_type_id: chi_picking_type_in + origin: 'incomming_chicago_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_9 + product_uom: product.product_uom_unit + product_uom_qty: 25.0 + picking_type_id: chi_picking_type_in + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_shop0 +- + !record {model: stock.picking, id: incomming_chicago_warehouse1}: + picking_type_id: chi_picking_type_in + origin: 'incomming_shipment_chicago_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_48 + product_uom: product.product_uom_unit + product_uom_qty: 180.0 + picking_type_id: chi_picking_type_in + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_shop0 + state: done + pack_operation_ids: + - product_id: product.product_product_48 + product_qty: 100 + product_uom_id: product.product_uom_unit + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_shop0 +- + !record {model: stock.picking, id: incomming_chicago_warehouse2}: + picking_type_id: chi_picking_type_in + origin: 'incomming_shipment chicago_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_32 + product_uom: product.product_uom_unit + product_uom_qty: 45.0 + picking_type_id: chi_picking_type_in + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_shop0 +- + !record {model: stock.picking, id: incomming_chicago_warehouse3}: + picking_type_id: chi_picking_type_in + origin: 'chicago_warehouse' + partner_id: base.res_partner_6 + date: !eval "'%s-%s-2' % ((datetime.now()-timedelta(days=30)).month,(datetime.now()-timedelta(days=30)).month)" + move_lines: + - product_id: product.product_product_22 + product_uom: product.product_uom_unit + product_uom_qty: 75.0 + picking_type_id: chi_picking_type_in + location_id: stock.stock_location_suppliers + location_dest_id: stock.stock_location_shop0 +- + Create STOCK_PICKING_OUT for Chicago Warehouse +- + !record {model: stock.picking, id: outgoing_chicago_warehouse}: + picking_type_id: chi_picking_type_out + origin: 'outgoing_chicago_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_27 + product_uom: product.product_uom_unit + product_uom_qty: 15.0 + picking_type_id: chi_picking_type_out + location_id: stock.stock_location_shop0 + location_dest_id: stock.stock_location_customers +- + !record {model: stock.picking, id: outgoing_chicago_warehouse1}: + picking_type_id: chi_picking_type_out + origin: 'outgoing_shipment_chicago_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_6 + product_uom: product.product_uom_unit + product_uom_qty: 180.0 + picking_type_id: chi_picking_type_out + location_id: stock.stock_location_shop0 + location_dest_id: stock.stock_location_customers + pack_operation_ids: + - product_id: product.product_product_6 + product_qty: 100 + product_uom_id: product.product_uom_unit + location_id: stock.stock_location_shop0 + location_dest_id: stock.stock_location_customers +- + !record {model: stock.picking, id: outgoing_chicago_warehouse2}: + picking_type_id: chi_picking_type_out + origin: 'chicago_warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_31 + product_uom: product.product_uom_unit + product_uom_qty: 45.0 + picking_type_id: chi_picking_type_out + location_id: stock.stock_location_shop0 + location_dest_id: stock.stock_location_customers +- + !record {model: stock.picking, id: outgoing_chicago_warehouse3}: + picking_type_id: chi_picking_type_out + origin: 'outgoing chicago warehouse' + partner_id: base.res_partner_6 + move_lines: + - product_id: product.product_product_5 + product_uom: product.product_uom_unit + product_uom_qty: 75.0 + picking_type_id: chi_picking_type_out + location_id: stock.stock_location_shop0 + location_dest_id: stock.stock_location_customers +- + !python {model: stock.picking}: | + self.action_confirm(cr, uid, [ref('outgoing_shipment_main_warehouse'),ref('outgoing_shipment_main_warehouse1'),ref('incomming_shipment2'),ref('incomming_shipment1'),ref('incomming_shipment3'),ref('outgoing_chicago_warehouse3'),ref('outgoing_chicago_warehouse2'),ref('outgoing_chicago_warehouse1'),ref('incomming_chicago_warehouse1'),ref('incomming_chicago_warehouse2'),ref('incomming_chicago_warehouse3')], context=context) + record = self.browse(cr, uid, ref('outgoing_shipment_main_warehouse1'), context=context) + record_chi_in = self.browse(cr, uid, ref('incomming_chicago_warehouse1'), context=context) + record_chi_out = self.browse(cr, uid, ref('outgoing_chicago_warehouse1'), context=context) + if record.state != 'done' and record_chi_in.state != 'done' and record_chi_out.state != 'done': + self.force_assign(cr, uid, [ref('outgoing_shipment_main_warehouse'),ref('outgoing_chicago_warehouse3'),ref('outgoing_shipment_main_warehouse2')], context=context) + self.do_transfer(cr, uid, [ref('outgoing_shipment_main_warehouse1'),ref('incomming_chicago_warehouse1'),ref('outgoing_chicago_warehouse1')], context=context) diff --git a/addons/stock/stock_demo_pre.yml b/addons/stock/stock_demo_pre.yml new file mode 100644 index 00000000000..c752ebc28da --- /dev/null +++ b/addons/stock/stock_demo_pre.yml @@ -0,0 +1,14 @@ +- + !record {model: stock.location, id: stock_location_14}: + name: Shelf 2 + posx: 0 + +- + !record {model: stock.location, id: stock_location_components}: + name: Shelf 1 + posx: 0 + +- + !python {model: ir.model.data}: | + main_warehouse = self.pool.get('stock.warehouse').browse(cr, uid, ref('warehouse0'), context=context) + self.pool.get('stock.location').write(cr, uid, [ref('stock_location_14'), ref('stock_location_components')], {'location_id':main_warehouse.lot_stock_id.id}, context=context) diff --git a/addons/stock/stock_location_demo_cpu1.xml b/addons/stock/stock_location_demo_cpu1.xml new file mode 100644 index 00000000000..8cc0f8ce8e2 --- /dev/null +++ b/addons/stock/stock_location_demo_cpu1.xml @@ -0,0 +1,19 @@ + + + + This product is configured with example of push/pull flows + + + + + 20.0 + 10.0 + + + + + + + + + diff --git a/addons/stock/stock_location_demo_cpu3.yml b/addons/stock/stock_location_demo_cpu3.yml new file mode 100644 index 00000000000..65ab318df6d --- /dev/null +++ b/addons/stock/stock_location_demo_cpu3.yml @@ -0,0 +1,26 @@ +- + !record {model: stock.location, id: location_order}: + name: Order Processing + usage: internal + location_id: stock.stock_location_company +- + !record {model: stock.location, id: location_dispatch_zone}: + name: Dispatch Zone + usage: internal + location_id: location_order +- + !record {model: stock.location, id: location_gate_a}: + name: Gate A + usage: internal + location_id: location_dispatch_zone +- + !record {model: stock.location, id: location_gate_b}: + name: Gate B + usage: internal + location_id: location_dispatch_zone +- + !record {model: stock.location.path, id: push_pick}: + name: Pick List + location_from_id: stock.stock_location_output + location_dest_id: location_pack_zone + picking_type_id: stock.picking_type_internal diff --git a/addons/procurement/stock_orderpoint.xml b/addons/stock/stock_orderpoint.xml similarity index 84% rename from addons/procurement/stock_orderpoint.xml rename to addons/stock/stock_orderpoint.xml index 67d610c65c9..5bbca72765b 100644 --- a/addons/procurement/stock_orderpoint.xml +++ b/addons/stock/stock_orderpoint.xml @@ -9,7 +9,7 @@ - + 10.0 @@ -17,7 +17,7 @@ - + 12.0 @@ -25,7 +25,7 @@ - + 50.0 @@ -33,7 +33,7 @@ - + 15.0 @@ -41,7 +41,7 @@ - + 5.0 @@ -49,7 +49,7 @@ - + \ No newline at end of file diff --git a/addons/stock/stock_orderpoint.yml b/addons/stock/stock_orderpoint.yml new file mode 100644 index 00000000000..3c4eb6e9961 --- /dev/null +++ b/addons/stock/stock_orderpoint.yml @@ -0,0 +1,6 @@ +- + !python {model: stock.location}: | + main_warehouse = self.pool.get('stock.warehouse').browse(cr, uid, ref('warehouse0'), context=context) + main_stock = main_warehouse.lot_stock_id.id + stowar_op_ids = self.pool.get('stock.warehouse.orderpoint').search(cr, uid, [], context=context) + self.pool.get('stock.warehouse.orderpoint').write(cr,uid,stowar_op_ids,{'location_id':main_stock}, context=context) diff --git a/addons/stock/stock_report.xml b/addons/stock/stock_report.xml index 53b89dcf41f..f5c98068ef9 100644 --- a/addons/stock/stock_report.xml +++ b/addons/stock/stock_report.xml @@ -1,13 +1,25 @@ + + + - - - - - - - + + diff --git a/addons/stock/stock_sequence.xml b/addons/stock/stock_sequence.xml index c3569c48c3e..1656f7d5b59 100644 --- a/addons/stock/stock_sequence.xml +++ b/addons/stock/stock_sequence.xml @@ -24,21 +24,7 @@ Sequences for pickings --> - - Picking IN - stock.picking.in - IN/ - 5 - - - - - Picking OUT - stock.picking.out - OUT/ - 5 - - + Picking INT @@ -65,6 +51,7 @@ + Packs stock.lot.tracking @@ -79,5 +66,19 @@ 1 + + + + Packages + stock.quant.package + + + + Packages + stock.quant.package + PACK + 7 + + diff --git a/addons/stock/stock_view.xml b/addons/stock/stock_view.xml index ac6636147c1..06aba6e66ea 100644 --- a/addons/stock/stock_view.xml +++ b/addons/stock/stock_view.xml @@ -8,15 +8,14 @@ groups="group_stock_manager,group_stock_user" sequence="70"/> - - + + parent="stock.menu_stock_product" sequence="0" groups="base.group_no_one"/> - + @@ -49,33 +48,11 @@ - - -
- - - - - - - - stock.tracking.tree - stock.tracking - - - - - - - - - - Packs - ir.actions.act_window - stock.tracking - form - - -

- Click to add a tracking number. -

- This is the list of all your packs. When you select a Pack, you - can get the upstream or downstream traceability of the products - contained in the pack. -

-
-
- - - stock.tracking.tree - stock.tracking - child_ids - - - - - - - - - - - - Pack Search - stock.tracking - - - - - - - - - - - stock.production.lot.revision.form - stock.production.lot.revision - -
- - - - - - - - - - -
- - stock.production.lot.revision.tree - stock.production.lot.revision - - - - - - - - - stock.production.lot.form stock.production.lot
-
- + - - - - - - - - - - - - - + + + + - - - - - + - - @@ -413,12 +229,10 @@ stock.production.lot - - - + @@ -428,9 +242,7 @@ stock.production.lot - - - + @@ -440,7 +252,7 @@ - Serial Number + Serial Numbers ir.actions.act_window stock.production.lot form @@ -452,9 +264,9 @@ Click to add a serial number.

This is the list of all the production lots you recorded. When - you select a lot, you can get the upstream or downstream + you select a lot, you can get the traceability of the products contained in lot. By default, the - list is filtred on the serial numbers that are available in + list is filtered on the serial numbers that are available in your warehouse but you can uncheck the 'Available' button to get all the lots you produced, received or delivered to customers. @@ -471,14 +283,11 @@ Stock Moves stock.move - move_history_ids - + - - @@ -494,14 +303,11 @@ Stock Moves stock.move - move_history_ids2 - + - - @@ -546,40 +352,43 @@ + + {'search_default_productgroup': 1} + [('location_id', 'child_of', active_ids)] + Quants + stock.quant + + stock.location.form stock.location +

+
+ + + product.putaway.form + product.putaway + + + + + + +
+ + + + + + + + +
+ +
+
+ + + product.removal.form + product.removal + +
+ + + + +
+ + + stock.location.path.tree + stock.location.path + + + + + + + + + + + stock.location.path.form + stock.location.path + +
+ + + + + + + + + + + + +
+
+
+ + + product.category.form + product.category + + + + + +
+

+ The following routes will apply to the products in this category taking into account parent categories: + +

+
+ +
+
+
+
+ Locations @@ -647,68 +546,62 @@ - - stock.location.tree - stock.location - child_ids - - - - - - - - {'product_id': active_id} - Stock by Location - stock.location - + {'search_default_done': 1,'search_default_product_id': active_id, 'default_product_id': active_id} Moves stock.move - - Location Structure - stock.location - ir.actions.act_window - [('location_id','=',False)] - tree - - -

- Click to add a location. -

- This is the structure of your company's warehouses and - locations. You can click on a location to get the list of the - products and their stock level in this particular location and - all its children. -

-
-
- stock.warehouse stock.warehouse
-
@@ -718,9 +611,7 @@ - - @@ -752,7 +643,7 @@ - + @@ -764,13 +655,15 @@ - - + - - - + + + + + +
@@ -780,55 +673,101 @@ stock.picking -
+
-
+
+

- + - - - + + - + + + + - + - - + + + + + + +
+
+ + +
@@ -837,37 +776,169 @@ stock.picking.internal.search stock.picking - - - - + + + + + + + + + + - + + - - + + + - - Internal Moves + + Stock Operations stock.picking ir.actions.act_window form tree,form,calendar - [('type','=','internal')] - {'contact_display': 'partner_address', 'search_default_available': 1} + + { + 'contact_display': 'partner_address', + } + + + + + + Done Transfers + stock.picking + ir.actions.act_window + form + tree,form,calendar + + { + 'search_default_picking_type_id': [active_id], + 'default_picking_type_id': active_id, + 'contact_display': 'partner_address', + 'search_default_done': 1, + } + + + + + + Ready Transfers + stock.picking + ir.actions.act_window + form + tree,form,calendar + + { + 'search_default_picking_type_id': [active_id], + 'default_picking_type_id': active_id, + 'contact_display': 'partner_address', + 'search_default_available': 1, + } + + + + + + Done Transfers by Date + stock.picking + ir.actions.act_window + form + tree,form,calendar + + { + 'search_default_picking_type_id': [active_id], + 'default_picking_type_id': active_id, + 'contact_display': 'partner_address', + 'search_default_done': 1, + 'group_by': ['date'], + } + + + + + + Waiting Availability Transfers + stock.picking + ir.actions.act_window + form + tree,form,calendar + + { + 'search_default_picking_type_id': [active_id], + 'default_picking_type_id': active_id, + 'contact_display': 'partner_address', + 'search_default_waiting': 1, + } + + + + + + Late Transfers + stock.picking + ir.actions.act_window + form + tree,form,calendar + + { + 'search_default_picking_type_id': [active_id], + 'default_picking_type_id': active_id, + 'contact_display': 'partner_address', + 'search_default_late': 1, + 'search_default_confirmed': 1, + } + + + + + + Backorders + stock.picking + ir.actions.act_window + form + tree,form,calendar + + { + 'search_default_picking_type_id': [active_id], + 'default_picking_type_id': active_id, + 'contact_display': 'partner_address', + 'search_default_backorder': 1, + 'search_default_confirmed': 1, + } + + + + + + Transfers + stock.picking + ir.actions.act_window + form + tree,form,calendar + + { + 'search_default_picking_type_id': [active_id], + 'default_picking_type_id': active_id, + 'contact_display': 'partner_address', + } +

- Click to create an internal move request. + Click to create a stock operation.

Most operations are prepared automatically by OpenERP according to your preconfigured logistics rules, but you can also record @@ -876,279 +947,17 @@ - - - tree - - - - - - form - - - - - - - stock.picking.out.calendar - stock.picking.out - + + stock.move.graph + stock.move - - - - - + + + + + - - - stock.picking.out.tree - stock.picking.out - - - - - - - - - - - - - - - - stock.picking.out.form - stock.picking.out - - - - Date of Delivery - - -

-
@@ -1319,23 +1088,23 @@ stock.move.form stock.move - + - +
- - - - - - - - - - - - - - - - + + + + + + + + + + + + + +
@@ -1396,7 +1143,7 @@ - + @@ -1407,12 +1154,9 @@ - - - @@ -1456,6 +1200,13 @@ + + + graph + + + + stock.incoterms.tree @@ -1595,149 +1315,772 @@ - - - tree_but_open - stock.location - Products - - - - - - tree_but_open - stock.location - Open Products - - - - Customers Packings - stock.picking - ir.actions.act_window - form - tree,form,calendar - [('type','=','out')] - {'default_type': 'out', 'contact_display': 'partner',"search_default_available":1} - - - - - tree - - - - - - form - - - - - - calendar - - - - - Deliver Products - stock.move - ir.actions.act_window - form - tree,form - ['|','&',('picking_id','=',False),('location_dest_id.usage', 'in', ['customer','supplier']),'&',('picking_id','!=',False),('picking_id.type','=','out')] - - {'picking_type': 'out', 'search_default_future': True} - -

- Click to register a product delivery. -

-

- You will find in this list all products you have to deliver to - your customers. You can process the deliveries directly from - this list using the buttons on the right of each line. You can - filter the products to deliver by customer, products or sale - order (using the Origin field). -

-
-
- - - - tree - - - - - - form - - - - - - - - - - stock.journal.filter - stock.journal + + stock.picking.type.filter + stock.picking.type - - - + + + + - - Stock Journals - stock.journal + + Picking types + stock.picking.type - + - + + - - Stock Journals - stock.journal + + Picking Types + stock.picking.type -
+ - - + + + + + + + + + + + + + + + +
- - Stock Journals - stock.journal + + + + stock.picking.type.kanban + stock.picking.type + + + + + + + + + + + +
+
+ í +
+
+

+
+ + Click to launch the barcode interface + +
+ +
+ Late (%%) + Backorders (%%) + +
+ +
+
+
+
+
+
+
+ + + All Operations + stock.picking.type ir.actions.act_window form + kanban,form

- Click to create a new journal. + Click to create a new picking type.

- The stock journal system allows you to assign each stock - operation to a specific journal according to the type of - operation to perform or the worker/team that should perform the - operation. Examples of stock journals may be: quality control, - pick lists, packing, etc. + The picking type system allows you to assign each stock + operation a specific type which will alter its views accordingly. + On the picking type you could e.g. specify if packing is needed by default, + if it should show the customer.

- + + + All Operations + stock.picking.type + ir.actions.act_window + form + list,form + + + + + + + + + stock.warehouse.orderpoint.tree + stock.warehouse.orderpoint + + + + + + + + + + + + + + + stock.warehouse.orderpoint.search + stock.warehouse.orderpoint + + + + + + + + + + + + + + + + + stock.warehouse.orderpoint.form + stock.warehouse.orderpoint + +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + + Reordering Rules + stock.warehouse.orderpoint + ir.actions.act_window + form + + + +

+ Click to add a reordering rule. +

You can define your minimum stock rules, so that OpenERP will automatically create draft manufacturing orders or request for quotations according to the stock level. Once the virtual stock of a product (= stock on hand minus all confirmed orders and reservations) is below the minimum quantity, OpenERP will generate a procurement request to increase the stock up to the maximum quantity.

+
+
+ + + + + + + procurement.order.form.stock.inherit + procurement.order + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + stock.quant.tree + stock.quant + + + + + + + + + + + + + + + + + + + + + stock.quant.graph + stock.quant + + + + + + + + + + + + + + + + + + + + + + + + + {'default_product_id': active_id, 'search_default_product_id': active_id} + Reordering Rules + stock.warehouse.orderpoint + + + {'search_default_product_id': active_id, 'search_default_locationgroup':1} + Quants + stock.quant + + + + + product.template.procurement + product.product + + + + + + + + + --> + + product.search.procurment.form + product.product + + + + + + + + + + product.normal.procurement.locations.inherit + product.product + + + + + + + + + + + + +
+
+
-
@@ -64,69 +34,12 @@ Scrap Move ir.actions.act_window stock.move.scrap + form form new {'form_view_ref': False}
- - Split in Serial Numbers - stock.move.split - - - - - - - - - - - - - - - - - - - - - - -
- - - - -
-
-
-
- -
-
- - - Split in Serial Numbers - ir.actions.act_window - stock.move.split - form - form - new - {'form_view_ref': False} - - diff --git a/addons/stock/wizard/stock_partial_move.py b/addons/stock/wizard/stock_partial_move.py deleted file mode 100644 index e1956e202c9..00000000000 --- a/addons/stock/wizard/stock_partial_move.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-TODAY OpenERP SA (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## - -from openerp.osv import fields, osv -from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT -import time -from openerp.tools.translate import _ - -class stock_partial_move_line(osv.osv_memory): - _inherit = "stock.partial.picking.line" - _name = "stock.partial.move.line" - _columns = { - 'wizard_id' : fields.many2one('stock.partial.move', string="Wizard", ondelete='CASCADE'), - } - -class stock_partial_move(osv.osv_memory): - _name = "stock.partial.move" - _inherit = 'stock.partial.picking' - _description = "Partial Move Processing Wizard" - _columns = { - 'date': fields.datetime('Date', required=True), - 'move_ids' : fields.one2many('stock.partial.move.line', 'wizard_id', 'Moves'), - - # picking_id is not used for move processing, so we remove the required attribute - # from the inherited column, and ignore it - 'picking_id': fields.many2one('stock.picking', 'Picking'), - } - - def default_get(self, cr, uid, fields, context=None): - if context is None: context = {} - # no call to super! - res = {} - move_ids = context.get('active_ids', []) - if not move_ids or not context.get('active_model') == 'stock.move': - return res - if 'move_ids' in fields: - move_ids = self.pool.get('stock.move').browse(cr, uid, move_ids, context=context) - moves = [self._partial_move_for(cr, uid, m) for m in move_ids if m.state not in ('done','cancel')] - res.update(move_ids=moves) - if 'date' in fields: - res.update(date=time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) - return res - - def do_partial(self, cr, uid, ids, context=None): - # no call to super! - assert len(ids) == 1, 'Partial move processing may only be done one form at a time.' - partial = self.browse(cr, uid, ids[0], context=context) - partial_data = { - 'delivery_date' : partial.date - } - moves_ids = [] - for move in partial.move_ids: - if not move.move_id: - raise osv.except_osv(_('Warning !'), _("You have manually created product lines, please delete them to proceed")) - move_id = move.move_id.id - partial_data['move%s' % (move_id)] = { - 'product_id': move.product_id.id, - 'product_qty': move.quantity, - 'product_uom': move.product_uom.id, - 'prodlot_id': move.prodlot_id.id, - } - moves_ids.append(move_id) - if (move.move_id.picking_id.type == 'in') and (move.product_id.cost_method == 'average'): - partial_data['move%s' % (move_id)].update(product_price=move.cost, - product_currency=move.currency.id) - self.pool.get('stock.move').do_partial(cr, uid, moves_ids, partial_data, context=context) - return {'type': 'ir.actions.act_window_close'} - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/stock/wizard/stock_partial_move_view.xml b/addons/stock/wizard/stock_partial_move_view.xml deleted file mode 100644 index 78d30ee7481..00000000000 --- a/addons/stock/wizard/stock_partial_move_view.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - Deliver/Receive Products - - code - action = obj.action_partial_move(context=context) - - - - - - Deliver/Receive Products - - - - - stock.partial.move.form - stock.partial.move - -
- - -
-
- -
-
- - - stock.partial.move.line.list - stock.partial.move.line - - - - - - - - - - - - - - - - - stock.partial.move.line.form - stock.partial.move.line - -
- - - - - - - - - - - -
-
-
-
-
diff --git a/addons/stock/wizard/stock_partial_picking.py b/addons/stock/wizard/stock_partial_picking.py deleted file mode 100644 index ceedb682ed8..00000000000 --- a/addons/stock/wizard/stock_partial_picking.py +++ /dev/null @@ -1,217 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-TODAY OpenERP SA (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## - -import time -from lxml import etree -from openerp.osv import fields, osv -from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT -from openerp.tools.float_utils import float_compare -import openerp.addons.decimal_precision as dp -from openerp.tools.translate import _ - -class stock_partial_picking_line(osv.TransientModel): - - def _tracking(self, cursor, user, ids, name, arg, context=None): - res = {} - for tracklot in self.browse(cursor, user, ids, context=context): - tracking = False - if (tracklot.move_id.picking_id.type == 'in' and tracklot.product_id.track_incoming == True) or \ - (tracklot.move_id.picking_id.type == 'out' and tracklot.product_id.track_outgoing == True): - tracking = True - res[tracklot.id] = tracking - return res - - _name = "stock.partial.picking.line" - _rec_name = 'product_id' - _columns = { - 'product_id' : fields.many2one('product.product', string="Product", required=True, ondelete='CASCADE'), - 'quantity' : fields.float("Quantity", digits_compute=dp.get_precision('Product Unit of Measure'), required=True), - 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, ondelete='CASCADE'), - 'prodlot_id' : fields.many2one('stock.production.lot', 'Serial Number', ondelete='CASCADE'), - 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete='CASCADE', domain = [('usage','<>','view')]), - 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', required=True, ondelete='CASCADE',domain = [('usage','<>','view')]), - 'move_id' : fields.many2one('stock.move', "Move", ondelete='CASCADE'), - 'wizard_id' : fields.many2one('stock.partial.picking', string="Wizard", ondelete='CASCADE'), - 'update_cost': fields.boolean('Need cost update'), - 'cost' : fields.float("Cost", help="Unit Cost for this product line", digits_compute=dp.get_precision('Product Price')), - 'currency' : fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'), - 'tracking': fields.function(_tracking, string='Tracking', type='boolean'), - } - - def onchange_product_id(self, cr, uid, ids, product_id, context=None): - uom_id = False - if product_id: - product = self.pool.get('product.product').browse(cr, uid, product_id, context=context) - uom_id = product.uom_id.id - return {'value': {'product_uom': uom_id}} - - -class stock_partial_picking(osv.osv_memory): - _name = "stock.partial.picking" - _rec_name = 'picking_id' - _description = "Partial Picking Processing Wizard" - - def _hide_tracking(self, cursor, user, ids, name, arg, context=None): - res = {} - for wizard in self.browse(cursor, user, ids, context=context): - res[wizard.id] = any([not(x.tracking) for x in wizard.move_ids]) - return res - - _columns = { - 'date': fields.datetime('Date', required=True), - 'move_ids' : fields.one2many('stock.partial.picking.line', 'wizard_id', 'Product Moves'), - 'picking_id': fields.many2one('stock.picking', 'Picking', required=True, ondelete='CASCADE'), - 'hide_tracking': fields.function(_hide_tracking, string='Tracking', type='boolean', help='This field is for internal purpose. It is used to decide if the column production lot has to be shown on the moves or not.'), - } - - def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): - #override of fields_view_get in order to change the label of the process button and the separator accordingly to the shipping type - if context is None: - context={} - res = super(stock_partial_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) - type = context.get('default_type', False) - if type: - doc = etree.XML(res['arch']) - for node in doc.xpath("//button[@name='do_partial']"): - if type == 'in': - node.set('string', _('_Receive')) - elif type == 'out': - node.set('string', _('_Deliver')) - for node in doc.xpath("//separator[@name='product_separator']"): - if type == 'in': - node.set('string', _('Receive Products')) - elif type == 'out': - node.set('string', _('Deliver Products')) - res['arch'] = etree.tostring(doc) - return res - - def default_get(self, cr, uid, fields, context=None): - if context is None: context = {} - res = super(stock_partial_picking, self).default_get(cr, uid, fields, context=context) - picking_ids = context.get('active_ids', []) - active_model = context.get('active_model') - - if not picking_ids or len(picking_ids) != 1: - # Partial Picking Processing may only be done for one picking at a time - return res - assert active_model in ('stock.picking', 'stock.picking.in', 'stock.picking.out'), 'Bad context propagation' - picking_id, = picking_ids - if 'picking_id' in fields: - res.update(picking_id=picking_id) - if 'move_ids' in fields: - picking = self.pool.get('stock.picking').browse(cr, uid, picking_id, context=context) - moves = [self._partial_move_for(cr, uid, m) for m in picking.move_lines if m.state not in ('done','cancel')] - res.update(move_ids=moves) - if 'date' in fields: - res.update(date=time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) - return res - - def _product_cost_for_average_update(self, cr, uid, move): - """Returns product cost and currency ID for the given move, suited for re-computing - the average product cost. - - :return: map of the form:: - - {'cost': 123.34, - 'currency': 42} - """ - # Currently, the cost on the product form is supposed to be expressed in the currency - # of the company owning the product. If not set, we fall back to the picking's company, - # which should work in simple cases. - product_currency_id = move.product_id.company_id.currency_id and move.product_id.company_id.currency_id.id - picking_currency_id = move.picking_id.company_id.currency_id and move.picking_id.company_id.currency_id.id - return {'cost': move.product_id.standard_price, - 'currency': product_currency_id or picking_currency_id or False} - - def _partial_move_for(self, cr, uid, move): - partial_move = { - 'product_id' : move.product_id.id, - 'quantity' : move.product_qty if move.state == 'assigned' or move.picking_id.type == 'in' else 0, - 'product_uom' : move.product_uom.id, - 'prodlot_id' : move.prodlot_id.id, - 'move_id' : move.id, - 'location_id' : move.location_id.id, - 'location_dest_id' : move.location_dest_id.id, - } - if move.picking_id.type == 'in' and move.product_id.cost_method == 'average': - partial_move.update(update_cost=True, **self._product_cost_for_average_update(cr, uid, move)) - return partial_move - - def do_partial(self, cr, uid, ids, context=None): - assert len(ids) == 1, 'Partial picking processing may only be done one at a time.' - stock_picking = self.pool.get('stock.picking') - stock_move = self.pool.get('stock.move') - uom_obj = self.pool.get('product.uom') - partial = self.browse(cr, uid, ids[0], context=context) - partial_data = { - 'delivery_date' : partial.date - } - picking_type = partial.picking_id.type - for wizard_line in partial.move_ids: - line_uom = wizard_line.product_uom - move_id = wizard_line.move_id.id - - #Quantiny must be Positive - if wizard_line.quantity < 0: - raise osv.except_osv(_('Warning!'), _('Please provide proper Quantity.')) - - #Compute the quantity for respective wizard_line in the line uom (this jsut do the rounding if necessary) - qty_in_line_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, line_uom.id) - - if line_uom.factor and line_uom.factor <> 0: - if float_compare(qty_in_line_uom, wizard_line.quantity, precision_rounding=line_uom.rounding) != 0: - raise osv.except_osv(_('Warning!'), _('The unit of measure rounding does not allow you to ship "%s %s", only rounding of "%s %s" is accepted by the Unit of Measure.') % (wizard_line.quantity, line_uom.name, line_uom.rounding, line_uom.name)) - if move_id: - #Check rounding Quantity.ex. - #picking: 1kg, uom kg rounding = 0.01 (rounding to 10g), - #partial delivery: 253g - #=> result= refused, as the qty left on picking would be 0.747kg and only 0.75 is accepted by the uom. - initial_uom = wizard_line.move_id.product_uom - #Compute the quantity for respective wizard_line in the initial uom - qty_in_initial_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, initial_uom.id) - without_rounding_qty = (wizard_line.quantity / line_uom.factor) * initial_uom.factor - if float_compare(qty_in_initial_uom, without_rounding_qty, precision_rounding=initial_uom.rounding) != 0: - raise osv.except_osv(_('Warning!'), _('The rounding of the initial uom does not allow you to ship "%s %s", as it would let a quantity of "%s %s" to ship and only rounding of "%s %s" is accepted by the uom.') % (wizard_line.quantity, line_uom.name, wizard_line.move_id.product_qty - without_rounding_qty, initial_uom.name, initial_uom.rounding, initial_uom.name)) - else: - seq_obj_name = 'stock.picking.' + picking_type - move_id = stock_move.create(cr,uid,{'name' : self.pool.get('ir.sequence').get(cr, uid, seq_obj_name), - 'product_id': wizard_line.product_id.id, - 'product_qty': wizard_line.quantity, - 'product_uom': wizard_line.product_uom.id, - 'prodlot_id': wizard_line.prodlot_id.id, - 'location_id' : wizard_line.location_id.id, - 'location_dest_id' : wizard_line.location_dest_id.id, - 'picking_id': partial.picking_id.id - },context=context) - stock_move.action_confirm(cr, uid, [move_id], context) - partial_data['move%s' % (move_id)] = { - 'product_id': wizard_line.product_id.id, - 'product_qty': wizard_line.quantity, - 'product_uom': wizard_line.product_uom.id, - 'prodlot_id': wizard_line.prodlot_id.id, - } - if (picking_type == 'in') and (wizard_line.product_id.cost_method == 'average'): - partial_data['move%s' % (wizard_line.move_id.id)].update(product_price=wizard_line.cost, - product_currency=wizard_line.currency.id) - stock_picking.do_partial(cr, uid, [partial.picking_id.id], partial_data, context=context) - return {'type': 'ir.actions.act_window_close'} - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/stock/wizard/stock_partial_picking_view.xml b/addons/stock/wizard/stock_partial_picking_view.xml deleted file mode 100644 index f4bab484483..00000000000 --- a/addons/stock/wizard/stock_partial_picking_view.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - Process Picking - stock.partial.picking - form - form - new - - - - - stock.partial.picking.form - stock.partial.picking - -
- - - - - - - - - - - - - - - -
-
- -
-
- - - stock.partial.picking.line.list - stock.partial.picking.line - - - - - - - - - - - - - - - - stock.partial.picking.line.form - stock.partial.picking.line - -
- - - - - - - - - - - - -
-
-
-
-
diff --git a/addons/stock/wizard/stock_return_picking.py b/addons/stock/wizard/stock_return_picking.py index 57ca03a8205..112b233bf1f 100644 --- a/addons/stock/wizard/stock_return_picking.py +++ b/addons/stock/wizard/stock_return_picking.py @@ -19,33 +19,29 @@ # ############################################################################## -import time - -from openerp.osv import osv,fields +from openerp.osv import osv, fields from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp -class stock_return_picking_memory(osv.osv_memory): - _name = "stock.return.picking.memory" +class stock_return_picking_line(osv.osv_memory): + _name = "stock.return.picking.line" _rec_name = 'product_id' _columns = { - 'product_id' : fields.many2one('product.product', string="Product", required=True), - 'quantity' : fields.float("Quantity", digits_compute=dp.get_precision('Product Unit of Measure'), required=True), - 'wizard_id' : fields.many2one('stock.return.picking', string="Wizard"), - 'move_id' : fields.many2one('stock.move', "Move"), - 'prodlot_id': fields.related('move_id', 'prodlot_id', type='many2one', relation='stock.production.lot', string='Serial Number', readonly=True), - + 'product_id': fields.many2one('product.product', string="Product", required=True), + 'quantity': fields.float("Quantity", digits_compute=dp.get_precision('Product Unit of Measure'), required=True), + 'wizard_id': fields.many2one('stock.return.picking', string="Wizard"), + 'move_id': fields.many2one('stock.move', "Move"), + 'lot_id': fields.many2one('stock.production.lot', 'Serial Number', help="Used to choose the lot/serial number of the product returned"), } - class stock_return_picking(osv.osv_memory): _name = 'stock.return.picking' _description = 'Return Picking' _columns = { - 'product_return_moves' : fields.one2many('stock.return.picking.memory', 'wizard_id', 'Moves'), - 'invoice_state': fields.selection([('2binvoiced', 'To be refunded/invoiced'), ('none', 'No invoicing')], 'Invoicing',required=True), + 'product_return_moves': fields.one2many('stock.return.picking.line', 'wizard_id', 'Moves'), + 'move_dest_exists': fields.boolean('Chained Move Exists', readonly=True, help="Technical field used to hide help tooltip if not needed"), } def default_get(self, cr, uid, fields, context=None): @@ -63,78 +59,102 @@ class stock_return_picking(osv.osv_memory): context = {} res = super(stock_return_picking, self).default_get(cr, uid, fields, context=context) record_id = context and context.get('active_id', False) or False + uom_obj = self.pool.get('product.uom') pick_obj = self.pool.get('stock.picking') pick = pick_obj.browse(cr, uid, record_id, context=context) + quant_obj = self.pool.get("stock.quant") + chained_move_exist = False if pick: - if 'invoice_state' in fields: - if pick.invoice_state=='invoiced': - res.update({'invoice_state': '2binvoiced'}) - else: - res.update({'invoice_state': 'none'}) - return_history = self.get_return_history(cr, uid, record_id, context) - for line in pick.move_lines: - qty = line.product_qty - return_history.get(line.id, 0) - if qty > 0: - result1.append({'product_id': line.product_id.id, 'quantity': qty,'move_id':line.id, 'prodlot_id': line.prodlot_id and line.prodlot_id.id or False}) + if pick.state != 'done': + raise osv.except_osv(_('Warning!'), _("You may only return pickings that are Done!")) + + for move in pick.move_lines: + if move.move_dest_id: + chained_move_exist = True + #Sum the quants in that location that can be returned (they should have been moved by the moves that were included in the returned picking) + qty = 0 + quant_search = quant_obj.search(cr, uid, [('history_ids', 'in', move.id), ('qty', '>', 0.0), ('location_id', 'child_of', move.location_dest_id.id)], context=context) + for quant in quant_obj.browse(cr, uid, quant_search, context=context): + if not quant.reservation_id or quant.reservation_id.origin_returned_move_id.id != move.id: + qty += quant.qty + qty = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id) + result1.append({'product_id': move.product_id.id, 'quantity': qty, 'move_id': move.id}) + + if len(result1) == 0: + raise osv.except_osv(_('Warning!'), _("No products to return (only lines in Done state and not fully returned yet can be returned)!")) if 'product_return_moves' in fields: res.update({'product_return_moves': result1}) + if 'move_dest_exists' in fields: + res.update({'move_dest_exists': chained_move_exist}) return res - def view_init(self, cr, uid, fields_list, context=None): - """ - Creates view dynamically and adding fields at runtime. - @param self: The object pointer. - @param cr: A database cursor - @param uid: ID of the user currently logged in - @param context: A standard dictionary - @return: New arch of view with new columns. - """ + def _create_returns(self, cr, uid, ids, context=None): if context is None: context = {} - res = super(stock_return_picking, self).view_init(cr, uid, fields_list, context=context) - record_id = context and context.get('active_id', False) - if record_id: - pick_obj = self.pool.get('stock.picking') - pick = pick_obj.browse(cr, uid, record_id, context=context) - if pick.state not in ['done','confirmed','assigned']: - raise osv.except_osv(_('Warning!'), _("You may only return pickings that are Confirmed, Available or Done!")) - valid_lines = 0 - return_history = self.get_return_history(cr, uid, record_id, context) - for m in pick.move_lines: - if m.state == 'done' and m.product_qty * m.product_uom.factor > return_history.get(m.id, 0): - valid_lines += 1 - if not valid_lines: - raise osv.except_osv(_('Warning!'), _("No products to return (only lines in Done state and not fully returned yet can be returned)!")) - return res - - def get_return_history(self, cr, uid, pick_id, context=None): - """ - Get return_history. - @param self: The object pointer. - @param cr: A database cursor - @param uid: ID of the user currently logged in - @param pick_id: Picking id - @param context: A standard dictionary - @return: A dictionary which of values. - """ + record_id = context and context.get('active_id', False) or False + move_obj = self.pool.get('stock.move') pick_obj = self.pool.get('stock.picking') - pick = pick_obj.browse(cr, uid, pick_id, context=context) - return_history = {} - for m in pick.move_lines: - if m.state == 'done': - return_history[m.id] = 0 - for rec in m.move_history_ids2: - # only take into account 'product return' moves, ignoring any other - # kind of upstream moves, such as internal procurements, etc. - # a valid return move will be the exact opposite of ours: - # (src location, dest location) <=> (dest location, src location)) - if rec.location_dest_id.id == m.location_id.id \ - and rec.location_id.id == m.location_dest_id.id: - return_history[m.id] += (rec.product_qty * rec.product_uom.factor) - return return_history + uom_obj = self.pool.get('product.uom') + data_obj = self.pool.get('stock.return.picking.line') + pick = pick_obj.browse(cr, uid, record_id, context=context) + data = self.read(cr, uid, ids[0], context=context) + returned_lines = 0 + + # Cancel assignment of existing chained assigned moves + moves_to_unreserve = [] + for move in pick.move_lines: + to_check_moves = [move.move_dest_id] + while to_check_moves: + current_move = to_check_moves.pop() + if current_move.state not in ('done', 'cancel') and current_move.reserved_quant_ids: + moves_to_unreserve.append(current_move.id) + split_move_ids = move_obj.search(cr, uid, [('split_from', '=', current_move.id)], context=context) + if split_move_ids: + to_check_moves += move_obj.browse(cr, uid, split_move_ids, context=context) + + if moves_to_unreserve: + move_obj.do_unreserve(cr, uid, moves_to_unreserve, context=context) + #break the link between moves in order to be able to fix them later if needed + move_obj.write(cr, uid, moves_to_unreserve, {'move_orig_ids': False}, context=context) + + #Create new picking for returned products + pick_type_id = pick.picking_type_id.return_picking_type_id and pick.picking_type_id.return_picking_type_id.id or pick.picking_type_id.id + new_picking = pick_obj.copy(cr, uid, pick.id, { + 'move_lines': [], + 'picking_type_id': pick_type_id, + 'state': 'draft', + 'origin': pick.name, + }, context=context) + + for data_get in data_obj.browse(cr, uid, data['product_return_moves'], context=context): + move = data_get.move_id + if not move: + raise osv.except_osv(_('Warning !'), _("You have manually created product lines, please delete them to proceed")) + new_qty = data_get.quantity + if new_qty: + returned_lines += 1 + move_obj.copy(cr, uid, move.id, { + 'product_id': data_get.product_id.id, + 'product_uom_qty': new_qty, + 'product_uos_qty': uom_obj._compute_qty(cr, uid, move.product_uom.id, new_qty, move.product_uos.id), + 'picking_id': new_picking, + 'state': 'draft', + 'location_id': move.location_dest_id.id, + 'location_dest_id': move.location_id.id, + 'origin_returned_move_id': move.id, + 'procure_method': 'make_to_stock', + 'restrict_lot_id': data_get.lot_id.id, + }) + + if not returned_lines: + raise osv.except_osv(_('Warning!'), _("Please specify at least one non-zero quantity.")) + + pick_obj.action_confirm(cr, uid, [new_picking], context=context) + pick_obj.action_assign(cr, uid, [new_picking], context) + return new_picking, pick_type_id def create_returns(self, cr, uid, ids, context=None): - """ + """ Creates return picking. @param self: The object pointer. @param cr: A database cursor @@ -143,89 +163,25 @@ class stock_return_picking(osv.osv_memory): @param context: A standard dictionary @return: A dictionary which of fields with values. """ - if context is None: - context = {} - record_id = context and context.get('active_id', False) or False - move_obj = self.pool.get('stock.move') - pick_obj = self.pool.get('stock.picking') - uom_obj = self.pool.get('product.uom') - data_obj = self.pool.get('stock.return.picking.memory') - act_obj = self.pool.get('ir.actions.act_window') - model_obj = self.pool.get('ir.model.data') - pick = pick_obj.browse(cr, uid, record_id, context=context) - data = self.read(cr, uid, ids[0], context=context) - date_cur = time.strftime('%Y-%m-%d %H:%M:%S') - set_invoice_state_to_none = True - returned_lines = 0 - -# Create new picking for returned products - - seq_obj_name = 'stock.picking' - new_type = 'internal' - if pick.type =='out': - new_type = 'in' - seq_obj_name = 'stock.picking.in' - elif pick.type =='in': - new_type = 'out' - seq_obj_name = 'stock.picking.out' - new_pick_name = self.pool.get('ir.sequence').get(cr, uid, seq_obj_name) - new_picking = pick_obj.copy(cr, uid, pick.id, { - 'name': _('%s-%s-return') % (new_pick_name, pick.name), - 'move_lines': [], - 'state':'draft', - 'type': new_type, - 'date':date_cur, - 'invoice_state': data['invoice_state'], - }) - - val_id = data['product_return_moves'] - for v in val_id: - data_get = data_obj.browse(cr, uid, v, context=context) - mov_id = data_get.move_id.id - if not mov_id: - raise osv.except_osv(_('Warning !'), _("You have manually created product lines, please delete them to proceed")) - new_qty = data_get.quantity - move = move_obj.browse(cr, uid, mov_id, context=context) - new_location = move.location_dest_id.id - returned_qty = move.product_qty - for rec in move.move_history_ids2: - returned_qty -= rec.product_qty - - if returned_qty != new_qty: - set_invoice_state_to_none = False - if new_qty: - returned_lines += 1 - new_move=move_obj.copy(cr, uid, move.id, { - 'product_qty': new_qty, - 'product_uos_qty': uom_obj._compute_qty(cr, uid, move.product_uom.id, new_qty, move.product_uos.id), - 'picking_id': new_picking, - 'state': 'draft', - 'location_id': new_location, - 'location_dest_id': move.location_id.id, - 'date': date_cur, - }) - move_obj.write(cr, uid, [move.id], {'move_history_ids2':[(4,new_move)]}, context=context) - if not returned_lines: - raise osv.except_osv(_('Warning!'), _("Please specify at least one non-zero quantity.")) - - if set_invoice_state_to_none: - pick_obj.write(cr, uid, [pick.id], {'invoice_state':'none'}, context=context) - pick_obj.signal_button_confirm(cr, uid, [new_picking]) - pick_obj.force_assign(cr, uid, [new_picking], context) - # Update view id in context, lp:702939 - model_list = { - 'out': 'stock.picking.out', - 'in': 'stock.picking.in', - 'internal': 'stock.picking', + new_picking_id, pick_type_id = self._create_returns(cr, uid, ids, context=context) + # Override the context to disable all the potential filters that could have been set previously + ctx = { + 'search_default_picking_type_id': pick_type_id, + 'search_default_draft': False, + 'search_default_assigned': False, + 'search_default_confirmed': False, + 'search_default_ready': False, + 'search_default_late': False, + 'search_default_available': False, } return { - 'domain': "[('id', 'in', ["+str(new_picking)+"])]", + 'domain': "[('id', 'in', [" + str(new_picking_id) + "])]", 'name': _('Returned Picking'), - 'view_type':'form', - 'view_mode':'tree,form', - 'res_model': model_list.get(new_type, 'stock.picking'), - 'type':'ir.actions.act_window', - 'context':context, + 'view_type': 'form', + 'view_mode': 'tree,form', + 'res_model': 'stock.picking', + 'type': 'ir.actions.act_window', + 'context': ctx, } diff --git a/addons/stock/wizard/stock_return_picking_view.xml b/addons/stock/wizard/stock_return_picking_view.xml index 2f1983fa46c..3baed374568 100644 --- a/addons/stock/wizard/stock_return_picking_view.xml +++ b/addons/stock/wizard/stock_return_picking_view.xml @@ -9,43 +9,27 @@ key2="client_action_multi" multi="True" id="act_stock_return_picking"/> - - - - stock.return.picking.memory.tree - stock.return.picking.memory + + stock.return.picking.line.tree + stock.return.picking.line - + - - stock.return.picking.memory.from - stock.return.picking.memory + + stock.return.picking.line.from + stock.return.picking.line
- +
@@ -57,10 +41,18 @@ stock.return.picking
-
- - Split into - ir.actions.act_window - stock.split.into - form - form - new - - - diff --git a/addons/stock/wizard/stock_traceability.py b/addons/stock/wizard/stock_traceability.py deleted file mode 100644 index c13fc1cf7a6..00000000000 --- a/addons/stock/wizard/stock_traceability.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2010 Tiny SPRL (). -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . -# -############################################################################## - -from openerp.osv import fields, osv -from openerp.tools.translate import _ - -class action_traceability(osv.osv_memory): - """ - This class defines a function action_traceability for wizard - - """ - _name = "action.traceability" - _description = "Action traceability " - - def action_traceability(self, cr, uid, ids, context=None): - """ It traces the information of a product - @param self: The object pointer. - @param cr: A database cursor - @param uid: ID of the user currently logged in - @param ids: List of IDs selected - @param context: A standard dictionary - @return: A dictionary of values - """ - lot_id = ids - if context is None: - context = {} - type1 = context.get('type', 'move_history_ids2') - field = context.get('field', 'tracking_id') - obj = self.pool.get('stock.move') - ids = obj.search(cr, uid, [(field, 'in',lot_id)]) - cr.execute('select id from ir_ui_view where model=%s and field_parent=%s and type=%s', ('stock.move', type1, 'tree')) - view_ids = cr.fetchone() - view_id = view_ids and view_ids[0] or False - value = { - 'domain': "[('id','in',["+','.join(map(str, ids))+"])]", - 'name': ((type1=='move_history_ids2') and _('Upstream Traceability')) or _('Downstream Traceability'), - 'view_mode': 'tree', - 'view_type': 'tree', - 'res_model': 'stock.move', - 'field_parent': type1, - 'view_id': (view_id,'View'), - 'type': 'ir.actions.act_window', - 'nodestroy':True, - } - return value - - -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: - diff --git a/addons/stock_account/__init__.py b/addons/stock_account/__init__.py new file mode 100644 index 00000000000..bc6c5f0e3a8 --- /dev/null +++ b/addons/stock_account/__init__.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import product +import stock_account +import stock +import wizard +import res_config diff --git a/addons/stock_account/__openerp__.py b/addons/stock_account/__openerp__.py new file mode 100644 index 00000000000..a2dab1289f4 --- /dev/null +++ b/addons/stock_account/__openerp__.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +{ + 'name': 'WMS Accounting', + 'version': '1.1', + 'author': 'OpenERP SA', + 'summary': 'Inventory, Logistic, Valuation, Accounting', + 'description': """ +WMS Accounting module +====================== +This module makes the link between the 'stock' and 'account' modules and allows you to create accounting entries to value your stock movements + +Key Features +------------ +* Stock Valuation (periodical or automatic) +* Invoice from Picking + +Dashboard / Reports for Warehouse Management includes: +------------------------------------------------------ +* Stock Inventory Value at given date (support dates in the past) + """, + 'website': 'http://www.openerp.com', + 'images': [], + 'depends': ['stock', 'account'], + 'category': 'Hidden', + 'sequence': 16, + 'demo': [ + 'stock_account_demo.xml' + ], + 'data': [ + 'security/stock_account_security.xml', + 'security/ir.model.access.csv', + 'stock_account_data.xml', + 'wizard/stock_change_standard_price_view.xml', + 'wizard/stock_invoice_onshipping_view.xml', + 'wizard/stock_valuation_history_view.xml', + 'product_data.xml', + 'product_view.xml', + 'stock_account_view.xml', + 'res_config_view.xml', + ], + 'test': [ + + ], + 'installable': True, + 'application': True, + 'auto_install': True, +} diff --git a/addons/stock_account/product.py b/addons/stock_account/product.py new file mode 100644 index 00000000000..b043fc4094b --- /dev/null +++ b/addons/stock_account/product.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +from openerp.osv import fields, osv +from openerp.tools.translate import _ + +class product_product(osv.osv): + _inherit = "product.product" + + def get_product_accounts(self, cr, uid, product_id, context=None): + """ To get the stock input account, stock output account and stock journal related to product. + @param product_id: product id + @return: dictionary which contains information regarding stock input account, stock output account and stock journal + """ + if context is None: + context = {} + product_obj = self.pool.get('product.product').browse(cr, uid, product_id, context=context) + + stock_input_acc = product_obj.property_stock_account_input and product_obj.property_stock_account_input.id or False + if not stock_input_acc: + stock_input_acc = product_obj.categ_id.property_stock_account_input_categ and product_obj.categ_id.property_stock_account_input_categ.id or False + + stock_output_acc = product_obj.property_stock_account_output and product_obj.property_stock_account_output.id or False + if not stock_output_acc: + stock_output_acc = product_obj.categ_id.property_stock_account_output_categ and product_obj.categ_id.property_stock_account_output_categ.id or False + + journal_id = product_obj.categ_id.property_stock_journal and product_obj.categ_id.property_stock_journal.id or False + account_valuation = product_obj.categ_id.property_stock_valuation_account_id and product_obj.categ_id.property_stock_valuation_account_id.id or False + + if not all([stock_input_acc, stock_output_acc, account_valuation, journal_id]): + raise osv.except_osv(_('Error!'), _('''One of the following information is missing on the product or product category and prevents the accounting valuation entries to be created: + Product: %s + Stock Input Account: %s + Stock Output Account: %s + Stock Valuation Account: %s + Stock Journal: %s + ''') % (product_obj.name, stock_input_acc, stock_output_acc, account_valuation, journal_id)) + return { + 'stock_account_input': stock_input_acc, + 'stock_account_output': stock_output_acc, + 'stock_journal': journal_id, + 'property_stock_valuation_account_id': account_valuation + } + + def do_change_standard_price(self, cr, uid, ids, new_price, context=None): + """ Changes the Standard Price of Product and creates an account move accordingly.""" + location_obj = self.pool.get('stock.location') + move_obj = self.pool.get('account.move') + move_line_obj = self.pool.get('account.move.line') + if context is None: + context = {} + user_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id + loc_ids = location_obj.search(cr, uid, [('usage', '=', 'internal'), ('company_id', '=', user_company_id)]) + for rec_id in ids: + datas = self.get_product_accounts(cr, uid, rec_id, context=context) + for location in location_obj.browse(cr, uid, loc_ids, context=context): + c = context.copy() + c.update({'location': location.id, 'compute_child': False}) + product = self.browse(cr, uid, rec_id, context=c) + + diff = product.standard_price - new_price + if not diff: + raise osv.except_osv(_('Error!'), _("No difference between standard price and new price!")) + qty = product.qty_available + if qty: + # Accounting Entries + move_vals = { + 'journal_id': datas['stock_journal'], + 'company_id': location.company_id.id, + } + move_id = move_obj.create(cr, uid, move_vals, context=context) + + if diff > 0: + amount_diff = qty * diff + debit_account_id = datas['stock_account_input'] + credit_account_id = datas['property_stock_valuation_account_id'] + else: + amount_diff = qty * -diff + debit_account_id = datas['property_stock_valuation_account_id'] + credit_account_id = datas['stock_account_output'] + + move_line_obj.create(cr, uid, { + 'name': _('Standard Price changed'), + 'account_id': debit_account_id, + 'debit': amount_diff, + 'credit': 0, + 'move_id': move_id, + }, context=context) + move_line_obj.create(cr, uid, { + 'name': _('Standard Price changed'), + 'account_id': credit_account_id, + 'debit': 0, + 'credit': amount_diff, + 'move_id': move_id + }, context=context) + self.write(cr, uid, rec_id, {'standard_price': new_price}) + return True + + _columns = { + 'valuation': fields.property(type='selection', selection=[('manual_periodic', 'Periodical (manual)'), + ('real_time', 'Real Time (automated)')], string='Inventory Valuation', + help="If real-time valuation is enabled for a product, the system will automatically write journal entries corresponding to stock moves, with product price as specified by the 'Costing Method'" \ + "The inventory variation account set on the product category will represent the current inventory value, and the stock input and stock output account will hold the counterpart moves for incoming and outgoing products." + , required=True), + } + + +class product_template(osv.osv): + _name = 'product.template' + _inherit = 'product.template' + _columns = { + 'cost_method': fields.property(type='selection', selection=[('standard', 'Standard Price'), ('average', 'Average Price'), ('real', 'Real Price')], + help="""Standard Price: The cost price is manually updated at the end of a specific period (usually every year). + Average Price: The cost price is recomputed at each incoming shipment and used for the product valuation. + Real Price: The cost price displayed is the price of the last outgoing product (will be use in case of inventory loss for example).""", + string="Costing Method", required=True), + 'property_stock_account_input': fields.property( + type='many2one', + relation='account.account', + string='Stock Input Account', + help="When doing real-time inventory valuation, counterpart journal items for all incoming stock moves will be posted in this account, unless " + "there is a specific valuation account set on the source location. When not set on the product, the one from the product category is used."), + 'property_stock_account_output': fields.property( + type='many2one', + relation='account.account', + string='Stock Output Account', + help="When doing real-time inventory valuation, counterpart journal items for all outgoing stock moves will be posted in this account, unless " + "there is a specific valuation account set on the destination location. When not set on the product, the one from the product category is used."), + } + + +class product_category(osv.osv): + _inherit = 'product.category' + _columns = { + 'property_stock_journal': fields.property( + relation='account.journal', + type='many2one', + string='Stock Journal', + help="When doing real-time inventory valuation, this is the Accounting Journal in which entries will be automatically posted when stock moves are processed."), + 'property_stock_account_input_categ': fields.property( + type='many2one', + relation='account.account', + string='Stock Input Account', + help="When doing real-time inventory valuation, counterpart journal items for all incoming stock moves will be posted in this account, unless " + "there is a specific valuation account set on the source location. This is the default value for all products in this category. It " + "can also directly be set on each product"), + 'property_stock_account_output_categ': fields.property( + type='many2one', + relation='account.account', + string='Stock Output Account', + help="When doing real-time inventory valuation, counterpart journal items for all outgoing stock moves will be posted in this account, unless " + "there is a specific valuation account set on the destination location. This is the default value for all products in this category. It " + "can also directly be set on each product"), + 'property_stock_valuation_account_id': fields.property( + type='many2one', + relation='account.account', + string="Stock Valuation Account", + help="When real-time inventory valuation is enabled on a product, this account will hold the current value of the products.",), + } + diff --git a/addons/stock/product_data.xml b/addons/stock_account/product_data.xml similarity index 94% rename from addons/stock/product_data.xml rename to addons/stock_account/product_data.xml index ae5a3478500..49a065488a1 100644 --- a/addons/stock/product_data.xml +++ b/addons/stock_account/product_data.xml @@ -5,7 +5,7 @@ property_stock_journal - + diff --git a/addons/stock_account/product_view.xml b/addons/stock_account/product_view.xml new file mode 100644 index 00000000000..e1e414698a5 --- /dev/null +++ b/addons/stock_account/product_view.xml @@ -0,0 +1,93 @@ + + + + + + product.category.stock.property.form.inherit + product.category + + + + + + + + + + + + + + + + + product.template.stock.property.form.inherit + product.template + + + + + + + + + + + + + + + + + + + + + + + + + + + product.product.standard.price.form.inherit + product.product + + + + + + + + + + product.normal.stock.acc.property.form.inherit + product.product + + 26 + + + + + + + + + + + + + + + + + + diff --git a/addons/stock_account/res_config.py b/addons/stock_account/res_config.py new file mode 100644 index 00000000000..a6076bebf94 --- /dev/null +++ b/addons/stock_account/res_config.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Business Applications +# Copyright (C) 2004-2012 OpenERP S.A. (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +from openerp.osv import fields, osv + + + +class stock_config_settings(osv.osv_memory): + _inherit = 'stock.config.settings' + + _columns = { + 'group_stock_inventory_valuation': fields.boolean("Generate accounting entries per stock movement", + implied_group='stock_account.group_inventory_valuation', + help="""Allows to configure inventory valuations on products and product categories."""), + 'module_stock_invoice_directly': fields.boolean("Create and open the invoice when the user finish a delivery order", + help='This allows to automatically launch the invoicing wizard if the delivery is ' + 'to be invoiced when you send or deliver goods.\n' + '-This installs the module stock_invoice_directly.'), + 'module_stock_landed_costs': fields.boolean("Calculate landed costs on products", + help="""Install the module that allows to affect landed costs on pickings, and split them onto the different products."""), + } + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/stock_account/res_config_view.xml b/addons/stock_account/res_config_view.xml new file mode 100644 index 00000000000..4a48349f8df --- /dev/null +++ b/addons/stock_account/res_config_view.xml @@ -0,0 +1,31 @@ + + + + stock.config.settings.inherit + stock.config.settings + + + + + + + + + + + diff --git a/addons/stock_account/security/ir.model.access.csv b/addons/stock_account/security/ir.model.access.csv new file mode 100644 index 00000000000..b1a572003a6 --- /dev/null +++ b/addons/stock_account/security/ir.model.access.csv @@ -0,0 +1,8 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_account_invoice_user,account.invoice stock user,account.model_account_invoice,stock.group_stock_user,1,1,1,0 +access_account_invoice_line_user,account.invoice.line stock user,account.model_account_invoice_line,stock.group_stock_user,1,1,1,0 +access_account_invoice_tax_user,account.invoice.tax stock user,account.model_account_invoice_tax,stock.group_stock_user,1,1,1,0 +access_account_journal_user,account.journal stock user,account.model_account_journal,stock.group_stock_user,1,0,0,0 +access_account_fiscalyear,account.fiscalyear stock user,account.model_account_fiscalyear,stock.group_stock_user,1,0,0,0 +access_account_account_stock_manager,account.account stock manager,account.model_account_account,stock.group_stock_manager,1,0,0,0 +access_stock_history_stock_manager,stock.history stock manager,model_stock_history,stock.group_stock_manager,1,0,0,0 diff --git a/addons/stock_account/security/stock_account_security.xml b/addons/stock_account/security/stock_account_security.xml new file mode 100644 index 00000000000..97ecaecd278 --- /dev/null +++ b/addons/stock_account/security/stock_account_security.xml @@ -0,0 +1,13 @@ + + + + + + + + Manage Inventory Valuation and Costing Methods + + + + + diff --git a/addons/stock_account/stock.py b/addons/stock_account/stock.py new file mode 100644 index 00000000000..db08ba39eb4 --- /dev/null +++ b/addons/stock_account/stock.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +from openerp.osv import fields, osv + +class stock_location_path(osv.osv): + _inherit = "stock.location.path" + _columns = { + 'invoice_state': fields.selection([ + ("invoiced", "Invoiced"), + ("2binvoiced", "To Be Invoiced"), + ("none", "Not Applicable")], "Invoice Status", + required=True,), + } + _defaults = { + 'invoice_state': 'none', + } + +#---------------------------------------------------------- +# Procurement Rule +#---------------------------------------------------------- +class procurement_rule(osv.osv): + _inherit = 'procurement.rule' + _columns = { + 'invoice_state': fields.selection([ + ("invoiced", "Invoiced"), + ("2binvoiced", "To Be Invoiced"), + ("none", "Not Applicable")], "Invoice Status", + required=True), + } + _defaults = { + 'invoice_state': 'none', + } + +#---------------------------------------------------------- +# Procurement Order +#---------------------------------------------------------- + + +class procurement_order(osv.osv): + _inherit = "procurement.order" + _columns = { + 'invoice_state': fields.selection([("invoiced", "Invoiced"), + ("2binvoiced", "To Be Invoiced"), + ("none", "Not Applicable") + ], "Invoice Control", required=True), + } + + def _run_move_create(self, cr, uid, procurement, context=None): + res = super(procurement_order, self)._run_move_create(cr, uid, procurement, context=context) + res.update({'invoice_state': (procurement.rule_id.invoice_state in ('none', False) and procurement.invoice_state or procurement.rule_id.invoice_state) or 'none'}) + return res + + _defaults = { + 'invoice_state': 'none' + } + + +#---------------------------------------------------------- +# Move +#---------------------------------------------------------- + +class stock_move(osv.osv): + _inherit = "stock.move" + _columns = { + 'invoice_state': fields.selection([("invoiced", "Invoiced"), + ("2binvoiced", "To Be Invoiced"), + ("none", "Not Applicable")], "Invoice Control", + select=True, required=True, track_visibility='onchange', + states={'draft': [('readonly', False)]}), + } + _defaults = { + 'invoice_state': lambda *args, **argv: 'none' + } + + def _get_master_data(self, cr, uid, move, company, context=None): + ''' returns a tupple (browse_record(res.partner), ID(res.users), ID(res.currency)''' + return move.picking_id.partner_id, uid, company.currency_id.id + + def _create_invoice_line_from_vals(self, cr, uid, move, invoice_line_vals, context=None): + return self.pool.get('account.invoice.line').create(cr, uid, invoice_line_vals, context=context) + + def _get_price_unit_invoice(self, cr, uid, move_line, type, context=None): + """ Gets price unit for invoice + @param move_line: Stock move lines + @param type: Type of invoice + @return: The price unit for the move line + """ + if context is None: + context = {} + if type in ('in_invoice', 'in_refund'): + # Take the user company and pricetype + context['currency_id'] = move_line.company_id.currency_id.id + amount_unit = move_line.product_id.price_get('standard_price', context=context)[move_line.product_id.id] + return amount_unit + return move_line.product_id.list_price + + def _get_invoice_line_vals(self, cr, uid, move, partner, inv_type, context=None): + fp_obj = self.pool.get('account.fiscal.position') + # Get account_id + if inv_type in ('out_invoice', 'out_refund'): + account_id = move.product_id.property_account_income.id + if not account_id: + account_id = move.product_id.categ_id.property_account_income_categ.id + else: + account_id = move.product_id.property_account_expense.id + if not account_id: + account_id = move.product_id.categ_id.property_account_expense_categ.id + fiscal_position = partner.property_account_position + account_id = fp_obj.map_account(cr, uid, fiscal_position, account_id) + + # set UoS if it's a sale and the picking doesn't have one + uos_id = move.product_uom.id + quantity = move.product_uom_qty + if move.product_uos: + uos_id = move.product_uos.id + quantity = move.product_uos_qty + return { + 'name': move.name, + 'account_id': account_id, + 'product_id': move.product_id.id, + 'uos_id': uos_id, + 'quantity': quantity, + 'price_unit': self._get_price_unit_invoice(cr, uid, move, inv_type), + 'discount': 0.0, + 'account_analytic_id': False, + } + +#---------------------------------------------------------- +# Picking +#---------------------------------------------------------- + +class stock_picking(osv.osv): + _inherit = 'stock.picking' + def __get_invoice_state(self, cr, uid, ids, name, arg, context=None): + result = {} + for pick in self.browse(cr, uid, ids, context=context): + result[pick.id] = 'none' + for move in pick.move_lines: + if move.invoice_state == 'invoiced': + result[pick.id] = 'invoiced' + elif move.invoice_state == '2binvoiced': + result[pick.id] = '2binvoiced' + break + return result + + def __get_picking_move(self, cr, uid, ids, context={}): + res = [] + for move in self.pool.get('stock.move').browse(cr, uid, ids, context=context): + if move.picking_id: + res.append(move.picking_id.id) + return res + + _columns = { + 'invoice_state': fields.function(__get_invoice_state, type='selection', selection=[ + ("invoiced", "Invoiced"), + ("2binvoiced", "To Be Invoiced"), + ("none", "Not Applicable") + ], string="Invoice Control", required=True, + + store={ + 'stock.picking': (lambda self, cr, uid, ids, c={}: ids, ['state'], 10), + 'stock.move': (__get_picking_move, ['picking_id', 'invoice_state'], 10), + }, + ), + } + _defaults = { + 'invoice_state': lambda *args, **argv: 'none' + } + + def _create_invoice_from_picking(self, cr, uid, picking, vals, context=None): + ''' This function simply creates the invoice from the given values. It is overriden in delivery module to add the delivery costs. + ''' + invoice_obj = self.pool.get('account.invoice') + return invoice_obj.create(cr, uid, vals, context=context) + + def action_invoice_create(self, cr, uid, ids, journal_id, group=False, type='out_invoice', context=None): + """ Creates invoice based on the invoice state selected for picking. + @param journal_id: Id of journal + @param group: Whether to create a group invoice or not + @param type: Type invoice to be created + @return: Ids of created invoices for the pickings + """ + context = context or {} + todo = {} + for picking in self.browse(cr, uid, ids, context=context): + key = group and picking.id or True + for move in picking.move_lines: + if move.procurement_id and (move.procurement_id.invoice_state == '2binvoiced') or move.invoice_state == '2binvoiced': + if (move.state != 'cancel') and not move.scrapped: + todo.setdefault(key, []) + todo[key].append(move) + invoices = [] + for moves in todo.values(): + invoices = self._invoice_create_line(cr, uid, moves, journal_id, type, context=context) + return invoices + + def _get_invoice_vals(self, cr, uid, key, inv_type, journal_id, origin, context=None): + if context is None: + context = {} + partner, currency_id, company_id, user_id = key + if inv_type in ('out_invoice', 'out_refund'): + account_id = partner.property_account_receivable.id + payment_term = partner.property_payment_term.id or False + else: + account_id = partner.property_account_payable.id + payment_term = partner.property_supplier_payment_term.id or False + return { + 'origin': origin, + 'date_invoice': context.get('date_inv', False), + 'user_id': user_id, + 'partner_id': partner.id, + 'account_id': account_id, + 'payment_term': payment_term, + 'type': inv_type, + 'fiscal_position': partner.property_account_position.id, + 'company_id': company_id, + 'currency_id': currency_id, + 'journal_id': journal_id, + } + + def _invoice_create_line(self, cr, uid, moves, journal_id, inv_type='out_invoice', context=None): + invoice_obj = self.pool.get('account.invoice') + move_obj = self.pool.get('stock.move') + invoices = {} + for move in moves: + company = move.company_id + origin = move.picking_id.name + partner, user_id, currency_id = move_obj._get_master_data(cr, uid, move, company, context=context) + + key = (partner, currency_id, company.id, user_id) + + if key not in invoices: + # Get account and payment terms + invoice_vals = self._get_invoice_vals(cr, uid, key, inv_type, journal_id, origin, context=context) + invoice_id = self._create_invoice_from_picking(cr, uid, move.picking_id, invoice_vals, context=context) + invoices[key] = invoice_id + + invoice_line_vals = move_obj._get_invoice_line_vals(cr, uid, move, partner, inv_type, context=context) + invoice_line_vals['invoice_id'] = invoices[key] + invoice_line_vals['origin'] = origin + + move_obj._create_invoice_line_from_vals(cr, uid, move, invoice_line_vals, context=context) + + move_obj.write(cr, uid, move.id, {'invoice_state': 'invoiced'}, context=context) + if move.procurement_id: + self.pool.get('procurement.order').write(cr, uid, [move.procurement_id.id], { + 'invoice_state': 'invoiced', + }, context=context) + + invoice_obj.button_compute(cr, uid, invoices.values(), context=context, set_total=(inv_type in ('in_invoice', 'in_refund'))) + return invoices.values() diff --git a/addons/stock_account/stock_account.py b/addons/stock_account/stock_account.py new file mode 100644 index 00000000000..6c6a20e0e59 --- /dev/null +++ b/addons/stock_account/stock_account.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +from openerp.osv import fields, osv +from openerp.tools.translate import _ +from openerp import SUPERUSER_ID +import logging +_logger = logging.getLogger(__name__) + + +class stock_inventory(osv.osv): + _inherit = "stock.inventory" + _columns = { + 'period_id': fields.many2one('account.period', 'Force Valuation Period', help="Choose the accounting period where you want to value the stock moves created by the inventory instead of the default one (chosen by the inventory end date)"), + } + + def post_inventory(self, cr, uid, inv, context=None): + if context is None: + context = {} + ctx = context.copy() + if inv.period_id: + ctx['force_period'] = inv.period_id.id + return super(stock_inventory, self).post_inventory(cr, uid, inv, context=ctx) + + +#---------------------------------------------------------- +# Stock Location +#---------------------------------------------------------- + +class stock_location(osv.osv): + _inherit = "stock.location" + + _columns = { + 'valuation_in_account_id': fields.many2one('account.account', 'Stock Valuation Account (Incoming)', domain=[('type', '=', 'other')], + help="Used for real-time inventory valuation. When set on a virtual location (non internal type), " + "this account will be used to hold the value of products being moved from an internal location " + "into this location, instead of the generic Stock Output Account set on the product. " + "This has no effect for internal locations."), + 'valuation_out_account_id': fields.many2one('account.account', 'Stock Valuation Account (Outgoing)', domain=[('type', '=', 'other')], + help="Used for real-time inventory valuation. When set on a virtual location (non internal type), " + "this account will be used to hold the value of products being moved out of this location " + "and into an internal location, instead of the generic Stock Output Account set on the product. " + "This has no effect for internal locations."), + } + +#---------------------------------------------------------- +# Quants +#---------------------------------------------------------- + +class stock_quant(osv.osv): + _inherit = "stock.quant" + + def _get_inventory_value(self, cr, uid, quant, context=None): + if quant.product_id.cost_method in ('real'): + return quant.cost * quant.qty + return super(stock_quant, self)._get_inventory_value(cr, uid, quant, context=context) + + def _price_update(self, cr, uid, quant_ids, newprice, context=None): + ''' This function is called at the end of negative quant reconciliation and does the accounting entries adjustemnts and the update of the product cost price if needed + ''' + if context is None: + context = {} + super(stock_quant, self)._price_update(cr, uid, quant_ids, newprice, context=context) + ctx = context.copy() + for quant in self.browse(cr, uid, quant_ids, context=context): + move = self._get_latest_move(cr, uid, quant, context=context) + # this is where we post accounting entries for adjustment + ctx['force_valuation_amount'] = newprice - quant.cost + self._account_entry_move(cr, uid, [quant], move, context=ctx) + #update the standard price of the product, only if we would have done it if we'd have had enough stock at first, which means + #1) the product cost's method is 'real' + #2) we just fixed a negative quant caused by an outgoing shipment + if quant.product_id.cost_method == 'real' and quant.location_id.usage != 'internal': + self.pool.get('stock.move')._store_average_cost_price(cr, uid, move, context=context) + + def _account_entry_move(self, cr, uid, quants, move, context=None): + """ + Accounting Valuation Entries + + quants: browse record list of Quants to create accounting valuation entries for. Unempty and all quants are supposed to have the same location id (thay already moved in) + move: Move to use. browse record + """ + if context is None: + context = {} + location_obj = self.pool.get('stock.location') + location_from = move.location_id + location_to = quants[0].location_id + company_from = location_obj._location_owner(cr, uid, location_from, context=context) + company_to = location_obj._location_owner(cr, uid, location_to, context=context) + + if move.product_id.valuation != 'real_time': + return False + for q in quants: + if q.owner_id: + #if the quant isn't owned by the company, we don't make any valuation entry + return False + if q.qty <= 0: + #we don't make any stock valuation for negative quants because the valuation is already made for the counterpart. + #At that time the valuation will be made at the product cost price and afterward there will be new accounting entries + #to make the adjustments when we know the real cost price. + return False + + #in case of routes making the link between several warehouse of the same company, the transit location belongs to this company, so we don't need to create accounting entries + # Create Journal Entry for products arriving in the company + if company_to and (move.location_id.usage not in ('internal', 'transit') and move.location_dest_id.usage == 'internal' or company_from != company_to): + ctx = context.copy() + ctx['force_company'] = company_to.id + journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation(cr, uid, move, context=ctx) + if location_from and location_from.usage == 'customer': + #goods returned from customer + self._create_account_move_line(cr, uid, quants, move, acc_dest, acc_valuation, journal_id, context=ctx) + else: + self._create_account_move_line(cr, uid, quants, move, acc_src, acc_valuation, journal_id, context=ctx) + + # Create Journal Entry for products leaving the company + if company_from and (move.location_id.usage == 'internal' and move.location_dest_id.usage not in ('internal', 'transit') or company_from != company_to): + ctx = context.copy() + ctx['force_company'] = company_from.id + journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation(cr, uid, move, context=ctx) + if location_to and location_to.usage == 'supplier': + #goods returned to supplier + self._create_account_move_line(cr, uid, quants, move, acc_valuation, acc_src, journal_id, context=ctx) + else: + self._create_account_move_line(cr, uid, quants, move, acc_valuation, acc_dest, journal_id, context=ctx) + + def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, force_location_from=False, force_location_to=False, context=None): + quant = super(stock_quant, self)._quant_create(cr, uid, qty, move, lot_id=lot_id, owner_id=owner_id, src_package_id=src_package_id, dest_package_id=dest_package_id, force_location_from=force_location_from, force_location_to=force_location_to, context=context) + if move.product_id.valuation == 'real_time': + self._account_entry_move(cr, uid, [quant], move, context) + return quant + + def move_quants_write(self, cr, uid, quants, move, location_dest_id, dest_package_id, context=None): + res = super(stock_quant, self).move_quants_write(cr, uid, quants, move, location_dest_id, dest_package_id, context=context) + if move.product_id.valuation == 'real_time': + self._account_entry_move(cr, uid, quants, move, context=context) + return res + + + def _get_accounting_data_for_valuation(self, cr, uid, move, context=None): + """ + Return the accounts and journal to use to post Journal Entries for the real-time + valuation of the quant. + + :param context: context dictionary that can explicitly mention the company to consider via the 'force_company' key + :returns: journal_id, source account, destination account, valuation account + :raise: osv.except_osv() is any mandatory account or journal is not defined. + """ + product_obj = self.pool.get('product.product') + accounts = product_obj.get_product_accounts(cr, uid, move.product_id.id, context) + if move.location_id.valuation_out_account_id: + acc_src = move.location_id.valuation_out_account_id.id + else: + acc_src = accounts['stock_account_input'] + + if move.location_dest_id.valuation_in_account_id: + acc_dest = move.location_dest_id.valuation_in_account_id.id + else: + acc_dest = accounts['stock_account_output'] + + acc_valuation = accounts.get('property_stock_valuation_account_id', False) + journal_id = accounts['stock_journal'] + return journal_id, acc_src, acc_dest, acc_valuation + + def _prepare_account_move_line(self, cr, uid, move, qty, cost, credit_account_id, debit_account_id, context=None): + """ + Generate the account.move.line values to post to track the stock valuation difference due to the + processing of the given quant. + """ + if context is None: + context = {} + currency_obj = self.pool.get('res.currency') + if context.get('force_valuation_amount'): + valuation_amount = context.get('force_valuation_amount') + else: + valuation_amount = move.product_id.cost_method == 'real' and cost or move.product_id.standard_price + #the standard_price of the product may be in another decimal precision, or not compatible with the coinage of + #the company currency... so we need to use round() before creating the accounting entries. + valuation_amount = currency_obj.round(cr, uid, move.company_id.currency_id, valuation_amount * qty) + partner_id = (move.picking_id.partner_id and self.pool.get('res.partner')._find_accounting_partner(move.picking_id.partner_id).id) or False + debit_line_vals = { + 'name': move.name, + 'product_id': move.product_id.id, + 'quantity': qty, + 'product_uom_id': move.product_id.uom_id.id, + 'ref': move.picking_id and move.picking_id.name or False, + 'date': move.date, + 'partner_id': partner_id, + 'debit': valuation_amount > 0 and valuation_amount or 0, + 'credit': valuation_amount < 0 and -valuation_amount or 0, + 'account_id': debit_account_id, + } + credit_line_vals = { + 'name': move.name, + 'product_id': move.product_id.id, + 'quantity': qty, + 'product_uom_id': move.product_id.uom_id.id, + 'ref': move.picking_id and move.picking_id.name or False, + 'date': move.date, + 'partner_id': partner_id, + 'credit': valuation_amount > 0 and valuation_amount or 0, + 'debit': valuation_amount < 0 and -valuation_amount or 0, + 'account_id': credit_account_id, + } + return [(0, 0, debit_line_vals), (0, 0, credit_line_vals)] + + def _create_account_move_line(self, cr, uid, quants, move, credit_account_id, debit_account_id, journal_id, context=None): + #group quants by cost + quant_cost_qty = {} + for quant in quants: + if quant_cost_qty.get(quant.cost): + quant_cost_qty[quant.cost] += quant.qty + else: + quant_cost_qty[quant.cost] = quant.qty + move_obj = self.pool.get('account.move') + for cost, qty in quant_cost_qty.items(): + move_lines = self._prepare_account_move_line(cr, uid, move, qty, cost, credit_account_id, debit_account_id, context=context) + period_id = context.get('force_period', self.pool.get('account.period').find(cr, uid, move.date, context=context)[0]) + move_obj.create(cr, uid, {'journal_id': journal_id, + 'line_id': move_lines, + 'period_id': period_id, + 'date': move.date, + 'ref': move.picking_id and move.picking_id.name}, context=context) + + #def _reconcile_single_negative_quant(self, cr, uid, to_solve_quant, quant, quant_neg, qty, context=None): + # move = self._get_latest_move(cr, uid, to_solve_quant, context=context) + # quant_neg_position = quant_neg.negative_dest_location_id.usage + # remaining_solving_quant, remaining_to_solve_quant = super(stock_quant, self)._reconcile_single_negative_quant(cr, uid, to_solve_quant, quant, quant_neg, qty, context=context) + # #update the standard price of the product, only if we would have done it if we'd have had enough stock at first, which means + # #1) there isn't any negative quant anymore + # #2) the product cost's method is 'real' + # #3) we just fixed a negative quant caused by an outgoing shipment + # if not remaining_to_solve_quant and move.product_id.cost_method == 'real' and quant_neg_position != 'internal': + # self.pool.get('stock.move')._store_average_cost_price(cr, uid, move, context=context) + # return remaining_solving_quant, remaining_to_solve_quant + +class stock_move(osv.osv): + _inherit = "stock.move" + + def action_done(self, cr, uid, ids, context=None): + self.product_price_update_before_done(cr, uid, ids, context=context) + super(stock_move, self).action_done(cr, uid, ids, context=context) + self.product_price_update_after_done(cr, uid, ids, context=context) + + def _store_average_cost_price(self, cr, uid, move, context=None): + ''' move is a browe record ''' + product_obj = self.pool.get('product.product') + move.refresh() + if any([q.qty <= 0 for q in move.quant_ids]): + #if there is a negative quant, the standard price shouldn't be updated + return + #Note: here we can't store a quant.cost directly as we may have moved out 2 units (1 unit to 5€ and 1 unit to 7€) and in case of a product return of 1 unit, we can't know which of the 2 costs has to be used (5€ or 7€?). So at that time, thanks to the average valuation price we are storing we will svaluate it at 6€ + average_valuation_price = 0.0 + for q in move.quant_ids: + average_valuation_price += q.qty * q.cost + average_valuation_price = average_valuation_price / move.product_qty + # Write the standard price, as SUPERUSER_ID because a warehouse manager may not have the right to write on products + product_obj.write(cr, SUPERUSER_ID, [move.product_id.id], {'standard_price': average_valuation_price}, context=context) + self.write(cr, uid, [move.id], {'price_unit': average_valuation_price}, context=context) + + def product_price_update_before_done(self, cr, uid, ids, context=None): + product_obj = self.pool.get('product.product') + for move in self.browse(cr, uid, ids, context=context): + #adapt standard price on incomming moves if the product cost_method is 'average' + if (move.location_id.usage == 'supplier') and (move.product_id.cost_method == 'average'): + product = move.product_id + company_currency_id = move.company_id.currency_id.id + ctx = {'currency_id': company_currency_id} + product_avail = product.qty_available + if product.qty_available <= 0: + new_std_price = move.price_unit + else: + # Get the standard price + amount_unit = product.standard_price + new_std_price = ((amount_unit * product_avail) + (move.price_unit * move.product_qty)) / (product_avail + move.product_qty) + # Write the standard price, as SUPERUSER_ID because a warehouse manager may not have the right to write on products + product_obj.write(cr, SUPERUSER_ID, [product.id], {'standard_price': new_std_price}, context=context) + + def product_price_update_after_done(self, cr, uid, ids, context=None): + ''' + This method adapts the price on the product when necessary + ''' + for move in self.browse(cr, uid, ids, context=context): + #adapt standard price on outgoing moves if the product cost_method is 'real', so that a return + #or an inventory loss is made using the last value used for an outgoing valuation. + if move.product_id.cost_method == 'real' and move.location_dest_id.usage != 'internal': + #store the average price of the move on the move and product form + self._store_average_cost_price(cr, uid, move, context=context) diff --git a/addons/stock_account/stock_account_data.xml b/addons/stock_account/stock_account_data.xml new file mode 100644 index 00000000000..4dea1742498 --- /dev/null +++ b/addons/stock_account/stock_account_data.xml @@ -0,0 +1,31 @@ + + + + + + stock journal sequence + + STJ/%(year)s/ + + + Stock Journal + STJ + general + + + + + Cost Method Property + + standard + selection + + + Valuation Property + + manual_periodic + selection + + + + diff --git a/addons/stock_account/stock_account_demo.xml b/addons/stock_account/stock_account_demo.xml new file mode 100644 index 00000000000..97a2523b7b4 --- /dev/null +++ b/addons/stock_account/stock_account_demo.xml @@ -0,0 +1,14 @@ + + + + + + property_stock_valuation_account_id + + + + + + + + diff --git a/addons/stock_account/stock_account_view.xml b/addons/stock_account/stock_account_view.xml new file mode 100644 index 00000000000..3b3ab37b212 --- /dev/null +++ b/addons/stock_account/stock_account_view.xml @@ -0,0 +1,75 @@ + + + + + stock.inventory.form.inherit + stock.inventory + + + + + + + + + + stock.location.form.inherit + stock.location + + + + + + + + + + + + + stock.picking.form.inherit + stock.picking + + + +