Merge with addons-trunk revno 7150
[odoo/odoo.git] / addons / purchase / wizard / purchase_line_invoice.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 from osv import osv
23 from tools.translate import _
24
25
26 class purchase_line_invoice(osv.osv_memory):
27
28     """ To create invoice for purchase order line"""
29
30     _name = 'purchase.order.line_invoice'
31     _description = 'Purchase Order Line Make Invoice'
32
33     def makeInvoices(self, cr, uid, ids, context=None):
34
35         """
36              To get Purchase Order line and create Invoice
37              @param self: The object pointer.
38              @param cr: A database cursor
39              @param uid: ID of the user currently logged in
40              @param context: A standard dictionary
41              @return : retrun view of Invoice
42         """
43
44         if context is None:
45             context={}
46
47         record_ids =  context.get('active_ids',[])
48         if record_ids:
49             res = False
50             invoices = {}
51             invoice_obj=self.pool.get('account.invoice')
52             purchase_line_obj=self.pool.get('purchase.order.line')
53             property_obj=self.pool.get('ir.property')
54             account_fiscal_obj=self.pool.get('account.fiscal.position')
55             invoice_line_obj=self.pool.get('account.invoice.line')
56             account_jrnl_obj=self.pool.get('account.journal')
57
58             def multiple_order_invoice_notes(orders):
59                 notes = ""
60                 for order in orders:
61                     notes += "%s \n" % order.notes
62                 return notes
63
64
65
66             def make_invoice_by_partner(partner, orders, lines_ids):
67                 """
68                     create a new invoice for one supplier
69                     @param partner : The object partner
70                     @param orders : The set of orders to add in the invoice
71                     @param lines : The list of line's id
72                 """
73                 name = orders and orders[0].name or ''
74                 journal_id = account_jrnl_obj.search(cr, uid, [('type', '=', 'purchase')], context=None)
75                 journal_id = journal_id and journal_id[0] or False
76                 a = partner.property_account_payable.id
77                 inv = {
78                     'name': name,
79                     'origin': name,
80                     'type': 'in_invoice',
81                     'journal_id':journal_id,
82                     'reference' : partner.ref,
83                     'account_id': a,
84                     'partner_id': partner.id,
85                     'invoice_line': [(6,0,lines_ids)],
86                     'currency_id' : orders[0].pricelist_id.currency_id.id,
87                     'comment': multiple_order_invoice_notes(orders),
88                     'payment_term': orders[0].payment_term.id,
89                     'fiscal_position': partner.property_account_position.id
90                 }
91                 inv_id = invoice_obj.create(cr, uid, inv)
92                 for order in orders:
93                     order.write({'invoice_ids': [(4, inv_id)]})
94                 return inv_id
95
96             for line in purchase_line_obj.browse(cr,uid,record_ids):
97                 if (not line.invoiced) and (line.state not in ('draft','cancel')):
98                     if not line.partner_id.id in invoices:
99                         invoices[line.partner_id.id] = []
100                     if line.product_id:
101                         a = line.product_id.product_tmpl_id.property_account_expense.id
102                         if not a:
103                             a = line.product_id.categ_id.property_account_expense_categ.id
104                         if not a:
105                             raise osv.except_osv(_('Error !'),
106                                     _('There is no expense account defined ' \
107                                             'for this product: "%s" (id:%d)') % \
108                                             (line.product_id.name, line.product_id.id,))
109                     else:
110                         a = property_obj.get(cr, uid,
111                                 'property_account_expense_categ', 'product.category',
112                                 context=context).id
113                     fpos = line.order_id.fiscal_position or False
114                     a = account_fiscal_obj.map_account(cr, uid, fpos, a)
115                     inv_id = invoice_line_obj.create(cr, uid, {
116                         'name': line.name,
117                         'origin': line.order_id.name,
118                         'account_id': a,
119                         'price_unit': line.price_unit,
120                         'quantity': line.product_qty,
121                         'uos_id': line.product_uom.id,
122                         'product_id': line.product_id.id or False,
123                         'invoice_line_tax_id': [(6, 0, [x.id for x in line.taxes_id])],
124                         'account_analytic_id': line.account_analytic_id and line.account_analytic_id.id or False,
125                     })
126                     purchase_line_obj.write(cr, uid, [line.id], {'invoiced': True, 'invoice_lines': [(4, inv_id)]})
127                     invoices[line.partner_id.id].append((line,inv_id))
128
129             res = []
130             for result in invoices.values():
131                 il = map(lambda x: x[1], result)
132                 orders = list(set(map(lambda x : x[0].order_id, result)))
133
134                 res.append(make_invoice_by_partner(orders[0].partner_id, orders, il))
135
136         return {
137             'domain': "[('id','in', ["+','.join(map(str,res))+"])]",
138             'name': _('Supplier Invoices'),
139             'view_type': 'form',
140             'view_mode': 'tree,form',
141             'res_model': 'account.invoice',
142             'view_id': False,
143             'context': "{'type':'in_invoice', 'journal_type': 'purchase'}",
144             'type': 'ir.actions.act_window'
145         }
146 purchase_line_invoice()
147
148
149 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
150