1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
23 from osv import fields
26 from tools.translate import _
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'
34 xml = urllib.urlopen(url).read()
36 raise osv.except_osv(_('Network error'),
37 _('Could not contact geolocation servers, please make sure you have a working internet connection (%s)') % e)
41 result = re.search(regex, xml, re.M|re.I)
44 return float(result.group(2)),float(result.group(1))
46 def geo_query_address(street=None, zip=None, city=None, state=None, country=None):
47 if country and ',' in country and (country.endswith(' of') or country.endswith(' of the')):
48 # put country qualifier in front, otherwise GMap gives wrong results,
49 # e.g. 'Congo, Democratic Republic of the' => 'Democratic Republic of the Congo'
50 country = '{1} {0}'.format(*country.split(',',1))
51 return tools.ustr(', '.join(filter(None, [street,
52 ("%s %s" % (zip or '', city or '')).strip(),
56 class res_partner_grade(osv.osv):
58 _name = 'res.partner.grade'
60 'sequence': fields.integer('Sequence'),
61 'active': fields.boolean('Active'),
62 'name': fields.char('Grade Name', size=32)
65 'active': lambda *args: 1
69 class res_partner_activation(osv.osv):
70 _name = 'res.partner.activation'
74 'sequence' : fields.integer('Sequence'),
75 'name' : fields.char('Name', size=32, required=True),
78 res_partner_activation()
80 class res_partner(osv.osv):
81 _inherit = "res.partner"
83 'partner_latitude': fields.float('Geo Latitude'),
84 'partner_longitude': fields.float('Geo Longitude'),
85 'date_localization': fields.date('Geo Localization Date'),
86 'partner_weight': fields.integer('Weight',
87 help="Gives the probability to assign a lead to this partner. (0 means no assignation.)"),
88 'opportunity_assigned_ids': fields.one2many('crm.lead', 'partner_assigned_id',\
89 'Assigned Opportunities'),
90 'grade_id': fields.many2one('res.partner.grade', 'Partner Grade'),
91 'activation' : fields.many2one('res.partner.activation', 'Activation', select=1),
92 'date_partnership' : fields.date('Partnership Date'),
93 'date_review' : fields.date('Latest Partner Review'),
94 'date_review_next' : fields.date('Next Partner Review'),
97 'partner_weight': lambda *args: 0
99 def geo_localize(self, cr, uid, ids, context=None):
100 # Don't pass context to browse()! We need country names in english below
101 for partner in self.browse(cr, uid, ids):
102 if not partner.address:
104 contact = partner.address[0] #TOFIX: should be get latitude and longitude for default contact?
105 result = geo_find(geo_query_address(street=contact.street,
108 state=contact.state_id.name,
109 country=contact.country_id.name))
111 self.write(cr, uid, [partner.id], {
112 'partner_latitude': result[0],
113 'partner_longitude': result[1],
114 'date_localization': fields.date.context_today(self,cr,uid,context=context)
119 class crm_lead(osv.osv):
120 _inherit = "crm.lead"
122 'partner_latitude': fields.float('Geo Latitude'),
123 'partner_longitude': fields.float('Geo Longitude'),
124 'partner_assigned_id': fields.many2one('res.partner', 'Assigned Partner', help="Partner this case has been forwarded/assigned to.", select=True),
125 'date_assign': fields.date('Assignation Date', help="Last date this case was forwarded/assigned to a partner"),
127 def _merge_data(self, cr, uid, ids, oldest, fields, context=None):
128 fields += ['partner_latitude', 'partner_longitude', 'partner_assigned_id', 'date_assign']
129 return super(crm_lead, self)._merge_data(cr, uid, ids, oldest, fields, context=context)
131 def onchange_assign_id(self, cr, uid, ids, partner_assigned_id, context=None):
132 """This function updates the "assignation date" automatically, when manually assign a partner in the geo assign tab
134 if not partner_assigned_id:
135 return {'value':{'date_assign': False}}
137 partners = self.pool.get('res.partner').browse(cr, uid, [partner_assigned_id], context=context)
138 user_id = partners[0] and partners[0].user_id.id or False
140 {'date_assign': fields.date.context_today(self,cr,uid,context=context),
144 def action_assign_partner(self, cr, uid, ids, context=None):
145 return self.assign_partner(cr, uid, ids, partner_id=False, context=context)
147 def assign_partner(self, cr, uid, ids, partner_id=False, context=None):
150 res_partner = self.pool.get('res.partner')
152 partner_ids = self.search_geo_partner(cr, uid, ids, context=context)
153 for lead in self.browse(cr, uid, ids, context=context):
155 partner_id = partner_ids.get(lead.id, False)
158 self.assign_geo_localize(cr, uid, [lead.id], lead.partner_latitude, lead.partner_longitude, context=context)
159 partner = res_partner.browse(cr, uid, partner_id, context=context)
162 self.allocate_salesman(cr, uid, [lead_id], [partner.user_id.id], context=context)
163 self.write(cr, uid, [lead.id], {'date_assign': fields.date.context_today(self,cr,uid,context=context), 'partner_assigned_id': partner_id}, context=context)
166 def assign_geo_localize(self, cr, uid, ids, latitude=False, longitude=False, context=None):
167 # Don't pass context to browse()! We need country name in english below
168 for lead in self.browse(cr, uid, ids):
169 if not lead.country_id:
171 result = geo_find(geo_query_address(street=lead.street,
174 state=lead.state_id.name,
175 country=lead.country_id.name))
176 if not latitude and result:
178 if not longitude and result:
179 longitude = result[1]
180 self.write(cr, uid, [lead.id], {
181 'partner_latitude': latitude,
182 'partner_longitude': longitude
186 def search_geo_partner(self, cr, uid, ids, context=None):
187 res_partner = self.pool.get('res.partner')
189 self.assign_geo_localize(cr, uid, ids, context=context)
190 for lead in self.browse(cr, uid, ids, context=context):
192 if not lead.country_id:
194 latitude = lead.partner_latitude
195 longitude = lead.partner_longitude
196 if latitude and longitude:
197 # 1. first way: in the same country, small area
198 partner_ids = res_partner.search(cr, uid, [
199 ('partner_weight', '>', 0),
200 ('partner_latitude', '>', latitude - 2), ('partner_latitude', '<', latitude + 2),
201 ('partner_longitude', '>', longitude - 1.5), ('partner_longitude', '<', longitude + 1.5),
202 ('country', '=', lead.country_id.id),
205 # 2. second way: in the same country, big area
207 partner_ids = res_partner.search(cr, uid, [
208 ('partner_weight', '>', 0),
209 ('partner_latitude', '>', latitude - 4), ('partner_latitude', '<', latitude + 4),
210 ('partner_longitude', '>', longitude - 3), ('partner_longitude', '<' , longitude + 3),
211 ('country', '=', lead.country_id.id),
214 # 3. third way: in the same country, extra large area
216 partner_ids = res_partner.search(cr, uid, [
217 ('partner_weight','>', 0),
218 ('partner_latitude','>', latitude - 8), ('partner_latitude','<', latitude + 8),
219 ('partner_longitude','>', longitude - 8), ('partner_longitude','<', longitude + 8),
220 ('country', '=', lead.country_id.id),
223 # 5. fifth way: anywhere in same country
225 # still haven't found any, let's take all partners in the country!
226 partner_ids = res_partner.search(cr, uid, [
227 ('partner_weight', '>', 0),
228 ('country', '=', lead.country_id.id),
231 # 6. sixth way: closest partner whatsoever, just to have at least one result
233 # warning: point() type takes (longitude, latitude) as parameters in this order!
234 cr.execute("""SELECT id, distance
235 FROM (select id, (point(partner_longitude, partner_latitude) <-> point(%s,%s)) AS distance FROM res_partner
236 WHERE partner_longitude is not null
237 AND partner_latitude is not null
238 AND partner_weight > 0) AS d
239 ORDER BY distance LIMIT 1""", (longitude, latitude))
240 res = cr.dictfetchone()
242 partner_ids.append(res['id'])
246 for partner in res_partner.browse(cr, uid, partner_ids, context=context):
247 total_weight += partner.partner_weight
248 toassign.append( (partner.id, total_weight) )
250 random.shuffle(toassign) # avoid always giving the leads to the first ones in db natural order!
251 nearest_weight = random.randint(0, total_weight)
252 for partner_id, weight in toassign:
253 if nearest_weight <= weight:
254 res_partner_ids[lead.id] = partner_id
256 return res_partner_ids
260 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: