[FIX] crm: Clicked on forword button for lead forward to its partner, Its gave traceback
[odoo/odoo.git] / addons / crm_partner_assign / partner_geo_assign.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 osv import fields
24 import urllib,re
25 import random, time
26 from tools.translate import _
27 import tools
28
29 def geo_find(addr):
30     addr = addr.encode('utf8')
31     regex = '<coordinates>([+-]?[0-9\.]+),([+-]?[0-9\.]+),([+-]?[0-9\.]+)</coordinates>'
32     url = 'http://maps.google.com/maps/geo?q=' + urllib.quote(addr) + '&output=xml&oe=utf8&sensor=false'
33     try:
34         xml = urllib.urlopen(url).read()
35     except Exception, e:
36         raise osv.except_osv(_('Network error'),
37                              _('Could not contact geolocation servers, please make sure you have a working internet connection (%s)') % e)
38
39     if '<error>' in xml:
40         return None
41     result = re.search(regex, xml, re.M|re.I)
42     if not result:
43         return None
44     return float(result.group(2)),float(result.group(1))
45     
46
47 class res_partner_grade(osv.osv):
48     _order = 'sequence'
49     _name = 'res.partner.grade'
50     _columns = {
51         'sequence': fields.integer('Sequence'),
52         'active': fields.boolean('Active'),
53         'name': fields.char('Grade Name', size=32)
54     }
55     _defaults = {
56         'active': lambda *args: 1
57     }
58 res_partner_grade()
59
60
61 class res_partner(osv.osv):
62     _inherit = "res.partner"
63     _columns = {
64         'partner_latitude': fields.float('Geo Latitude'),
65         'partner_longitude': fields.float('Geo Longitude'),
66         'date_localization': fields.date('Geo Localization Date'),
67         'partner_weight': fields.integer('Weight',
68             help="Gives the probability to assign a lead to this partner. (0 means no assignation.)"),
69         'opportunity_assigned_ids': fields.one2many('crm.lead', 'partner_assigned_id',\
70             'Assigned Opportunities'),
71         'grade_id': fields.many2one('res.partner.grade', 'Partner Grade')
72     }
73     _defaults = {
74         'partner_weight': lambda *args: 0
75     }
76     def geo_localize(self, cr, uid, ids, context=None):
77         for partner in self.browse(cr, uid, ids, context=context):
78             if not partner.address:
79                 continue
80             contact = partner.address[0] #TOFIX: should be get latitude and longitude for default contact?
81             addr = ', '.join(filter(None, [
82                     contact.street, 
83                     "%s %s" % (contact.zip , contact.city), 
84                     contact.state_id and contact.state_id.name, 
85                     contact.country_id and contact.country_id.name]))
86             result = geo_find(tools.ustr(addr))
87             if result:
88                 self.write(cr, uid, [partner.id], {
89                     'partner_latitude': result[0],
90                     'partner_longitude': result[1],
91                     'date_localization': time.strftime('%Y-%m-%d')
92                 }, context=context)
93         return True
94 res_partner()
95
96 class crm_lead(osv.osv):
97     _inherit = "crm.lead"
98     _columns = {
99         'partner_latitude': fields.float('Geo Latitude'),
100         'partner_longitude': fields.float('Geo Longitude'),
101         'partner_assigned_id': fields.many2one('res.partner', 'Assigned Partner', help="Partner this case has been forwarded/assigned to.", select=True),
102         'date_assign': fields.date('Assignation Date', help="Last date this case was forwarded/assigned to a partner"),
103     }
104     def _merge_data(self, cr, uid, ids, oldest, fields, context=None):
105         fields += ['partner_latitude', 'partner_longitude', 'partner_assigned_id', 'date_assign']
106         return super(crm_lead, self)._merge_data(cr, uid, ids, oldest, fields, context=context)
107
108     def onchange_assign_id(self, cr, uid, ids, partner_assigned_id, context=None):
109         """This function updates the "assignation date" automatically, when manually assign a partner in the geo assign tab
110         """
111         if not partner_assigned_id:
112             return {'value':{'date_assign': False}}
113         else:
114             partners = self.pool.get('res.partner').browse(cr, uid, [partner_assigned_id], context=context)
115             user_id = partners[0] and partners[0].user_id.id or False
116             return {'value':
117                         {'date_assign': time.strftime('%Y-%m-%d'),
118                          'user_id' : user_id}
119                    }
120
121     def assign_partner(self, cr, uid, ids, partner_id=False, context=None):
122         partner_ids = {}
123         res = False
124         res_partner = self.pool.get('res.partner')
125         if not partner_id:
126             partner_ids = self.search_geo_partner(cr, uid, ids, context=context)
127         for lead in self.browse(cr, uid, ids, context=context):
128             if not partner_id:
129                 partner_id = partner_ids.get(lead.id, False)
130             partner = res_partner.browse(cr, uid, partner_id, context=context)
131             if partner.user_id:
132                 for lead_id in ids:
133                     self.allocate_salesman(cr, uid, [lead_id], [partner.user_id.id], context=context)
134             self.write(cr, uid, [lead.id], {'date_assign': time.strftime('%Y-%m-%d'), 'partner_assigned_id': partner_id}, context=context)
135         return res
136         
137
138     def assign_geo_localize(self, cr, uid, ids, latitude=False, longitude=False, context=None):
139         for lead in self.browse(cr, uid, ids, context=context):
140             if not lead.country_id:
141                 continue
142             addr = ', '.join(filter(None, [
143                     lead.street, 
144                     "%s %s" % (lead.zip, lead.city), 
145                     lead.state_id and lead.state_id.name or '', 
146                     lead.country_id and lead.country_id.name or ''
147             ]))
148             result = geo_find(tools.ustr(addr))
149             if not latitude and result:
150                 latitude = result[0]
151             if not longitude and result:
152                 longitude = result[1]
153             self.write(cr, uid, [lead.id], {
154                 'partner_latitude': latitude,
155                 'partner_longitude': longitude
156             }, context=context)
157         return True
158         
159     def search_geo_partner(self, cr, uid, ids, context=None):
160         res_partner = self.pool.get('res.partner')
161         res_partner_ids = {}
162         self.assign_geo_localize(cr, uid, ids, context=context)
163         for lead in self.browse(cr, uid, ids, context=context):
164             partner_ids = []
165             if not lead.country_id:
166                 continue
167             latitude = lead.partner_latitude
168             longitude = lead.partner_longitude
169             if latitude and longitude:
170                 # 1. first way: in the same country, small area
171                 partner_ids = res_partner.search(cr, uid, [
172                     ('partner_weight', '>', 0),
173                     ('partner_latitude', '>', latitude - 2), ('partner_latitude', '<', latitude + 2),
174                     ('partner_longitude', '>', longitude - 1.5), ('partner_longitude', '<', longitude + 1.5),
175                     ('country', '=', lead.country_id.id),
176                 ], context=context)
177
178                 # 2. second way: in the same country, big area
179                 if not partner_ids:
180                     partner_ids = res_partner.search(cr, uid, [
181                         ('partner_weight', '>', 0),
182                         ('partner_latitude', '>', latitude - 4), ('partner_latitude', '<', latitude + 4),
183                         ('partner_longitude', '>', longitude - 3), ('partner_longitude', '<' , longitude + 3),
184                         ('country', '=', lead.country_id.id),
185                     ], context=context)
186
187
188                 # 5. fifth way: anywhere in same country
189                 if not partner_ids:
190                     # still haven't found any, let's take all partners in the country!
191                     partner_ids = partner.search(cr, uid, [
192                         ('partner_weight', '>', 0),
193                         ('country', '=', lead.country_id.id),
194                     ], context=context)
195
196                 # 6. sixth way: closest partner whatsoever, just to have at least one result
197                 if not partner_ids:
198                     # warning: point() type takes (longitude, latitude) as parameters in this order!
199                     cr.execute("""SELECT id, distance
200                                   FROM  (select id, (point(partner_longitude, partner_latitude) <-> point(%s,%s)) AS distance FROM res_partner
201                                   WHERE partner_longitude is not null
202                                         AND partner_latitude is not null
203                                         AND partner_weight > 0) AS d
204                                   ORDER BY distance LIMIT 1""", (longitude, latitude))
205                     res = cr.dictfetchone()
206                     if res:
207                         partner_ids.append(res['id'])
208
209                 total_weight = 0
210                 toassign = []
211                 for partner in res_partner.browse(cr, uid, partner_ids, context=context):
212                     total_weight += partner.partner_weight
213                     toassign.append( (partner.id, total_weight) )
214
215                 random.shuffle(toassign) # avoid always giving the leads to the first ones in db natural order!
216                 nearest_weight = random.randint(0, total_weight)
217                 for partner_id, weight in toassign:
218                     if nearest_weight <= weight:
219                         res_partner_ids[lead.id] = partner_id
220                         break
221         return res_partner_ids
222 crm_lead()
223