[imp] minor improvement for future bug fix
[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 class res_partner_activation(osv.osv):
61     _name = 'res.partner.activation'
62     _order = 'sequence'
63
64     _columns = {
65         'sequence' : fields.integer('Sequence'),
66         'name' : fields.char('Name', size=32, required=True),
67     }
68
69 res_partner_activation()
70
71 class res_partner(osv.osv):
72     _inherit = "res.partner"
73     _columns = {
74         'partner_latitude': fields.float('Geo Latitude'),
75         'partner_longitude': fields.float('Geo Longitude'),
76         'date_localization': fields.date('Geo Localization Date'),
77         'partner_weight': fields.integer('Weight',
78             help="Gives the probability to assign a lead to this partner. (0 means no assignation.)"),
79         'opportunity_assigned_ids': fields.one2many('crm.lead', 'partner_assigned_id',\
80             'Assigned Opportunities'),
81         'grade_id': fields.many2one('res.partner.grade', 'Partner Grade'),
82         'activation' : fields.many2one('res.partner.activation', 'Activation', select=1),
83         'date_partnership' : fields.date('Partnership Date'),
84         'date_review' : fields.date('Latest Partner Review'),
85         'date_review_next' : fields.date('Next Partner Review'),
86     }
87     _defaults = {
88         'partner_weight': lambda *args: 0
89     }
90     def geo_localize(self, cr, uid, ids, context=None):
91         for partner in self.browse(cr, uid, ids, context=context):
92             if not partner.address:
93                 continue
94             contact = partner.address[0] #TOFIX: should be get latitude and longitude for default contact?
95             addr = ', '.join(filter(None, [
96                     contact.street, 
97                     "%s %s" % (contact.zip , contact.city), 
98                     contact.state_id and contact.state_id.name, 
99                     contact.country_id and contact.country_id.name]))
100             result = geo_find(tools.ustr(addr))
101             if result:
102                 self.write(cr, uid, [partner.id], {
103                     'partner_latitude': result[0],
104                     'partner_longitude': result[1],
105                     'date_localization': fields.date.context_today(self,cr,uid,context=context)
106                 }, context=context)
107         return True
108 res_partner()
109
110 class crm_lead(osv.osv):
111     _inherit = "crm.lead"
112     _columns = {
113         'partner_latitude': fields.float('Geo Latitude'),
114         'partner_longitude': fields.float('Geo Longitude'),
115         'partner_assigned_id': fields.many2one('res.partner', 'Assigned Partner', help="Partner this case has been forwarded/assigned to.", select=True),
116         'date_assign': fields.date('Assignation Date', help="Last date this case was forwarded/assigned to a partner"),
117     }
118     def _merge_data(self, cr, uid, ids, oldest, fields, context=None):
119         fields += ['partner_latitude', 'partner_longitude', 'partner_assigned_id', 'date_assign']
120         return super(crm_lead, self)._merge_data(cr, uid, ids, oldest, fields, context=context)
121
122     def onchange_assign_id(self, cr, uid, ids, partner_assigned_id, context=None):
123         """This function updates the "assignation date" automatically, when manually assign a partner in the geo assign tab
124         """
125         if not partner_assigned_id:
126             return {'value':{'date_assign': False}}
127         else:
128             partners = self.pool.get('res.partner').browse(cr, uid, [partner_assigned_id], context=context)
129             user_id = partners[0] and partners[0].user_id.id or False
130             return {'value':
131                         {'date_assign': fields.date.context_today(self,cr,uid,context=context),
132                          'user_id' : user_id}
133                    }
134
135     def action_assign_partner(self, cr, uid, ids, context=None):
136         return self.assign_partner(cr, uid, ids, partner_id=False, context=context)
137
138     def assign_partner(self, cr, uid, ids, partner_id=False, context=None):
139         partner_ids = {}
140         res = False
141         res_partner = self.pool.get('res.partner')
142         if not partner_id:
143             partner_ids = self.search_geo_partner(cr, uid, ids, context=context)
144         for lead in self.browse(cr, uid, ids, context=context):
145             if not partner_id:
146                 partner_id = partner_ids.get(lead.id, False)
147             if not partner_id:
148                 continue
149             self.assign_geo_localize(cr, uid, [lead.id], lead.partner_latitude, lead.partner_longitude, context=context)
150             partner = res_partner.browse(cr, uid, partner_id, context=context)
151             if partner.user_id:
152                 for lead_id in ids:
153                     self.allocate_salesman(cr, uid, [lead_id], [partner.user_id.id], context=context)
154             self.write(cr, uid, [lead.id], {'date_assign': fields.date.context_today(self,cr,uid,context=context), 'partner_assigned_id': partner_id}, context=context)
155         return res
156
157
158     def assign_geo_localize(self, cr, uid, ids, latitude=False, longitude=False, context=None):
159         for lead in self.browse(cr, uid, ids, context=context):
160             if not lead.country_id:
161                 continue
162             addr = ', '.join(filter(None, [
163                     lead.street, 
164                     "%s %s" % (lead.zip, lead.city), 
165                     lead.state_id and lead.state_id.name or '', 
166                     lead.country_id and lead.country_id.name or ''
167             ]))
168             result = geo_find(tools.ustr(addr))
169             if not latitude and result:
170                 latitude = result[0]
171             if not longitude and result:
172                 longitude = result[1]
173             self.write(cr, uid, [lead.id], {
174                 'partner_latitude': latitude,
175                 'partner_longitude': longitude
176             }, context=context)
177         return True
178         
179     def search_geo_partner(self, cr, uid, ids, context=None):
180         res_partner = self.pool.get('res.partner')
181         res_partner_ids = {}
182         self.assign_geo_localize(cr, uid, ids, context=context)
183         for lead in self.browse(cr, uid, ids, context=context):
184             partner_ids = []
185             if not lead.country_id:
186                 continue
187             latitude = lead.partner_latitude
188             longitude = lead.partner_longitude
189             if latitude and longitude:
190                 # 1. first way: in the same country, small area
191                 partner_ids = res_partner.search(cr, uid, [
192                     ('partner_weight', '>', 0),
193                     ('partner_latitude', '>', latitude - 2), ('partner_latitude', '<', latitude + 2),
194                     ('partner_longitude', '>', longitude - 1.5), ('partner_longitude', '<', longitude + 1.5),
195                     ('country', '=', lead.country_id.id),
196                 ], context=context)
197
198                 # 2. second way: in the same country, big area
199                 if not partner_ids:
200                     partner_ids = res_partner.search(cr, uid, [
201                         ('partner_weight', '>', 0),
202                         ('partner_latitude', '>', latitude - 4), ('partner_latitude', '<', latitude + 4),
203                         ('partner_longitude', '>', longitude - 3), ('partner_longitude', '<' , longitude + 3),
204                         ('country', '=', lead.country_id.id),
205                     ], context=context)
206
207
208                 # 5. fifth way: anywhere in same country
209                 if not partner_ids:
210                     # still haven't found any, let's take all partners in the country!
211                     partner_ids = res_partner.search(cr, uid, [
212                         ('partner_weight', '>', 0),
213                         ('country', '=', lead.country_id.id),
214                     ], context=context)
215
216                 # 6. sixth way: closest partner whatsoever, just to have at least one result
217                 if not partner_ids:
218                     # warning: point() type takes (longitude, latitude) as parameters in this order!
219                     cr.execute("""SELECT id, distance
220                                   FROM  (select id, (point(partner_longitude, partner_latitude) <-> point(%s,%s)) AS distance FROM res_partner
221                                   WHERE partner_longitude is not null
222                                         AND partner_latitude is not null
223                                         AND partner_weight > 0) AS d
224                                   ORDER BY distance LIMIT 1""", (longitude, latitude))
225                     res = cr.dictfetchone()
226                     if res:
227                         partner_ids.append(res['id'])
228
229                 total_weight = 0
230                 toassign = []
231                 for partner in res_partner.browse(cr, uid, partner_ids, context=context):
232                     total_weight += partner.partner_weight
233                     toassign.append( (partner.id, total_weight) )
234
235                 random.shuffle(toassign) # avoid always giving the leads to the first ones in db natural order!
236                 nearest_weight = random.randint(0, total_weight)
237                 for partner_id, weight in toassign:
238                     if nearest_weight <= weight:
239                         res_partner_ids[lead.id] = partner_id
240                         break
241         return res_partner_ids
242 crm_lead()
243
244
245 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: