[MERGE] merged addons trunk development branch after resolving conflicts
[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
28 def geo_find(addr):
29     try:
30         regex = '<coordinates>([+-]?[0-9\.]+),([+-]?[0-9\.]+),([+-]?[0-9\.]+)</coordinates>'
31         url = 'http://maps.google.com/maps/geo?q=' + urllib.quote(addr) + '&output=xml&oe=utf8&sensor=false'
32         xml = urllib.urlopen(url).read()
33         if '<error>' in xml:
34             return None
35         result = re.search(regex, xml, re.M|re.I)
36         if not result:
37             return None
38         return float(result.group(1)),float(result.group(2))
39     except Exception, e:
40         raise osv.except_osv(_('Network error'),
41                              _('Could not contact geolocation servers, please make sure you have a working internet connection (%s)') % e)
42
43
44 class res_partner_grade(osv.osv):
45     _order = 'sequence'
46     _name = 'res.partner.grade'
47     _columns = {
48         'sequence': fields.integer('Sequence'),
49         'active': fields.boolean('Active'),
50         'name': fields.char('Grade Name', size=32)
51     }
52     _defaults = {
53         'active': lambda *args: 1
54     }
55 res_partner_grade()
56
57
58 class res_partner(osv.osv):
59     _inherit = "res.partner"
60     _columns = {
61         'partner_latitude': fields.float('Geo Latitude'),
62         'partner_longitude': fields.float('Geo Longitude'),
63         'date_localization': fields.date('Geo Localization Date'),
64         'partner_weight': fields.integer('Weight',
65             help="Gives the probability to assign a lead to this partner. (0 means no assignation.)"),
66         'opportunity_assigned_ids': fields.one2many('crm.lead', 'partner_assigned_id',\
67             'Assigned Opportunities'),
68         'grade_id': fields.many2one('res.partner.grade', 'Partner Grade')
69     }
70     _defaults = {
71         'partner_weight': lambda *args: 0
72     }
73     def geo_localize(self, cr, uid, ids, context=None):
74         for partner in self.browse(cr, uid, ids, context=context):
75             if not partner.address:
76                 continue
77             part = partner.address[0]
78             addr = ', '.join(filter(None, [part.street, (part.zip or '')+' '+(part.city or ''), part.state_id and part.state_id.name, part.country_id and part.country_id.name]))
79             result = geo_find(addr.encode('utf8'))
80             if result:
81                 self.write(cr, uid, [partner.id], {
82                     'partner_latitude': result[0],
83                     'partner_longitude': result[1],
84                     'date_localization': time.strftime('%Y-%m-%d')
85                 }, context=context)
86         return True
87 res_partner()
88
89 class crm_lead(osv.osv):
90     _inherit = "crm.lead"
91     _columns = {
92         'partner_latitude': fields.float('Geo Latitude'),
93         'partner_longitude': fields.float('Geo Longitude'),
94         'partner_assigned_id': fields.many2one('res.partner', 'Assigned Partner', help="Partner this case has been forwarded/assigned to.", select=True),
95         'date_assign': fields.date('Assignation Date', help="Last date this case was forwarded/assigned to a partner"),
96     }
97     def onchange_assign_id(self, cr, uid, ids, partner_assigned_id, context=None):
98         """This function updates the "assignation date" automatically, when manually assign a partner in the geo assign tab
99             @param self: The object pointer
100             @param cr: the current row, from the database cursor,
101             @param uid: the current user’s ID for security checks,
102             @param ids: List of stage’s IDs
103             @stage_id: change state id on run time """
104
105         if not partner_assigned_id:
106             return {'value':{'date_assign': False}}
107         else:
108             partners = self.pool.get('res.partner').browse(cr, uid, [partner_assigned_id], context=context)
109             user_id = partners[0] and partners[0].user_id.id or False
110             return {'value':
111                         {'date_assign': time.strftime('%Y-%m-%d'),
112                          'user_id' : user_id}
113                    }
114
115     def assign_partner(self, cr, uid, ids, context=None):
116         ok = False
117         for part in self.browse(cr, uid, ids, context=context):
118             if not part.country_id:
119                 continue
120             addr = ', '.join(filter(None, [part.street, (part.zip or '')+' '+(part.city or ''), part.state_id and part.state_id.name, part.country_id and part.country_id.name]))
121             result = geo_find(addr.encode('utf8'))
122             if result:
123                 self.write(cr, uid, [part.id], {
124                     'partner_latitude': result[0],
125                     'partner_longitude': result[1]
126                 }, context=context)
127
128                 # 1. first way: in the same country, small area
129                 part_ids = self.pool.get('res.partner').search(cr, uid, [
130                     ('partner_weight','>',0),
131                     ('partner_latitude','>',result[0]-2), ('partner_latitude','<',result[0]+2),
132                     ('partner_longitude','>',result[1]-1.5), ('partner_longitude','<',result[1]+1.5),
133                     ('country', '=', part.country_id.id),
134                 ], context=context)
135
136                 # 2. second way: in the same country, big area
137                 if not part_ids:
138                     part_ids = self.pool.get('res.partner').search(cr, uid, [
139                         ('partner_weight','>',0),
140                         ('partner_latitude','>',result[0]-4), ('partner_latitude','<',result[0]+4),
141                         ('partner_longitude','>',result[1]-3), ('partner_longitude','<',result[1]+3),
142                         ('country', '=', part.country_id.id),
143                     ], context=context)
144
145
146                 # 5. fifth way: anywhere in same country
147                 if not part_ids:
148                     # still haven't found any, let's take all partners in the country!
149                     part_ids = self.pool.get('res.partner').search(cr, uid, [
150                         ('partner_weight','>',0),
151                         ('country', '=', part.country_id.id),
152                     ], context=context)
153
154                 # 6. sixth way: closest partner whatsoever, just to have at least one result
155                 if not part_ids:
156                     # warning: point() type takes (longitude, latitude) as parameters in this order!
157                     cr.execute("""SELECT id, distance
158                                   FROM  (select id, (point(partner_longitude, partner_latitude) <-> point(%s,%s)) AS distance FROM res_partner
159                                   WHERE partner_longitude is not null
160                                         AND partner_latitude is not null
161                                         AND partner_weight > 0) AS d
162                                   ORDER BY distance LIMIT 1""", (result[1],result[0]))
163                     res = cr.dictfetchone()
164                     if res:
165                         part_ids.append(res['id'])
166
167                 total = 0
168                 toassign = []
169                 for part2 in self.pool.get('res.partner').browse(cr, uid, part_ids, context=context):
170                     total += part2.partner_weight
171                     toassign.append( (part2.id, total) )
172                 random.shuffle(toassign) # avoid always giving the leads to the first ones in db natural order!
173                 mypartner = random.randint(0,total)
174                 for t in toassign:
175                     if mypartner<=t[1]:
176                         vals = self.onchange_assign_id(cr,uid, ids, t[0], context=context)['value']
177                         vals.update({'partner_assigned_id': t[0], 'date_assign': time.strftime('%Y-%m-%d')})
178                         self.write(cr, uid, [part.id], vals, context=context)
179                         break
180             ok = True
181         return ok
182 crm_lead()
183