1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
23 from lxml import etree
29 from openerp import SUPERUSER_ID
30 from openerp import pooler, tools
31 from openerp.osv import osv, fields
32 from openerp.tools.translate import _
33 from openerp.tools.yaml_import import is_comment
35 class format_address(object):
36 def fields_view_get_address(self, cr, uid, arch, context={}):
37 user_obj = self.pool.get('res.users')
38 fmt = user_obj.browse(cr, SUPERUSER_ID, uid, context).company_id.country_id
39 fmt = fmt and fmt.address_format
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}'/>
46 <field name="zip" placeholder="ZIP"/>
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%%"/>
54 <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
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"/>
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)
76 def _tz_get(self,cr,uid, context=None):
77 # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728
78 return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]
80 class res_partner_category(osv.osv):
82 def name_get(self, cr, uid, ids, context=None):
83 """Return the categories' display name, including their direct
86 :param dict context: the ``partner_category_display`` key can be
87 used to select the short version of the
88 category name (without the direct parent),
89 when set to ``'short'``. The default is
93 if context.get('partner_category_display') == 'short':
94 return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
95 if isinstance(ids, (int, long)):
97 reads = self.read(cr, uid, ids, ['name', 'parent_id'], context=context)
100 name = record['name']
101 if record['parent_id']:
102 name = record['parent_id'][1] + ' / ' + name
103 res.append((record['id'], name))
106 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
112 # Be sure name_search is symetric to name_get
113 name = name.split(' / ')[-1]
114 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
116 ids = self.search(cr, uid, args, limit=limit, context=context)
117 return self.name_get(cr, uid, ids, context)
120 def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
121 res = self.name_get(cr, uid, ids, context=context)
124 _description = 'Partner Categories'
125 _name = 'res.partner.category'
127 'name': fields.char('Category Name', required=True, size=64, translate=True),
128 'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
129 'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
130 'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
131 'active': fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
132 'parent_left': fields.integer('Left parent', select=True),
133 'parent_right': fields.integer('Right parent', select=True),
134 'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'),
137 (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
143 _parent_order = 'name'
144 _order = 'parent_left'
146 class res_partner_title(osv.osv):
147 _name = 'res.partner.title'
150 'name': fields.char('Title', required=True, size=46, translate=True),
151 'shortcut': fields.char('Abbreviation', size=16, translate=True),
152 'domain': fields.selection([('partner', 'Partner'), ('contact', 'Contact')], 'Domain', required=True, size=24)
158 def _lang_get(self, cr, uid, context=None):
159 lang_pool = self.pool.get('res.lang')
160 ids = lang_pool.search(cr, uid, [], context=context)
161 res = lang_pool.read(cr, uid, ids, ['code', 'name'], context)
162 return [(r['code'], r['name']) for r in res]
164 # fields copy if 'use_parent_address' is checked
165 ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
166 POSTAL_ADDRESS_FIELDS = ADDRESS_FIELDS # deprecated, to remove after 7.0
168 class res_partner(osv.osv, format_address):
169 _description = 'Partner'
170 _name = "res.partner"
172 def _address_display(self, cr, uid, ids, name, args, context=None):
174 for partner in self.browse(cr, uid, ids, context=context):
175 res[partner.id] = self._display_address(cr, uid, partner, context=context)
178 def _get_image(self, cr, uid, ids, name, args, context=None):
179 result = dict.fromkeys(ids, False)
180 for obj in self.browse(cr, uid, ids, context=context):
181 result[obj.id] = tools.image_get_resized_images(obj.image)
184 def _get_tz_offset(self, cr, uid, ids, name, args, context=None):
185 result = dict.fromkeys(ids, False)
186 for obj in self.browse(cr, uid, ids, context=context):
187 result[obj.id] = datetime.datetime.now(pytz.timezone(obj.tz or 'GMT')).strftime('%z')
190 def _set_image(self, cr, uid, id, name, value, args, context=None):
191 return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
193 def _has_image(self, cr, uid, ids, name, args, context=None):
195 for obj in self.browse(cr, uid, ids, context=context):
196 result[obj.id] = obj.image != False
199 def _commercial_partner_compute(self, cr, uid, ids, name, args, context=None):
200 """ Returns the partner that is considered the commercial
201 entity of this partner. The commercial entity holds the master data
202 for all commercial fields (see :py:meth:`~_commercial_fields`) """
203 result = dict.fromkeys(ids, False)
204 for partner in self.browse(cr, uid, ids, context=context):
205 current_partner = partner
206 while not current_partner.is_company and current_partner.parent_id:
207 current_partner = current_partner.parent_id
208 result[partner.id] = current_partner.id
211 # indirection to avoid passing a copy of the overridable method when declaring the function field
212 _commercial_partner_id = lambda self, *args, **kwargs: self._commercial_partner_compute(*args, **kwargs)
216 'name': fields.char('Name', size=128, required=True, select=True),
217 'date': fields.date('Date', select=1),
218 'title': fields.many2one('res.partner.title', 'Title'),
219 'parent_id': fields.many2one('res.partner', 'Related Company'),
220 'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts', domain=[('active','=',True)]), # force "active_test" domain to bypass _search() override
221 'ref': fields.char('Reference', size=64, select=1),
222 'lang': fields.selection(_lang_get, 'Language',
223 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."),
224 'tz': fields.selection(_tz_get, 'Timezone', size=64,
225 help="The partner's timezone, used to output proper date and time values inside printed reports. "
226 "It is important to set a value for this field. You should use the same timezone "
227 "that is otherwise used to pick and render date and time values: your computer's timezone."),
228 'tz_offset': fields.function(_get_tz_offset, type='char', size=5, string='Timezone offset', invisible=True),
229 'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this contact if any.'),
230 '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."),
231 'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
232 'website': fields.char('Website', size=64, help="Website of Partner or Company"),
233 'comment': fields.text('Notes'),
234 'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
235 'credit_limit': fields.float(string='Credit Limit'),
236 'ean13': fields.char('EAN13', size=13),
237 'active': fields.boolean('Active'),
238 'customer': fields.boolean('Customer', help="Check this box if this contact is a customer."),
239 '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."),
240 'employee': fields.boolean('Employee', help="Check this box if this contact is an Employee."),
241 'function': fields.char('Job Position', size=128),
242 'type': fields.selection([('default', 'Default'), ('invoice', 'Invoice'),
243 ('delivery', 'Shipping'), ('contact', 'Contact'),
244 ('other', 'Other')], 'Address Type',
245 help="Used to select automatically the right address according to the context in sales and purchases documents."),
246 'street': fields.char('Street', size=128),
247 'street2': fields.char('Street2', size=128),
248 'zip': fields.char('Zip', change_default=True, size=24),
249 'city': fields.char('City', size=128),
250 'state_id': fields.many2one("res.country.state", 'State'),
251 'country_id': fields.many2one('res.country', 'Country'),
252 'country': fields.related('country_id', type='many2one', relation='res.country', string='Country',
253 deprecated="This field will be removed as of OpenERP 7.1, use country_id instead"),
254 'email': fields.char('Email', size=240),
255 'phone': fields.char('Phone', size=64),
256 'fax': fields.char('Fax', size=64),
257 'mobile': fields.char('Mobile', size=64),
258 'birthdate': fields.char('Birthdate', size=64),
259 'is_company': fields.boolean('Is a Company', help="Check if the contact is a company, otherwise it is a person"),
260 'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information for this contact"),
261 # image: all image fields are base64 encoded and PIL-supported
262 'image': fields.binary("Image",
263 help="This field holds the image used as avatar for this contact, limited to 1024x1024px"),
264 'image_medium': fields.function(_get_image, fnct_inv=_set_image,
265 string="Medium-sized image", type="binary", multi="_get_image",
267 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
269 help="Medium-sized image of this contact. It is automatically "\
270 "resized as a 128x128px image, with aspect ratio preserved. "\
271 "Use this field in form views or some kanban views."),
272 'image_small': fields.function(_get_image, fnct_inv=_set_image,
273 string="Small-sized image", type="binary", multi="_get_image",
275 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
277 help="Small-sized image of this contact. It is automatically "\
278 "resized as a 64x64px image, with aspect ratio preserved. "\
279 "Use this field anywhere a small image is required."),
280 'has_image': fields.function(_has_image, type="boolean"),
281 'company_id': fields.many2one('res.company', 'Company', select=1),
282 'color': fields.integer('Color Index'),
283 'user_ids': fields.one2many('res.users', 'partner_id', 'Users'),
284 'contact_address': fields.function(_address_display, type='char', string='Complete Address'),
286 # technical field used for managing commercial fields
287 'commercial_partner_id': fields.function(_commercial_partner_id, type='many2one', relation='res.partner', string='Commercial Entity')
290 def _default_category(self, cr, uid, context=None):
293 if context.get('category_id'):
294 return [context['category_id']]
297 def _get_default_image(self, cr, uid, is_company, context=None, colorize=False):
298 img_path = openerp.modules.get_module_resource('base', 'static/src/img',
299 ('company_image.png' if is_company else 'avatar.png'))
300 with open(img_path, 'rb') as f:
303 # colorize user avatars
305 image = tools.image_colorize(image)
307 return tools.image_resize_image_big(image.encode('base64'))
309 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
310 if (not view_id) and (view_type=='form') and context and context.get('force_email', False):
311 view_id = self.pool.get('ir.model.data').get_object_reference(cr, user, 'base', 'view_partner_simple_form')[1]
312 res = super(res_partner,self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
313 if view_type == 'form':
314 res['arch'] = self.fields_view_get_address(cr, user, res['arch'], context=context)
319 'lang': lambda self, cr, uid, ctx: ctx.get('lang', 'en_US'),
320 'tz': lambda self, cr, uid, ctx: ctx.get('tz', False),
322 'category_id': _default_category,
323 'company_id': lambda self, cr, uid, ctx: self.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=ctx),
326 'type': 'contact', # type 'default' is wildcard and thus inappropriate
327 'use_parent_address': False,
332 (osv.osv._check_recursion, 'You cannot create recursive Partner hierarchies.', ['parent_id']),
335 def copy(self, cr, uid, id, default=None, context=None):
338 name = self.read(cr, uid, [id], ['name'], context)[0]['name']
339 default.update({'name': _('%s (copy)') % name})
340 return super(res_partner, self).copy(cr, uid, id, default, context)
342 def onchange_type(self, cr, uid, ids, is_company, context=None):
344 value['title'] = False
346 domain = {'title': [('domain', '=', 'partner')]}
348 domain = {'title': [('domain', '=', 'contact')]}
349 return {'value': value, 'domain': domain}
351 def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
352 def value_or_id(val):
353 """ return val or val.id if val is a browse record """
354 return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
358 partner = self.browse(cr, uid, ids[0], context=context)
359 if partner.parent_id and partner.parent_id.id != parent_id:
360 result['warning'] = {'title': _('Warning'),
361 'message': _('Changing the company of a contact should only be done if it '
362 'was never correctly set. If an existing contact starts working for a new '
363 'company then a new contact should be created under that new '
364 'company. You can use the "Discard" button to abandon this change.')}
365 parent = self.browse(cr, uid, parent_id, context=context)
366 address_fields = self._address_fields(cr, uid, context=context)
367 result['value'] = dict((key, value_or_id(parent[key])) for key in address_fields)
369 result['value'] = {'use_parent_address': False}
372 def onchange_state(self, cr, uid, ids, state_id, context=None):
374 country_id = self.pool.get('res.country.state').browse(cr, uid, state_id, context).country_id.id
375 return {'value':{'country_id':country_id}}
378 def _check_ean_key(self, cr, uid, ids, context=None):
379 for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
380 thisean=partner_o['ean13']
381 if thisean and thisean!='':
389 sum+=3*int(thisean[i])
390 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
394 # _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
396 def _update_fields_values(self, cr, uid, partner, fields, context=None):
397 """ Returns dict of write() values for synchronizing ``fields`` """
400 column = self._all_columns[field].column
401 if column._type == 'one2many':
402 raise AssertionError('One2Many fields cannot be synchronized as part of `commercial_fields` or `address fields`')
403 if column._type == 'many2one':
404 values[field] = partner[field].id if partner[field] else False
405 elif column._type == 'many2many':
406 values[field] = [(6,0,[r.id for r in partner[field] or []])]
408 values[field] = partner[field]
411 def _address_fields(self, cr, uid, context=None):
412 """ Returns the list of address fields that are synced from the parent
413 when the `use_parent_address` flag is set. """
414 return list(ADDRESS_FIELDS)
416 def update_address(self, cr, uid, ids, vals, context=None):
417 address_fields = self._address_fields(cr, uid, context=context)
418 addr_vals = dict((key, vals[key]) for key in address_fields if key in vals)
420 return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
422 def _commercial_fields(self, cr, uid, context=None):
423 """ Returns the list of fields that are managed by the commercial entity
424 to which a partner belongs. These fields are meant to be hidden on
425 partners that aren't `commercial entities` themselves, and will be
426 delegated to the parent `commercial entity`. The list is meant to be
427 extended by inheriting classes. """
430 def _commercial_sync_from_company(self, cr, uid, partner, context=None):
431 """ Handle sync of commercial fields when a new parent commercial entity is set,
432 as if they were related fields """
433 if partner.commercial_partner_id != partner:
434 commercial_fields = self._commercial_fields(cr, uid, context=context)
435 sync_vals = self._update_fields_values(cr, uid, partner.commercial_partner_id,
436 commercial_fields, context=context)
437 partner.write(sync_vals)
439 def _commercial_sync_to_children(self, cr, uid, partner, context=None):
440 """ Handle sync of commercial fields to descendants """
441 commercial_fields = self._commercial_fields(cr, uid, context=context)
442 sync_vals = self._update_fields_values(cr, uid, partner.commercial_partner_id,
443 commercial_fields, context=context)
444 sync_children = [c for c in partner.child_ids if not c.is_company]
445 for child in sync_children:
446 self._commercial_sync_to_children(cr, uid, child, context=context)
447 return self.write(cr, uid, [c.id for c in sync_children], sync_vals, context=context)
449 def _fields_sync(self, cr, uid, partner, update_values, context=None):
450 """ Sync commercial fields and address fields from company and to children after create/update,
451 just as if those were all modeled as fields.related to the parent """
452 # 1. From UPSTREAM: sync from parent
453 if update_values.get('parent_id') or update_values.get('use_parent_address'):
454 # 1a. Commercial fields: sync if parent changed
455 if update_values.get('parent_id'):
456 self._commercial_sync_from_company(cr, uid, partner, context=context)
457 # 1b. Address fields: sync if parent or use_parent changed *and* both are now set
458 if partner.parent_id and partner.use_parent_address:
459 onchange_vals = self.onchange_address(cr, uid, [partner.id],
460 use_parent_address=partner.use_parent_address,
461 parent_id=partner.parent_id.id,
462 context=context).get('value', {})
463 partner.update_address(onchange_vals)
465 # 2. To DOWNSTREAM: sync children
466 if partner.child_ids:
467 # 2a. Commercial Fields: sync if commercial entity
468 if partner.commercial_partner_id == partner and any(
469 field in update_values
470 for field in self._commercial_fields(
471 cr, uid, context=context)):
472 self._commercial_sync_to_children(cr, uid, partner, context=context)
473 # 2b. Address fields: sync if address changed
474 address_fields = self._address_fields(cr, uid, context=context)
475 if any(field in update_values for field in address_fields):
476 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
477 update_ids = self.search(cr, uid, domain_children, context=context)
478 self.update_address(cr, uid, update_ids, update_values, context=context)
480 def _handle_first_contact_creation(self, cr, uid, partner, context=None):
481 """ On creation of first contact for a company (or root) that has no address, assume contact address
482 was meant to be company address """
483 parent = partner.parent_id
484 address_fields = self._address_fields(cr, uid, context=context)
485 if parent and (parent.is_company or not parent.parent_id) and len(parent.child_ids) == 1 and \
486 any(partner[f] for f in address_fields) and not any(parent[f] for f in address_fields):
487 addr_vals = self._update_fields_values(cr, uid, partner, address_fields, context=context)
488 parent.update_address(addr_vals)
489 if not parent.is_company:
490 parent.write({'is_company': True})
492 def write(self, cr, uid, ids, vals, context=None):
493 if isinstance(ids, (int, long)):
495 result = super(res_partner,self).write(cr, uid, ids, vals, context=context)
496 for partner in self.browse(cr, uid, ids, context=context):
497 self._fields_sync(cr, uid, partner, vals, context)
500 def create(self, cr, uid, vals, context=None):
501 new_id = super(res_partner, self).create(cr, uid, vals, context=context)
502 partner = self.browse(cr, uid, new_id, context=context)
503 self._fields_sync(cr, uid, partner, vals, context)
504 self._handle_first_contact_creation(cr, uid, partner, context)
507 def open_commercial_entity(self, cr, uid, ids, context=None):
508 """ Utility method used to add an "Open Company" button in partner views """
509 partner = self.browse(cr, uid, ids[0], context=context)
510 return {'type': 'ir.actions.act_window',
511 'res_model': 'res.partner',
513 'res_id': partner.commercial_partner_id.id,
515 'flags': {'form': {'action_buttons': True}}}
517 def open_parent(self, cr, uid, ids, context=None):
518 """ Utility method used to add an "Open Parent" button in partner views """
519 partner = self.browse(cr, uid, ids[0], context=context)
520 return {'type': 'ir.actions.act_window',
521 'res_model': 'res.partner',
523 'res_id': partner.parent_id.id,
525 'flags': {'form': {'action_buttons': True}}}
527 def name_get(self, cr, uid, ids, context=None):
530 if isinstance(ids, (int, long)):
533 for record in self.browse(cr, uid, ids, context=context):
535 if record.parent_id and not record.is_company:
536 name = "%s, %s" % (record.parent_id.name, name)
537 if context.get('show_address'):
538 name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
539 name = name.replace('\n\n','\n')
540 name = name.replace('\n\n','\n')
541 if context.get('show_email') and record.email:
542 name = "%s <%s>" % (name, record.email)
543 res.append((record.id, name))
546 def _parse_partner_name(self, text, context=None):
547 """ Supported syntax:
548 - 'Raoul <raoul@grosbedon.fr>': will find name and email address
549 - otherwise: default, everything is set as the name """
550 emails = tools.email_split(text)
553 name = text[:text.index(email)].replace('"', '').replace('<', '').strip()
555 name, email = text, ''
558 def name_create(self, cr, uid, name, context=None):
559 """ Override of orm's name_create method for partners. The purpose is
560 to handle some basic formats to create partners using the
562 If only an email address is received and that the regex cannot find
563 a name, the name will have the email value.
564 If 'force_email' key in context: must find the email address. """
567 name, email = self._parse_partner_name(name, context=context)
568 if context.get('force_email') and not email:
569 raise osv.except_osv(_('Warning'), _("Couldn't create contact without email address!"))
570 if not name and email:
572 rec_id = self.create(cr, uid, {self._rec_name: name or email, 'email': email or False}, context=context)
573 return self.name_get(cr, uid, [rec_id], context)[0]
575 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
576 """ Override search() to always show inactive children when searching via ``child_of`` operator. The ORM will
577 always call search() with a simple domain of the form [('parent_id', 'in', [ids])]. """
578 # a special ``domain`` is set on the ``child_ids`` o2m to bypass this logic, as it uses similar domain expressions
579 if len(args) == 1 and len(args[0]) == 3 and args[0][:2] == ('parent_id','in'):
580 context = dict(context or {}, active_test=False)
581 return super(res_partner, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context,
582 count=count, access_rights_uid=access_rights_uid)
584 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
587 if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'):
588 # search on the name of the contacts and of its company
590 if operator in ('ilike', 'like'):
591 search_name = '%%%s%%' % name
592 if operator in ('=ilike', '=like'):
593 operator = operator[1:]
594 query_args = {'name': search_name}
597 limit_str = ' limit %(limit)s'
598 query_args['limit'] = limit
599 # TODO: simplify this in trunk with _rec_name='display_name', once display_name
600 # becomes a stored field
601 cr.execute('''SELECT partner.id FROM res_partner partner
602 LEFT JOIN res_partner company ON partner.parent_id = company.id
603 WHERE partner.email ''' + operator +''' %(name)s OR
604 CASE WHEN company.id IS NULL OR partner.is_company
607 company.name || ', ' || partner.name
609 ''' + operator + ' %(name)s ' + limit_str, query_args)
610 ids = map(lambda x: x[0], cr.fetchall())
611 ids = self.search(cr, uid, [('id', 'in', ids)] + args, limit=limit, context=context)
613 return self.name_get(cr, uid, ids, context)
614 return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
616 def find_or_create(self, cr, uid, email, context=None):
617 """ Find a partner with the given ``email`` or use :py:method:`~.name_create`
620 :param str email: email-like string, which should contain at least one email,
621 e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``"""
622 assert email, 'an email is required for find_or_create to work'
623 emails = tools.email_split(email)
626 ids = self.search(cr, uid, [('email','ilike',email)], context=context)
628 return self.name_create(cr, uid, email, context=context)[0]
631 def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
632 partners = self.browse(cr, uid, ids)
633 for partner in partners:
635 tools.email_send(email_from, [partner.email], subject, body, on_error)
638 def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
640 self.pool.get('ir.cron').create(cr, uid, {
641 'name': 'Send Partner Emails',
643 'model': 'res.partner',
644 'function': '_email_send',
645 'args': repr([ids[:16], email_from, subject, body, on_error])
650 def address_get(self, cr, uid, ids, adr_pref=None, context=None):
651 """ Find contacts/addresses of the right type(s) by doing a depth-first-search
652 through descendants within company boundaries (stop at entities flagged ``is_company``)
653 then continuing the search at the ancestors that are within the same company boundaries.
654 Defaults to partners of type ``'default'`` when the exact type is not found, or to the
655 provided partner itself if no type ``'default'`` is found either. """
656 adr_pref = set(adr_pref or [])
657 if 'default' not in adr_pref:
658 adr_pref.add('default')
661 for partner in self.browse(cr, uid, filter(None, ids), context=context):
662 current_partner = partner
663 while current_partner:
664 to_scan = [current_partner]
665 # Scan descendants, DFS
667 record = to_scan.pop(0)
669 if record.type in adr_pref and not result.get(record.type):
670 result[record.type] = record.id
671 if len(result) == len(adr_pref):
673 to_scan = [c for c in record.child_ids
675 if not c.is_company] + to_scan
677 # Continue scanning at ancestor if current_partner is not a commercial entity
678 if current_partner.is_company or not current_partner.parent_id:
680 current_partner = current_partner.parent_id
682 # default to type 'default' or the partner itself
683 default = result.get('default', partner.id)
684 for adr_type in adr_pref:
685 result[adr_type] = result.get(adr_type) or default
688 def view_header_get(self, cr, uid, view_id, view_type, context):
689 res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
691 if not context.get('category_id', False):
693 return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
695 def main_partner(self, cr, uid):
696 ''' Return the id of the main partner
698 model_data = self.pool.get('ir.model.data')
699 return model_data.browse(cr, uid,
700 model_data.search(cr, uid, [('module','=','base'),
701 ('name','=','main_partner')])[0],
704 def _display_address(self, cr, uid, address, without_company=False, context=None):
707 The purpose of this function is to build and return an address formatted accordingly to the
708 standards of the country where it belongs.
710 :param address: browse record of the res.partner to format
711 :returns: the address formatted in a display that fit its country habits (or the default ones
712 if not country is specified)
716 # get the information that will be injected into the display format
717 # get the address format
718 address_format = address.country_id and address.country_id.address_format or \
719 "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
721 'state_code': address.state_id and address.state_id.code or '',
722 'state_name': address.state_id and address.state_id.name or '',
723 'country_code': address.country_id and address.country_id.code or '',
724 'country_name': address.country_id and address.country_id.name or '',
725 'company_name': address.parent_id and address.parent_id.name or '',
727 for field in self._address_fields(cr, uid, context=context):
728 args[field] = getattr(address, field) or ''
730 args['company_name'] = ''
731 elif address.parent_id:
732 address_format = '%(company_name)s\n' + address_format
733 return address_format % args
735 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: