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