[MERGE] forward port of branch saas-3 up to ebf317a
[odoo/odoo.git] / openerp / addons / base / res / res_partner.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 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 import datetime
23 from lxml import etree
24 import math
25 import pytz
26 import urlparse
27
28 import openerp
29 from openerp import SUPERUSER_ID
30 from openerp import tools
31 from openerp.osv import osv, fields
32 from openerp.osv.expression import get_unaccent_wrapper
33 from openerp.tools.translate import _
34
35 class format_address(object):
36     def fields_view_get_address(self, cr, uid, arch, context={}):
37         user_obj = self.pool['res.users']
38         fmt = user_obj.browse(cr, SUPERUSER_ID, uid, context).company_id.country_id
39         fmt = fmt and fmt.address_format
40         layouts = {
41             '%(city)s %(state_code)s\n%(zip)s': """
42                 <div class="address_format">
43                     <field name="city" placeholder="City" style="width: 50%%"/>
44                     <field name="state_id" class="oe_no_button" placeholder="State" style="width: 47%%" options='{"no_open": true}'/>
45                     <br/>
46                     <field name="zip" placeholder="ZIP"/>
47                 </div>
48             """,
49             '%(zip)s %(city)s': """
50                 <div class="address_format">
51                     <field name="zip" placeholder="ZIP" style="width: 40%%"/>
52                     <field name="city" placeholder="City" style="width: 57%%"/>
53                     <br/>
54                     <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
55                 </div>
56             """,
57             '%(city)s\n%(state_name)s\n%(zip)s': """
58                 <div class="address_format">
59                     <field name="city" placeholder="City"/>
60                     <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
61                     <field name="zip" placeholder="ZIP"/>
62                 </div>
63             """
64         }
65         for k,v in layouts.items():
66             if fmt and (k in fmt):
67                 doc = etree.fromstring(arch)
68                 for node in doc.xpath("//div[@class='address_format']"):
69                     tree = etree.fromstring(v)
70                     node.getparent().replace(node, tree)
71                 arch = etree.tostring(doc)
72                 break
73         return arch
74
75
76 def _tz_get(self,cr,uid, context=None):
77     # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728
78     return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]
79
80 class res_partner_category(osv.osv):
81
82     def name_get(self, cr, uid, ids, context=None):
83         """Return the categories' display name, including their direct
84            parent by default.
85
86         :param dict context: the ``partner_category_display`` key can be
87                              used to select the short version of the
88                              category name (without the direct parent),
89                              when set to ``'short'``. The default is
90                              the long version."""
91         if context is None:
92             context = {}
93         if context.get('partner_category_display') == 'short':
94             return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
95         if isinstance(ids, (int, long)):
96             ids = [ids]
97         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context=context)
98         res = []
99         for record in reads:
100             name = record['name']
101             if record['parent_id']:
102                 name = record['parent_id'][1] + ' / ' + name
103             res.append((record['id'], name))
104         return res
105
106     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
107         if not args:
108             args = []
109         if not context:
110             context = {}
111         if name:
112             # Be sure name_search is symetric to name_get
113             name = name.split(' / ')[-1]
114             ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
115         else:
116             ids = self.search(cr, uid, args, limit=limit, context=context)
117         return self.name_get(cr, uid, ids, context)
118
119
120     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
121         res = self.name_get(cr, uid, ids, context=context)
122         return dict(res)
123
124     _description = 'Partner Tags'
125     _name = 'res.partner.category'
126     _columns = {
127         'name': fields.char('Category Name', required=True, size=64, translate=True),
128         'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
129         'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
130         'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
131         'active': fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
132         'parent_left': fields.integer('Left parent', select=True),
133         'parent_right': fields.integer('Right parent', select=True),
134         'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'),
135     }
136     _constraints = [
137         (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
138     ]
139     _defaults = {
140         'active': 1,
141     }
142     _parent_store = True
143     _parent_order = 'name'
144     _order = 'parent_left'
145
146 class res_partner_title(osv.osv):
147     _name = 'res.partner.title'
148     _order = 'name'
149     _columns = {
150         'name': fields.char('Title', required=True, size=46, translate=True),
151         'shortcut': fields.char('Abbreviation', size=16, translate=True),
152         'domain': fields.selection([('partner', 'Partner'), ('contact', 'Contact')], 'Domain', required=True, size=24)
153     }
154     _defaults = {
155         'domain': 'contact',
156     }
157
158 def _lang_get(self, cr, uid, context=None):
159     lang_pool = self.pool['res.lang']
160     ids = lang_pool.search(cr, uid, [], context=context)
161     res = lang_pool.read(cr, uid, ids, ['code', 'name'], context)
162     return [(r['code'], r['name']) for r in res]
163
164 # fields copy if 'use_parent_address' is checked
165 ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
166
167 class res_partner(osv.osv, format_address):
168     _description = 'Partner'
169     _name = "res.partner"
170
171     def _address_display(self, cr, uid, ids, name, args, context=None):
172         res = {}
173         for partner in self.browse(cr, uid, ids, context=context):
174             res[partner.id] = self._display_address(cr, uid, partner, context=context)
175         return res
176
177     def _get_image(self, cr, uid, ids, name, args, context=None):
178         result = dict.fromkeys(ids, False)
179         for obj in self.browse(cr, uid, ids, context=context):
180             result[obj.id] = tools.image_get_resized_images(obj.image)
181         return result
182
183     def _get_tz_offset(self, cr, uid, ids, name, args, context=None):
184         result = dict.fromkeys(ids, False)
185         for obj in self.browse(cr, uid, ids, context=context):
186             result[obj.id] = datetime.datetime.now(pytz.timezone(obj.tz or 'GMT')).strftime('%z')
187         return result
188
189     def _set_image(self, cr, uid, id, name, value, args, context=None):
190         return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
191
192     def _has_image(self, cr, uid, ids, name, args, context=None):
193         result = {}
194         for obj in self.browse(cr, uid, ids, context=context):
195             result[obj.id] = obj.image != False
196         return result
197
198     def _commercial_partner_compute(self, cr, uid, ids, name, args, context=None):
199         """ Returns the partner that is considered the commercial
200         entity of this partner. The commercial entity holds the master data
201         for all commercial fields (see :py:meth:`~_commercial_fields`) """
202         result = dict.fromkeys(ids, False)
203         for partner in self.browse(cr, uid, ids, context=context):
204             current_partner = partner 
205             while not current_partner.is_company and current_partner.parent_id:
206                 current_partner = current_partner.parent_id
207             result[partner.id] = current_partner.id
208         return result
209
210     def _display_name_compute(self, cr, uid, ids, name, args, context=None):
211         context = dict(context or {})
212         context.pop('show_address', None)
213         context.pop('show_address_only', None)
214         context.pop('show_email', None)
215         return dict(self.name_get(cr, uid, ids, context=context))
216
217     # indirections to avoid passing a copy of the overridable method when declaring the function field
218     _commercial_partner_id = lambda self, *args, **kwargs: self._commercial_partner_compute(*args, **kwargs)
219     _display_name = lambda self, *args, **kwargs: self._display_name_compute(*args, **kwargs)
220
221     _commercial_partner_store_triggers = {
222         'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
223                         ['parent_id', 'is_company'], 10)
224     }
225     _display_name_store_triggers = {
226         'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
227                         ['parent_id', 'is_company', 'name'], 10)
228     }
229
230     _order = "display_name"
231     _columns = {
232         'name': fields.char('Name', size=128, required=True, select=True),
233         'display_name': fields.function(_display_name, type='char', string='Name', store=_display_name_store_triggers, select=True),
234         'date': fields.date('Date', select=1),
235         'title': fields.many2one('res.partner.title', 'Title'),
236         'parent_id': fields.many2one('res.partner', 'Related Company', select=True),
237         'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts', domain=[('active','=',True)]), # force "active_test" domain to bypass _search() override
238         'ref': fields.char('Contact Reference', size=64, select=1),
239         'lang': fields.selection(_lang_get, 'Language',
240             help="If the selected language is loaded in the system, all documents related to this contact will be printed in this language. If not, it will be English."),
241         'tz': fields.selection(_tz_get,  'Timezone', size=64,
242             help="The partner's timezone, used to output proper date and time values inside printed reports. "
243                  "It is important to set a value for this field. You should use the same timezone "
244                  "that is otherwise used to pick and render date and time values: your computer's timezone."),
245         'tz_offset': fields.function(_get_tz_offset, type='char', size=5, string='Timezone offset', invisible=True),
246         'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this contact if any.'),
247         'vat': fields.char('TIN', size=32, help="Tax Identification Number. Check the box if this contact is subjected to taxes. Used by the some of the legal statements."),
248         'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
249         'website': fields.char('Website', size=64, help="Website of Partner or Company"),
250         'comment': fields.text('Notes'),
251         'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
252         'credit_limit': fields.float(string='Credit Limit'),
253         'ean13': fields.char('EAN13', size=13),
254         'active': fields.boolean('Active'),
255         'customer': fields.boolean('Customer', help="Check this box if this contact is a customer."),
256         'supplier': fields.boolean('Supplier', help="Check this box if this contact is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."),
257         'employee': fields.boolean('Employee', help="Check this box if this contact is an Employee."),
258         'function': fields.char('Job Position', size=128),
259         'type': fields.selection([('default', 'Default'), ('invoice', 'Invoice'),
260                                    ('delivery', 'Shipping'), ('contact', 'Contact'),
261                                    ('other', 'Other')], 'Address Type',
262             help="Used to select automatically the right address according to the context in sales and purchases documents."),
263         'street': fields.char('Street', size=128),
264         'street2': fields.char('Street2', size=128),
265         'zip': fields.char('Zip', change_default=True, size=24),
266         'city': fields.char('City', size=128),
267         'state_id': fields.many2one("res.country.state", 'State', ondelete='restrict'),
268         'country_id': fields.many2one('res.country', 'Country', ondelete='restrict'),
269         'country': fields.related('country_id', type='many2one', relation='res.country', string='Country',
270                                   deprecated="This field will be removed as of OpenERP 7.1, use country_id instead"),
271         'email': fields.char('Email', size=240),
272         'phone': fields.char('Phone', size=64),
273         'fax': fields.char('Fax', size=64),
274         'mobile': fields.char('Mobile', size=64),
275         'birthdate': fields.char('Birthdate', size=64),
276         'is_company': fields.boolean('Is a Company', help="Check if the contact is a company, otherwise it is a person"),
277         'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information  for this contact"),
278         # image: all image fields are base64 encoded and PIL-supported
279         'image': fields.binary("Image",
280             help="This field holds the image used as avatar for this contact, limited to 1024x1024px"),
281         'image_medium': fields.function(_get_image, fnct_inv=_set_image,
282             string="Medium-sized image", type="binary", multi="_get_image",
283             store={
284                 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
285             },
286             help="Medium-sized image of this contact. It is automatically "\
287                  "resized as a 128x128px image, with aspect ratio preserved. "\
288                  "Use this field in form views or some kanban views."),
289         'image_small': fields.function(_get_image, fnct_inv=_set_image,
290             string="Small-sized image", type="binary", multi="_get_image",
291             store={
292                 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
293             },
294             help="Small-sized image of this contact. It is automatically "\
295                  "resized as a 64x64px image, with aspect ratio preserved. "\
296                  "Use this field anywhere a small image is required."),
297         'has_image': fields.function(_has_image, type="boolean"),
298         'company_id': fields.many2one('res.company', 'Company', select=1),
299         'color': fields.integer('Color Index'),
300         'user_ids': fields.one2many('res.users', 'partner_id', 'Users'),
301         'contact_address': fields.function(_address_display,  type='char', string='Complete Address'),
302
303         # technical field used for managing commercial fields
304         'commercial_partner_id': fields.function(_commercial_partner_id, type='many2one', relation='res.partner', string='Commercial Entity', store=_commercial_partner_store_triggers)
305     }
306
307     def _default_category(self, cr, uid, context=None):
308         if context is None:
309             context = {}
310         if context.get('category_id'):
311             return [context['category_id']]
312         return False
313
314     def _get_default_image(self, cr, uid, is_company, context=None, colorize=False):
315         img_path = openerp.modules.get_module_resource('base', 'static/src/img',
316                                                        ('company_image.png' if is_company else 'avatar.png'))
317         with open(img_path, 'rb') as f:
318             image = f.read()
319
320         # colorize user avatars
321         if not is_company:
322             image = tools.image_colorize(image)
323
324         return tools.image_resize_image_big(image.encode('base64'))
325
326     def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
327         if (not view_id) and (view_type=='form') and context and context.get('force_email', False):
328             view_id = self.pool['ir.model.data'].get_object_reference(cr, user, 'base', 'view_partner_simple_form')[1]
329         res = super(res_partner,self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
330         if view_type == 'form':
331             res['arch'] = self.fields_view_get_address(cr, user, res['arch'], context=context)
332         return res
333
334     _defaults = {
335         'active': True,
336         'lang': lambda self, cr, uid, ctx: ctx.get('lang', 'en_US'),
337         'tz': lambda self, cr, uid, ctx: ctx.get('tz', False),
338         'customer': True,
339         'category_id': _default_category,
340         'company_id': lambda self, cr, uid, ctx: self.pool['res.company']._company_default_get(cr, uid, 'res.partner', context=ctx),
341         'color': 0,
342         'is_company': False,
343         'type': 'contact', # type 'default' is wildcard and thus inappropriate
344         'use_parent_address': False,
345         'image': False,
346     }
347
348     _constraints = [
349         (osv.osv._check_recursion, 'You cannot create recursive Partner hierarchies.', ['parent_id']),
350     ]
351
352     def copy(self, cr, uid, id, default=None, context=None):
353         if default is None:
354             default = {}
355         default['user_ids'] = False
356         name = self.read(cr, uid, [id], ['name'], context)[0]['name']
357         default.update({'name': _('%s (copy)') % name})
358         return super(res_partner, self).copy(cr, uid, id, default, context)
359
360     def onchange_type(self, cr, uid, ids, is_company, context=None):
361         value = {}
362         value['title'] = False
363         if is_company:
364             value['use_parent_address'] = False
365             domain = {'title': [('domain', '=', 'partner')]}
366         else:
367             domain = {'title': [('domain', '=', 'contact')]}
368         return {'value': value, 'domain': domain}
369
370     def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
371         def value_or_id(val):
372             """ return val or val.id if val is a browse record """
373             return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
374         result = {}
375         if parent_id:
376             if ids:
377                 partner = self.browse(cr, uid, ids[0], context=context)
378                 if partner.parent_id and partner.parent_id.id != parent_id:
379                     result['warning'] = {'title': _('Warning'),
380                                          'message': _('Changing the company of a contact should only be done if it '
381                                                       'was never correctly set. If an existing contact starts working for a new '
382                                                       'company then a new contact should be created under that new '
383                                                       'company. You can use the "Discard" button to abandon this change.')}
384             if use_parent_address:
385                 parent = self.browse(cr, uid, parent_id, context=context)
386                 address_fields = self._address_fields(cr, uid, context=context)
387                 result['value'] = dict((key, value_or_id(parent[key])) for key in address_fields)
388         else:
389             result['value'] = {'use_parent_address': False}
390         return result
391
392     def onchange_state(self, cr, uid, ids, state_id, context=None):
393         if state_id:
394             country_id = self.pool['res.country.state'].browse(cr, uid, state_id, context).country_id.id
395             return {'value':{'country_id':country_id}}
396         return {}
397
398     def _check_ean_key(self, cr, uid, ids, context=None):
399         for partner_o in self.pool['res.partner'].read(cr, uid, ids, ['ean13',]):
400             thisean=partner_o['ean13']
401             if thisean and thisean!='':
402                 if len(thisean)!=13:
403                     return False
404                 sum=0
405                 for i in range(12):
406                     if not (i % 2):
407                         sum+=int(thisean[i])
408                     else:
409                         sum+=3*int(thisean[i])
410                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
411                     return False
412         return True
413
414 #   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
415
416     def _update_fields_values(self, cr, uid, partner, fields, context=None):
417         """ Returns dict of write() values for synchronizing ``fields`` """
418         values = {}
419         for field in fields:
420             column = self._all_columns[field].column
421             if column._type == 'one2many':
422                 raise AssertionError('One2Many fields cannot be synchronized as part of `commercial_fields` or `address fields`')
423             if column._type == 'many2one':
424                 values[field] = partner[field].id if partner[field] else False
425             elif column._type == 'many2many':
426                 values[field] = [(6,0,[r.id for r in partner[field] or []])]
427             else:
428                 values[field] = partner[field]
429         return values
430
431     def _address_fields(self, cr, uid, context=None):
432         """ Returns the list of address fields that are synced from the parent
433         when the `use_parent_address` flag is set. """
434         return list(ADDRESS_FIELDS)
435
436     def update_address(self, cr, uid, ids, vals, context=None):
437         address_fields = self._address_fields(cr, uid, context=context)
438         addr_vals = dict((key, vals[key]) for key in address_fields if key in vals)
439         if addr_vals:
440             return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
441
442     def _commercial_fields(self, cr, uid, context=None):
443         """ Returns the list of fields that are managed by the commercial entity
444         to which a partner belongs. These fields are meant to be hidden on
445         partners that aren't `commercial entities` themselves, and will be
446         delegated to the parent `commercial entity`. The list is meant to be
447         extended by inheriting classes. """
448         return ['vat']
449
450     def _commercial_sync_from_company(self, cr, uid, partner, context=None):
451         """ Handle sync of commercial fields when a new parent commercial entity is set,
452         as if they were related fields """
453         commercial_partner = partner.commercial_partner_id
454         if not commercial_partner:
455             # On child partner creation of a parent partner,
456             # the commercial_partner_id is not yet computed
457             commercial_partner_id = self._commercial_partner_compute(
458                 cr, uid, [partner.id], 'commercial_partner_id', [], context=context)[partner.id]
459             commercial_partner = self.browse(cr, uid, commercial_partner_id, context=context)
460         if commercial_partner != partner:
461             commercial_fields = self._commercial_fields(cr, uid, context=context)
462             sync_vals = self._update_fields_values(cr, uid, commercial_partner,
463                                                    commercial_fields, context=context)
464             partner.write(sync_vals)
465
466     def _commercial_sync_to_children(self, cr, uid, partner, context=None):
467         """ Handle sync of commercial fields to descendants """
468         commercial_fields = self._commercial_fields(cr, uid, context=context)
469         commercial_partner = partner.commercial_partner_id
470         if not commercial_partner:
471             # On child partner creation of a parent partner,
472             # the commercial_partner_id is not yet computed
473             commercial_partner_id = self._commercial_partner_compute(
474                 cr, uid, [partner.id], 'commercial_partner_id', [], context=context)[partner.id]
475             commercial_partner = self.browse(cr, uid, commercial_partner_id, context=context)
476         sync_vals = self._update_fields_values(cr, uid, commercial_partner,
477                                                commercial_fields, context=context)
478         sync_children = [c for c in partner.child_ids if not c.is_company]
479         for child in sync_children:
480             self._commercial_sync_to_children(cr, uid, child, context=context)
481         return self.write(cr, uid, [c.id for c in sync_children], sync_vals, context=context)
482
483     def _fields_sync(self, cr, uid, partner, update_values, context=None):
484         """ Sync commercial fields and address fields from company and to children after create/update,
485         just as if those were all modeled as fields.related to the parent """
486         # 1. From UPSTREAM: sync from parent
487         if update_values.get('parent_id') or update_values.get('use_parent_address'):
488             # 1a. Commercial fields: sync if parent changed
489             if update_values.get('parent_id'):
490                 self._commercial_sync_from_company(cr, uid, partner, context=context)
491             # 1b. Address fields: sync if parent or use_parent changed *and* both are now set 
492             if partner.parent_id and partner.use_parent_address:
493                 onchange_vals = self.onchange_address(cr, uid, [partner.id],
494                                                       use_parent_address=partner.use_parent_address,
495                                                       parent_id=partner.parent_id.id,
496                                                       context=context).get('value', {})
497                 partner.update_address(onchange_vals)
498
499         # 2. To DOWNSTREAM: sync children 
500         if partner.child_ids:
501             # 2a. Commercial Fields: sync if commercial entity
502             if partner.commercial_partner_id == partner:
503                 commercial_fields = self._commercial_fields(cr, uid,
504                                                             context=context)
505                 if any(field in update_values for field in commercial_fields):
506                     self._commercial_sync_to_children(cr, uid, partner,
507                                                       context=context)
508             # 2b. Address fields: sync if address changed
509             address_fields = self._address_fields(cr, uid, context=context)
510             if any(field in update_values for field in address_fields):
511                 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
512                 update_ids = self.search(cr, uid, domain_children, context=context)
513                 self.update_address(cr, uid, update_ids, update_values, context=context)
514
515     def _handle_first_contact_creation(self, cr, uid, partner, context=None):
516         """ On creation of first contact for a company (or root) that has no address, assume contact address
517         was meant to be company address """
518         parent = partner.parent_id
519         address_fields = self._address_fields(cr, uid, context=context)
520         if parent and (parent.is_company or not parent.parent_id) and len(parent.child_ids) == 1 and \
521             any(partner[f] for f in address_fields) and not any(parent[f] for f in address_fields):
522             addr_vals = self._update_fields_values(cr, uid, partner, address_fields, context=context)
523             parent.update_address(addr_vals)
524             if not parent.is_company:
525                 parent.write({'is_company': True})
526
527     def _clean_website(self, website):
528         (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(website)
529         if not scheme:
530             if not netloc:
531                 netloc, path = path, ''
532             website = urlparse.urlunparse(('http', netloc, path, params, query, fragment))
533         return website
534
535     def write(self, cr, uid, ids, vals, context=None):
536         if isinstance(ids, (int, long)):
537             ids = [ids]
538         #res.partner must only allow to set the company_id of a partner if it
539         #is the same as the company of all users that inherit from this partner
540         #(this is to allow the code from res_users to write to the partner!) or
541         #if setting the company_id to False (this is compatible with any user company)
542         if vals.get('website'):
543             vals['website'] = self._clean_website(vals['website'])
544         if vals.get('company_id'):
545             for partner in self.browse(cr, uid, ids, context=context):
546                 if partner.user_ids:
547                     user_companies = set([user.company_id.id for user in partner.user_ids])
548                     if len(user_companies) > 1 or vals['company_id'] not in user_companies:
549                         raise osv.except_osv(_("Warning"),_("You can not change the company as the partner/user has multiple user linked with different companies."))
550         result = super(res_partner,self).write(cr, uid, ids, vals, context=context)
551         for partner in self.browse(cr, uid, ids, context=context):
552             self._fields_sync(cr, uid, partner, vals, context)
553         return result
554
555     def create(self, cr, uid, vals, context=None):
556         if vals.get('website'):
557             vals['website'] = self._clean_website(vals['website'])
558         new_id = super(res_partner, self).create(cr, uid, vals, context=context)
559         partner = self.browse(cr, uid, new_id, context=context)
560         self._fields_sync(cr, uid, partner, vals, context)
561         self._handle_first_contact_creation(cr, uid, partner, context)
562         return new_id
563
564     def open_commercial_entity(self, cr, uid, ids, context=None):
565         """ Utility method used to add an "Open Company" button in partner views """
566         partner = self.browse(cr, uid, ids[0], context=context)
567         return {'type': 'ir.actions.act_window',
568                 'res_model': 'res.partner',
569                 'view_mode': 'form',
570                 'res_id': partner.commercial_partner_id.id,
571                 'target': 'new',
572                 'flags': {'form': {'action_buttons': True}}}
573
574     def open_parent(self, cr, uid, ids, context=None):
575         """ Utility method used to add an "Open Parent" button in partner views """
576         partner = self.browse(cr, uid, ids[0], context=context)
577         return {'type': 'ir.actions.act_window',
578                 'res_model': 'res.partner',
579                 'view_mode': 'form',
580                 'res_id': partner.parent_id.id,
581                 'target': 'new',
582                 'flags': {'form': {'action_buttons': True}}}
583
584     def name_get(self, cr, uid, ids, context=None):
585         if context is None:
586             context = {}
587         if isinstance(ids, (int, long)):
588             ids = [ids]
589         res = []
590         for record in self.browse(cr, uid, ids, context=context):
591             name = record.name
592             if record.parent_id and not record.is_company:
593                 name =  "%s, %s" % (record.parent_id.name, name)
594             if context.get('show_address_only'):
595                 name = self._display_address(cr, uid, record, without_company=True, context=context)
596             if context.get('show_address'):
597                 name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
598             name = name.replace('\n\n','\n')
599             name = name.replace('\n\n','\n')
600             if context.get('show_email') and record.email:
601                 name = "%s <%s>" % (name, record.email)
602             res.append((record.id, name))
603         return res
604
605     def _parse_partner_name(self, text, context=None):
606         """ Supported syntax:
607             - 'Raoul <raoul@grosbedon.fr>': will find name and email address
608             - otherwise: default, everything is set as the name """
609         emails = tools.email_split(text.replace(' ',','))
610         if emails:
611             email = emails[0]
612             name = text[:text.index(email)].replace('"', '').replace('<', '').strip()
613         else:
614             name, email = text, ''
615         return name, email
616
617     def name_create(self, cr, uid, name, context=None):
618         """ Override of orm's name_create method for partners. The purpose is
619             to handle some basic formats to create partners using the
620             name_create.
621             If only an email address is received and that the regex cannot find
622             a name, the name will have the email value.
623             If 'force_email' key in context: must find the email address. """
624         if context is None:
625             context = {}
626         name, email = self._parse_partner_name(name, context=context)
627         if context.get('force_email') and not email:
628             raise osv.except_osv(_('Warning'), _("Couldn't create contact without email address!"))
629         if not name and email:
630             name = email
631         rec_id = self.create(cr, uid, {self._rec_name: name or email, 'email': email or False}, context=context)
632         return self.name_get(cr, uid, [rec_id], context)[0]
633
634     def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
635         """ Override search() to always show inactive children when searching via ``child_of`` operator. The ORM will
636         always call search() with a simple domain of the form [('parent_id', 'in', [ids])]. """
637         # a special ``domain`` is set on the ``child_ids`` o2m to bypass this logic, as it uses similar domain expressions
638         if len(args) == 1 and len(args[0]) == 3 and args[0][:2] == ('parent_id','in') \
639                 and args[0][2] != [False]:
640             context = dict(context or {}, active_test=False)
641         return super(res_partner, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context,
642                                                 count=count, access_rights_uid=access_rights_uid)
643
644     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
645         if not args:
646             args = []
647         if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'):
648
649             self.check_access_rights(cr, uid, 'read')
650             where_query = self._where_calc(cr, uid, args, context=context)
651             self._apply_ir_rules(cr, uid, where_query, 'read', context=context)
652             from_clause, where_clause, where_clause_params = where_query.get_sql()
653             where_str = where_clause and (" WHERE %s AND " % where_clause) or ' WHERE '
654
655             # search on the name of the contacts and of its company
656             search_name = name
657             if operator in ('ilike', 'like'):
658                 search_name = '%%%s%%' % name
659             if operator in ('=ilike', '=like'):
660                 operator = operator[1:]
661
662             unaccent = get_unaccent_wrapper(cr)
663
664             query = """SELECT id
665                          FROM res_partner
666                       {where} ({email} {operator} {percent}
667                            OR {display_name} {operator} {percent})
668                      ORDER BY {display_name}
669                     """.format(where=where_str, operator=operator,
670                                email=unaccent('email'),
671                                display_name=unaccent('display_name'),
672                                percent=unaccent('%s'))
673
674             where_clause_params += [search_name, search_name]
675             if limit:
676                 query += ' limit %s'
677                 where_clause_params.append(limit)
678             cr.execute(query, where_clause_params)
679             ids = map(lambda x: x[0], cr.fetchall())
680
681             if ids:
682                 return self.name_get(cr, uid, ids, context)
683             else:
684                 return []
685         return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
686
687     def find_or_create(self, cr, uid, email, context=None):
688         """ Find a partner with the given ``email`` or use :py:method:`~.name_create`
689             to create one
690
691             :param str email: email-like string, which should contain at least one email,
692                 e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``"""
693         assert email, 'an email is required for find_or_create to work'
694         emails = tools.email_split(email)
695         if emails:
696             email = emails[0]
697         ids = self.search(cr, uid, [('email','ilike',email)], context=context)
698         if not ids:
699             return self.name_create(cr, uid, email, context=context)[0]
700         return ids[0]
701
702     def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
703         partners = self.browse(cr, uid, ids)
704         for partner in partners:
705             if partner.email:
706                 tools.email_send(email_from, [partner.email], subject, body, on_error)
707         return True
708
709     def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
710         while len(ids):
711             self.pool['ir.cron'].create(cr, uid, {
712                 'name': 'Send Partner Emails',
713                 'user_id': uid,
714                 'model': 'res.partner',
715                 'function': '_email_send',
716                 'args': repr([ids[:16], email_from, subject, body, on_error])
717             })
718             ids = ids[16:]
719         return True
720
721     def address_get(self, cr, uid, ids, adr_pref=None, context=None):
722         """ Find contacts/addresses of the right type(s) by doing a depth-first-search
723         through descendants within company boundaries (stop at entities flagged ``is_company``)
724         then continuing the search at the ancestors that are within the same company boundaries.
725         Defaults to partners of type ``'default'`` when the exact type is not found, or to the
726         provided partner itself if no type ``'default'`` is found either. """
727         adr_pref = set(adr_pref or [])
728         if 'default' not in adr_pref:
729             adr_pref.add('default')
730         result = {}
731         visited = set()
732         for partner in self.browse(cr, uid, filter(None, ids), context=context):
733             current_partner = partner
734             while current_partner:
735                 to_scan = [current_partner]
736                 # Scan descendants, DFS
737                 while to_scan:
738                     record = to_scan.pop(0)
739                     visited.add(record)
740                     if record.type in adr_pref and not result.get(record.type):
741                         result[record.type] = record.id
742                     if len(result) == len(adr_pref):
743                         return result
744                     to_scan = [c for c in record.child_ids
745                                  if c not in visited
746                                  if not c.is_company] + to_scan
747
748                 # Continue scanning at ancestor if current_partner is not a commercial entity
749                 if current_partner.is_company or not current_partner.parent_id:
750                     break
751                 current_partner = current_partner.parent_id
752
753         # default to type 'default' or the partner itself
754         default = result.get('default', partner.id)
755         for adr_type in adr_pref:
756             result[adr_type] = result.get(adr_type) or default 
757         return result
758
759     def view_header_get(self, cr, uid, view_id, view_type, context):
760         res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
761         if res: return res
762         if not context.get('category_id', False):
763             return False
764         return _('Partners: ')+self.pool['res.partner.category'].browse(cr, uid, context['category_id'], context).name
765
766     def main_partner(self, cr, uid):
767         ''' Return the id of the main partner
768         '''
769         model_data = self.pool['ir.model.data']
770         return model_data.browse(cr, uid,
771                             model_data.search(cr, uid, [('module','=','base'),
772                                                 ('name','=','main_partner')])[0],
773                 ).res_id
774
775     def _display_address(self, cr, uid, address, without_company=False, context=None):
776
777         '''
778         The purpose of this function is to build and return an address formatted accordingly to the
779         standards of the country where it belongs.
780
781         :param address: browse record of the res.partner to format
782         :returns: the address formatted in a display that fit its country habits (or the default ones
783             if not country is specified)
784         :rtype: string
785         '''
786
787         # get the information that will be injected into the display format
788         # get the address format
789         address_format = address.country_id and address.country_id.address_format or \
790               "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
791         args = {
792             'state_code': address.state_id and address.state_id.code or '',
793             'state_name': address.state_id and address.state_id.name or '',
794             'country_code': address.country_id and address.country_id.code or '',
795             'country_name': address.country_id and address.country_id.name or '',
796             'company_name': address.parent_id and address.parent_id.name or '',
797         }
798         for field in self._address_fields(cr, uid, context=context):
799             args[field] = getattr(address, field) or ''
800         if without_company:
801             args['company_name'] = ''
802         elif address.parent_id:
803             address_format = '%(company_name)s\n' + address_format
804         return address_format % args
805
806 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: