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