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