[MERGE]: Merge with lp:openobject-trunk-dev-addons2
[odoo/odoo.git] / addons / sale_crm / wizard / crm_make_sale.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 fields, osv
23 from tools.translate import _
24 import time
25
26
27 class crm_make_sale(osv.osv_memory):
28     """ Make sale  order for crm """
29
30     _name = "crm.make.sale"
31     _description = "Make sale"
32
33     def _selectPartner(self, cr, uid, context=None):
34         """
35         This function gets default value for partner_id field.
36         @param self: The object pointer
37         @param cr: the current row, from the database cursor,
38         @param uid: the current user’s ID for security checks,
39         @param context: A standard dictionary for contextual values
40         @return: default value of partner_id field.
41         """
42         if not context:
43             context = {}
44
45         lead_obj = self.pool.get('crm.lead')
46         active_id = context and context.get('active_id', False) or False
47         if not active_id:
48             return False
49
50         lead = lead_obj.read(cr, uid, active_id, ['partner_id'])
51         return lead['partner_id']
52
53     def view_init(self, cr, uid, fields_list, context=None):
54         if context is None:
55             context = {}
56         return super(crm_make_sale, self).view_init(cr, uid, fields_list, context=context)
57
58     def makeOrder(self, cr, uid, ids, context=None):
59         """
60         This function  create Quotation on given case.
61         @param self: The object pointer
62         @param cr: the current row, from the database cursor,
63         @param uid: the current user’s ID for security checks,
64         @param ids: List of crm make sale' ids
65         @param context: A standard dictionary for contextual values
66         @return: Dictionary value of created sale order.
67         """
68         if not context:
69             context = {}
70
71         case_obj = self.pool.get('crm.lead')
72         sale_obj = self.pool.get('sale.order')
73         partner_obj = self.pool.get('res.partner')
74
75         data = context and context.get('active_ids', []) or []
76
77         for make in self.browse(cr, uid, ids, context=context):
78             partner = make.partner_id
79             partner_addr = partner_obj.address_get(cr, uid, [partner.id], 
80                     ['default', 'invoice', 'delivery', 'contact'])
81             pricelist = partner.property_product_pricelist.id
82             fpos = partner.property_account_position and partner.property_account_position.id or False
83             new_ids = []
84
85             for case in case_obj.browse(cr, uid, data, context=context):
86                 if not partner and case.partner_id:
87                     partner = case.partner_id
88                     fpos = partner.property_account_position and partner.property_account_position.id or False
89                     partner_addr = partner_obj.address_get(cr, uid, [partner.id], 
90                             ['default', 'invoice', 'delivery', 'contact'])
91                     pricelist = partner.property_product_pricelist.id
92
93                 if False in partner_addr.values():
94                     raise osv.except_osv(_('Data Insufficient!'), _('Customer has no addresses defined!'))
95
96                 vals = {
97                     'origin': _('Opportunity: %s') % str(case.id), 
98                     'section_id': case.section_id and case.section_id.id or False, 
99                     'shop_id': make.shop_id.id, 
100                     'partner_id': partner.id, 
101                     'pricelist_id': pricelist, 
102                     'partner_invoice_id': partner_addr['invoice'], 
103                     'partner_order_id': partner_addr['contact'], 
104                     'partner_shipping_id': partner_addr['delivery'], 
105                     'date_order': time.strftime('%Y-%m-%d'), 
106                     'fiscal_position': fpos, 
107                 }
108
109                 if partner.id:
110                     vals['user_id'] = partner.user_id and partner.user_id.id or uid
111
112                 new_id = sale_obj.create(cr, uid, vals)
113                 case_obj.write(cr, uid, [case.id], {'ref': 'sale.order,%s' % new_id})
114                 new_ids.append(new_id)
115                 message = _('Opportunity ') + " '" + case.name + "' "+ _("is converted to Quotation.")
116                 self.log(cr, uid, case.id, message)
117                 case_obj._history(cr, uid, [case], _("Converted to Sales Quotation(id: %s).") % (new_id))
118
119             if make.close:
120                 case_obj.case_close(cr, uid, data)
121
122             if not new_ids:
123                 return {}
124             if len(new_ids)<=1:
125                 value = {
126                     'domain': str([('id', 'in', new_ids)]), 
127                     'view_type': 'form', 
128                     'view_mode': 'form', 
129                     'res_model': 'sale.order', 
130                     'view_id': False, 
131                     'type': 'ir.actions.act_window', 
132                     'res_id': new_ids and new_ids[0]
133                 }
134             else:
135                 value = {
136                     'domain': str([('id', 'in', new_ids)]), 
137                     'view_type': 'form', 
138                     'view_mode': 'tree,form', 
139                     'res_model': 'sale.order', 
140                     'view_id': False, 
141                     'type': 'ir.actions.act_window', 
142                     'res_id': new_ids
143                 }
144             return value
145
146     def _get_shop_id(self, cr, uid, ids, context=None):
147         if context is None:
148             context = {}
149         cmpny_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
150         shop = self.pool.get('sale.shop').search(cr, uid, [('company_id', '=', cmpny_id)])
151         return shop and shop[0] or False
152
153     _columns = {
154         'shop_id': fields.many2one('sale.shop', 'Shop', required=True), 
155         'partner_id': fields.many2one('res.partner', 'Customer', required=True), 
156         'close': fields.boolean('Close Opportunity', help='Check this to close the opportunity after having created the sale order.'), 
157     }
158     _defaults = {
159          'shop_id': _get_shop_id, 
160          'close': lambda *args: 1, 
161          'partner_id': _selectPartner, 
162     }
163 crm_make_sale()