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
28 from openerp import SUPERUSER_ID
29 from openerp import tools
30 from openerp.osv import osv, fields
31 from openerp.tools.translate import _
33 class format_address(object):
34 def fields_view_get_address(self, cr, uid, arch, context={}):
35 user_obj = self.pool['res.users']
36 fmt = user_obj.browse(cr, SUPERUSER_ID, uid, context).company_id.country_id
37 fmt = fmt and fmt.address_format
39 '%(city)s %(state_code)s\n%(zip)s': """
40 <div class="address_format">
41 <field name="city" placeholder="City" style="width: 50%%"/>
42 <field name="state_id" class="oe_no_button" placeholder="State" style="width: 47%%" options='{"no_open": true}'/>
44 <field name="zip" placeholder="ZIP"/>
47 '%(zip)s %(city)s': """
48 <div class="address_format">
49 <field name="zip" placeholder="ZIP" style="width: 40%%"/>
50 <field name="city" placeholder="City" style="width: 57%%"/>
52 <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
55 '%(city)s\n%(state_name)s\n%(zip)s': """
56 <div class="address_format">
57 <field name="city" placeholder="City"/>
58 <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
59 <field name="zip" placeholder="ZIP"/>
63 for k,v in layouts.items():
64 if fmt and (k in fmt):
65 doc = etree.fromstring(arch)
66 for node in doc.xpath("//div[@class='address_format']"):
67 tree = etree.fromstring(v)
68 node.getparent().replace(node, tree)
69 arch = etree.tostring(doc)
74 def _tz_get(self,cr,uid, context=None):
75 # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728
76 return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]
78 class res_partner_category(osv.osv):
80 def name_get(self, cr, uid, ids, context=None):
81 """Return the categories' display name, including their direct
84 :param dict context: the ``partner_category_display`` key can be
85 used to select the short version of the
86 category name (without the direct parent),
87 when set to ``'short'``. The default is
91 if context.get('partner_category_display') == 'short':
92 return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
93 if isinstance(ids, (int, long)):
95 reads = self.read(cr, uid, ids, ['name', 'parent_id'], context=context)
99 if record['parent_id']:
100 name = record['parent_id'][1] + ' / ' + name
101 res.append((record['id'], name))
104 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
110 # Be sure name_search is symetric to name_get
111 name = name.split(' / ')[-1]
112 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
114 ids = self.search(cr, uid, args, limit=limit, context=context)
115 return self.name_get(cr, uid, ids, context)
118 def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
119 res = self.name_get(cr, uid, ids, context=context)
122 _description = 'Partner Tags'
123 _name = 'res.partner.category'
125 'name': fields.char('Category Name', required=True, size=64, translate=True),
126 'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
127 'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
128 'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
129 'active': fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
130 'parent_left': fields.integer('Left parent', select=True),
131 'parent_right': fields.integer('Right parent', select=True),
132 'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'),
135 (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
141 _parent_order = 'name'
142 _order = 'parent_left'
144 class res_partner_title(osv.osv):
145 _name = 'res.partner.title'
148 'name': fields.char('Title', required=True, size=46, translate=True),
149 'shortcut': fields.char('Abbreviation', size=16, translate=True),
150 'domain': fields.selection([('partner', 'Partner'), ('contact', 'Contact')], 'Domain', required=True, size=24)
156 def _lang_get(self, cr, uid, context=None):
157 lang_pool = self.pool['res.lang']
158 ids = lang_pool.search(cr, uid, [], context=context)
159 res = lang_pool.read(cr, uid, ids, ['code', 'name'], context)
160 return [(r['code'], r['name']) for r in res]
162 # fields copy if 'use_parent_address' is checked
163 ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
165 class res_partner(osv.osv, format_address):
166 _description = 'Partner'
167 _name = "res.partner"
169 def _address_display(self, cr, uid, ids, name, args, context=None):
171 for partner in self.browse(cr, uid, ids, context=context):
172 res[partner.id] = self._display_address(cr, uid, partner, context=context)
175 def _get_image(self, cr, uid, ids, name, args, context=None):
176 result = dict.fromkeys(ids, False)
177 for obj in self.browse(cr, uid, ids, context=context):
178 result[obj.id] = tools.image_get_resized_images(obj.image)
181 def _get_tz_offset(self, cr, uid, ids, name, args, context=None):
182 result = dict.fromkeys(ids, False)
183 for obj in self.browse(cr, uid, ids, context=context):
184 result[obj.id] = datetime.datetime.now(pytz.timezone(obj.tz or 'GMT')).strftime('%z')
187 def _set_image(self, cr, uid, id, name, value, args, context=None):
188 return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
190 def _has_image(self, cr, uid, ids, name, args, context=None):
192 for obj in self.browse(cr, uid, ids, context=context):
193 result[obj.id] = obj.image != False
196 def _commercial_partner_compute(self, cr, uid, ids, name, args, context=None):
197 """ Returns the partner that is considered the commercial
198 entity of this partner. The commercial entity holds the master data
199 for all commercial fields (see :py:meth:`~_commercial_fields`) """
200 result = dict.fromkeys(ids, False)
201 for partner in self.browse(cr, uid, ids, context=context):
202 current_partner = partner
203 while not current_partner.is_company and current_partner.parent_id:
204 current_partner = current_partner.parent_id
205 result[partner.id] = current_partner.id
208 def _display_name_compute(self, cr, uid, ids, name, args, context=None):
209 context = dict(context or {})
210 context.pop('show_address', None)
211 context.pop('show_address_only', None)
212 context.pop('show_email', None)
213 return dict(self.name_get(cr, uid, ids, context=context))
215 # indirections to avoid passing a copy of the overridable method when declaring the function field
216 _commercial_partner_id = lambda self, *args, **kwargs: self._commercial_partner_compute(*args, **kwargs)
217 _display_name = lambda self, *args, **kwargs: self._display_name_compute(*args, **kwargs)
219 _commercial_partner_store_triggers = {
220 'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
221 ['parent_id', 'is_company'], 10)
223 _display_name_store_triggers = {
224 'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
225 ['parent_id', 'is_company', 'name'], 10)
228 _order = "display_name"
230 'name': fields.char('Name', size=128, required=True, select=True),
231 'display_name': fields.function(_display_name, type='char', string='Name', store=_display_name_store_triggers),
232 'date': fields.date('Date', select=1),
233 'title': fields.many2one('res.partner.title', 'Title'),
234 'parent_id': fields.many2one('res.partner', 'Related Company'),
235 'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts', domain=[('active','=',True)]), # force "active_test" domain to bypass _search() override
236 'ref': fields.char('Reference', size=64, select=1),
237 'lang': fields.selection(_lang_get, 'Language',
238 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."),
239 'tz': fields.selection(_tz_get, 'Timezone', size=64,
240 help="The partner's timezone, used to output proper date and time values inside printed reports. "
241 "It is important to set a value for this field. You should use the same timezone "
242 "that is otherwise used to pick and render date and time values: your computer's timezone."),
243 'tz_offset': fields.function(_get_tz_offset, type='char', size=5, string='Timezone offset', invisible=True),
244 'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this contact if any.'),
245 '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."),
246 'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
247 'website': fields.char('Website', size=64, help="Website of Partner or Company"),
248 'comment': fields.text('Notes'),
249 'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
250 'credit_limit': fields.float(string='Credit Limit'),
251 'ean13': fields.char('EAN13', size=13),
252 'active': fields.boolean('Active'),
253 'customer': fields.boolean('Customer', help="Check this box if this contact is a customer."),
254 '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."),
255 'employee': fields.boolean('Employee', help="Check this box if this contact is an Employee."),
256 'function': fields.char('Job Position', size=128),
257 'type': fields.selection([('default', 'Default'), ('invoice', 'Invoice'),
258 ('delivery', 'Shipping'), ('contact', 'Contact'),
259 ('other', 'Other')], 'Address Type',
260 help="Used to select automatically the right address according to the context in sales and purchases documents."),
261 'street': fields.char('Street', size=128),
262 'street2': fields.char('Street2', size=128),
263 'zip': fields.char('Zip', change_default=True, size=24),
264 'city': fields.char('City', size=128),
265 'state_id': fields.many2one("res.country.state", 'State', ondelete='restrict'),
266 'country_id': fields.many2one('res.country', 'Country', ondelete='restrict'),
267 'country': fields.related('country_id', type='many2one', relation='res.country', string='Country',
268 deprecated="This field will be removed as of OpenERP 7.1, use country_id instead"),
269 'email': fields.char('Email', size=240),
270 'phone': fields.char('Phone', size=64),
271 'fax': fields.char('Fax', size=64),
272 'mobile': fields.char('Mobile', size=64),
273 'birthdate': fields.char('Birthdate', size=64),
274 'is_company': fields.boolean('Is a Company', help="Check if the contact is a company, otherwise it is a person"),
275 'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information for this contact"),
276 # image: all image fields are base64 encoded and PIL-supported
277 'image': fields.binary("Image",
278 help="This field holds the image used as avatar for this contact, limited to 1024x1024px"),
279 'image_medium': fields.function(_get_image, fnct_inv=_set_image,
280 string="Medium-sized image", type="binary", multi="_get_image",
282 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
284 help="Medium-sized image of this contact. It is automatically "\
285 "resized as a 128x128px image, with aspect ratio preserved. "\
286 "Use this field in form views or some kanban views."),
287 'image_small': fields.function(_get_image, fnct_inv=_set_image,
288 string="Small-sized image", type="binary", multi="_get_image",
290 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
292 help="Small-sized image of this contact. It is automatically "\
293 "resized as a 64x64px image, with aspect ratio preserved. "\
294 "Use this field anywhere a small image is required."),
295 'has_image': fields.function(_has_image, type="boolean"),
296 'company_id': fields.many2one('res.company', 'Company', select=1),
297 'color': fields.integer('Color Index'),
298 'user_ids': fields.one2many('res.users', 'partner_id', 'Users'),
299 'contact_address': fields.function(_address_display, type='char', string='Complete Address'),
301 # technical field used for managing commercial fields
302 'commercial_partner_id': fields.function(_commercial_partner_id, type='many2one', relation='res.partner', string='Commercial Entity', store=_commercial_partner_store_triggers)
305 def _default_category(self, cr, uid, context=None):
308 if context.get('category_id'):
309 return [context['category_id']]
312 def _get_default_image(self, cr, uid, is_company, context=None, colorize=False):
313 img_path = openerp.modules.get_module_resource('base', 'static/src/img',
314 ('company_image.png' if is_company else 'avatar.png'))
315 with open(img_path, 'rb') as f:
318 # colorize user avatars
320 image = tools.image_colorize(image)
322 return tools.image_resize_image_big(image.encode('base64'))
324 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
325 if (not view_id) and (view_type=='form') and context and context.get('force_email', False):
326 view_id = self.pool['ir.model.data'].get_object_reference(cr, user, 'base', 'view_partner_simple_form')[1]
327 res = super(res_partner,self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
328 if view_type == 'form':
329 res['arch'] = self.fields_view_get_address(cr, user, res['arch'], context=context)
334 'lang': lambda self, cr, uid, ctx: ctx.get('lang', 'en_US'),
335 'tz': lambda self, cr, uid, ctx: ctx.get('tz', False),
337 'category_id': _default_category,
338 'company_id': lambda self, cr, uid, ctx: self.pool['res.company']._company_default_get(cr, uid, 'res.partner', context=ctx),
341 'type': 'contact', # type 'default' is wildcard and thus inappropriate
342 'use_parent_address': False,
347 (osv.osv._check_recursion, 'You cannot create recursive Partner hierarchies.', ['parent_id']),
350 def copy(self, cr, uid, id, default=None, context=None):
353 name = self.read(cr, uid, [id], ['name'], context)[0]['name']
354 default.update({'name': _('%s (copy)') % name})
355 return super(res_partner, self).copy(cr, uid, id, default, context)
357 def onchange_type(self, cr, uid, ids, is_company, context=None):
359 value['title'] = False
361 value['use_parent_address'] = False
362 domain = {'title': [('domain', '=', 'partner')]}
364 domain = {'title': [('domain', '=', 'contact')]}
365 return {'value': value, 'domain': domain}
367 def onchange_use_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
368 def value_or_id(val):
369 """ return val or val.id if val is a browse record """
370 return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
372 address_fields = self._address_fields(cr, uid, context=context)
373 if parent_id and use_parent_address:
374 parent_company = self.browse(cr, uid, parent_id, context=context)
375 result['value'] = dict((key, value_or_id(parent_company[key])) for key in address_fields)
377 result['value'] = dict((key,"") for key in address_fields)
380 def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
381 def value_or_id(val):
382 """ return val or val.id if val is a browse record """
383 return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
387 partner = self.browse(cr, uid, ids[0], context=context)
388 if partner.parent_id and partner.parent_id.id != parent_id:
389 result['warning'] = {'title': _('Warning'),
390 'message': _('Changing the company of a contact should only be done if it '
391 'was never correctly set. If an existing contact starts working for a new '
392 'company then a new contact should be created under that new '
393 'company. You can use the "Discard" button to abandon this change.')}
394 parent_company = self.browse(cr, uid, parent_id, context=context)
395 address_fields = self._address_fields(cr, uid, context=context)
396 if use_parent_address:
397 result['value'] = dict((key, value_or_id(parent_company[key])) for key in address_fields)
399 result['value'] = {'use_parent_address': False}
402 def onchange_state(self, cr, uid, ids, state_id, context=None):
404 country_id = self.pool['res.country.state'].browse(cr, uid, state_id, context).country_id.id
405 return {'value':{'country_id':country_id}}
408 def _check_ean_key(self, cr, uid, ids, context=None):
409 for partner_o in self.pool['res.partner'].read(cr, uid, ids, ['ean13',]):
410 thisean=partner_o['ean13']
411 if thisean and thisean!='':
419 sum+=3*int(thisean[i])
420 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
424 # _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
426 def _update_fields_values(self, cr, uid, partner, fields, context=None):
427 """ Returns dict of write() values for synchronizing ``fields`` """
430 column = self._all_columns[field].column
431 if column._type == 'one2many':
432 raise AssertionError('One2Many fields cannot be synchronized as part of `commercial_fields` or `address fields`')
433 if column._type == 'many2one':
434 values[field] = partner[field].id if partner[field] else False
435 elif column._type == 'many2many':
436 values[field] = [(6,0,[r.id for r in partner[field] or []])]
438 values[field] = partner[field]
441 def _address_fields(self, cr, uid, context=None):
442 """ Returns the list of address fields that are synced from the parent
443 when the `use_parent_address` flag is set. """
444 return list(ADDRESS_FIELDS)
446 def update_address(self, cr, uid, ids, vals, context=None):
447 address_fields = self._address_fields(cr, uid, context=context)
448 addr_vals = dict((key, vals[key]) for key in address_fields if key in vals)
450 return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
452 def _commercial_fields(self, cr, uid, context=None):
453 """ Returns the list of fields that are managed by the commercial entity
454 to which a partner belongs. These fields are meant to be hidden on
455 partners that aren't `commercial entities` themselves, and will be
456 delegated to the parent `commercial entity`. The list is meant to be
457 extended by inheriting classes. """
460 def _commercial_sync_from_company(self, cr, uid, partner, context=None):
461 """ Handle sync of commercial fields when a new parent commercial entity is set,
462 as if they were related fields """
463 if partner.commercial_partner_id != partner:
464 commercial_fields = self._commercial_fields(cr, uid, context=context)
465 sync_vals = self._update_fields_values(cr, uid, partner.commercial_partner_id,
466 commercial_fields, context=context)
467 partner.write(sync_vals)
469 def _commercial_sync_to_children(self, cr, uid, partner, context=None):
470 """ Handle sync of commercial fields to descendants """
471 commercial_fields = self._commercial_fields(cr, uid, context=context)
472 sync_vals = self._update_fields_values(cr, uid, partner.commercial_partner_id,
473 commercial_fields, context=context)
474 sync_children = [c for c in partner.child_ids if not c.is_company]
475 for child in sync_children:
476 self._commercial_sync_to_children(cr, uid, child, context=context)
477 return self.write(cr, uid, [c.id for c in sync_children], sync_vals, context=context)
479 def _fields_sync(self, cr, uid, partner, update_values, context=None):
480 """ Sync commercial fields and address fields from company and to children after create/update,
481 just as if those were all modeled as fields.related to the parent """
482 # 1. From UPSTREAM: sync from parent
483 if update_values.get('parent_id') or update_values.get('use_parent_address'):
484 # 1a. Commercial fields: sync if parent changed
485 if update_values.get('parent_id'):
486 self._commercial_sync_from_company(cr, uid, partner, context=context)
487 # 1b. Address fields: sync if parent or use_parent changed *and* both are now set
488 if partner.parent_id and partner.use_parent_address:
489 onchange_vals = self.onchange_address(cr, uid, [partner.id],
490 use_parent_address=partner.use_parent_address,
491 parent_id=partner.parent_id.id,
492 context=context).get('value', {})
493 partner.update_address(onchange_vals)
495 # 2. To DOWNSTREAM: sync children
496 if partner.child_ids:
497 # 2a. Commercial Fields: sync if commercial entity
498 if partner.commercial_partner_id == partner:
499 commercial_fields = self._commercial_fields(cr, uid,
501 if any(field in update_values for field in commercial_fields):
502 self._commercial_sync_to_children(cr, uid, partner,
504 # 2b. Address fields: sync if address changed
505 address_fields = self._address_fields(cr, uid, context=context)
506 if any(field in update_values for field in address_fields):
507 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
508 update_ids = self.search(cr, uid, domain_children, context=context)
509 self.update_address(cr, uid, update_ids, update_values, context=context)
511 def _handle_first_contact_creation(self, cr, uid, partner, context=None):
512 """ On creation of first contact for a company (or root) that has no address, assume contact address
513 was meant to be company address """
514 parent = partner.parent_id
515 address_fields = self._address_fields(cr, uid, context=context)
516 if parent and (parent.is_company or not parent.parent_id) and len(parent.child_ids) == 1 and \
517 any(partner[f] for f in address_fields) and not any(parent[f] for f in address_fields):
518 addr_vals = self._update_fields_values(cr, uid, partner, address_fields, context=context)
519 parent.update_address(addr_vals)
520 if not parent.is_company:
521 parent.write({'is_company': True})
523 def write(self, cr, uid, ids, vals, context=None):
524 if isinstance(ids, (int, long)):
526 #res.partner must only allow to set the company_id of a partner if it
527 #is the same as the company of all users that inherit from this partner
528 #(this is to allow the code from res_users to write to the partner!) or
529 #if setting the company_id to False (this is compatible with any user company)
530 if vals.get('company_id'):
531 for partner in self.browse(cr, uid, ids, context=context):
533 user_companies = set([user.company_id.id for user in partner.user_ids])
534 if len(user_companies) > 1 or vals['company_id'] not in user_companies:
535 raise osv.except_osv(_("Warning"),_("You can not change the company as the partner/user has multiple user linked with different companies."))
536 result = super(res_partner,self).write(cr, uid, ids, vals, context=context)
537 for partner in self.browse(cr, uid, ids, context=context):
538 self._fields_sync(cr, uid, partner, vals, context)
541 def create(self, cr, uid, vals, context=None):
542 new_id = super(res_partner, self).create(cr, uid, vals, context=context)
543 partner = self.browse(cr, uid, new_id, context=context)
544 self._fields_sync(cr, uid, partner, vals, context)
545 self._handle_first_contact_creation(cr, uid, partner, context)
548 def open_commercial_entity(self, cr, uid, ids, context=None):
549 """ Utility method used to add an "Open Company" button in partner views """
550 partner = self.browse(cr, uid, ids[0], context=context)
551 return {'type': 'ir.actions.act_window',
552 'res_model': 'res.partner',
554 'res_id': partner.commercial_partner_id.id,
556 'flags': {'form': {'action_buttons': True}}}
558 def open_parent(self, cr, uid, ids, context=None):
559 """ Utility method used to add an "Open Parent" button in partner views """
560 partner = self.browse(cr, uid, ids[0], context=context)
561 return {'type': 'ir.actions.act_window',
562 'res_model': 'res.partner',
564 'res_id': partner.parent_id.id,
566 'flags': {'form': {'action_buttons': True}}}
568 def name_get(self, cr, uid, ids, context=None):
571 if isinstance(ids, (int, long)):
574 for record in self.browse(cr, uid, ids, context=context):
576 if record.parent_id and not record.is_company:
577 name = "%s, %s" % (record.parent_id.name, name)
578 if context.get('show_address_only'):
579 name = self._display_address(cr, uid, record, without_company=True, context=context)
580 if context.get('show_address'):
581 name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
582 name = name.replace('\n\n','\n')
583 name = name.replace('\n\n','\n')
584 if context.get('show_email') and record.email:
585 name = "%s <%s>" % (name, record.email)
586 res.append((record.id, name))
589 def _parse_partner_name(self, text, context=None):
590 """ Supported syntax:
591 - 'Raoul <raoul@grosbedon.fr>': will find name and email address
592 - otherwise: default, everything is set as the name """
593 emails = tools.email_split(text)
596 name = text[:text.index(email)].replace('"', '').replace('<', '').strip()
598 name, email = text, ''
601 def name_create(self, cr, uid, name, context=None):
602 """ Override of orm's name_create method for partners. The purpose is
603 to handle some basic formats to create partners using the
605 If only an email address is received and that the regex cannot find
606 a name, the name will have the email value.
607 If 'force_email' key in context: must find the email address. """
610 name, email = self._parse_partner_name(name, context=context)
611 if context.get('force_email') and not email:
612 raise osv.except_osv(_('Warning'), _("Couldn't create contact without email address!"))
613 if not name and email:
615 rec_id = self.create(cr, uid, {self._rec_name: name or email, 'email': email or False}, context=context)
616 return self.name_get(cr, uid, [rec_id], context)[0]
618 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
619 """ Override search() to always show inactive children when searching via ``child_of`` operator. The ORM will
620 always call search() with a simple domain of the form [('parent_id', 'in', [ids])]. """
621 # a special ``domain`` is set on the ``child_ids`` o2m to bypass this logic, as it uses similar domain expressions
622 if len(args) == 1 and len(args[0]) == 3 and args[0][:2] == ('parent_id','in') \
623 and args[0][2] != [False]:
624 context = dict(context or {}, active_test=False)
625 return super(res_partner, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context,
626 count=count, access_rights_uid=access_rights_uid)
628 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
631 if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'):
633 self.check_access_rights(cr, uid, 'read')
634 where_query = self._where_calc(cr, uid, args, context=context)
635 self._apply_ir_rules(cr, uid, where_query, 'read', context=context)
636 from_clause, where_clause, where_clause_params = where_query.get_sql()
637 where_str = where_clause and (" WHERE %s AND " % where_clause) or ' WHERE '
639 # search on the name of the contacts and of its company
641 if operator in ('ilike', 'like'):
642 search_name = '%%%s%%' % name
643 if operator in ('=ilike', '=like'):
644 operator = operator[1:]
646 query = ('SELECT id FROM res_partner ' +
647 where_str + '(email ' + operator + ''' %s
648 OR display_name ''' + operator + ''' %s)
649 ORDER BY display_name''')
651 where_clause_params += [search_name, search_name]
654 where_clause_params.append(limit)
655 cr.execute(query, where_clause_params)
656 ids = map(lambda x: x[0], cr.fetchall())
659 return self.name_get(cr, uid, ids, context)
662 return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
664 def find_or_create(self, cr, uid, email, context=None):
665 """ Find a partner with the given ``email`` or use :py:method:`~.name_create`
668 :param str email: email-like string, which should contain at least one email,
669 e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``"""
670 assert email, 'an email is required for find_or_create to work'
671 emails = tools.email_split(email)
674 ids = self.search(cr, uid, [('email','ilike',email)], context=context)
676 return self.name_create(cr, uid, email, context=context)[0]
679 def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
680 partners = self.browse(cr, uid, ids)
681 for partner in partners:
683 tools.email_send(email_from, [partner.email], subject, body, on_error)
686 def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
688 self.pool['ir.cron'].create(cr, uid, {
689 'name': 'Send Partner Emails',
691 'model': 'res.partner',
692 'function': '_email_send',
693 'args': repr([ids[:16], email_from, subject, body, on_error])
698 def address_get(self, cr, uid, ids, adr_pref=None, context=None):
699 """ Find contacts/addresses of the right type(s) by doing a depth-first-search
700 through descendants within company boundaries (stop at entities flagged ``is_company``)
701 then continuing the search at the ancestors that are within the same company boundaries.
702 Defaults to partners of type ``'default'`` when the exact type is not found, or to the
703 provided partner itself if no type ``'default'`` is found either. """
704 adr_pref = set(adr_pref or [])
705 if 'default' not in adr_pref:
706 adr_pref.add('default')
709 for partner in self.browse(cr, uid, filter(None, ids), context=context):
710 current_partner = partner
711 while current_partner:
712 to_scan = [current_partner]
713 # Scan descendants, DFS
715 record = to_scan.pop(0)
717 if record.type in adr_pref and not result.get(record.type):
718 result[record.type] = record.id
719 if len(result) == len(adr_pref):
721 to_scan = [c for c in record.child_ids
723 if not c.is_company] + to_scan
725 # Continue scanning at ancestor if current_partner is not a commercial entity
726 if current_partner.is_company or not current_partner.parent_id:
728 current_partner = current_partner.parent_id
730 # default to type 'default' or the partner itself
731 default = result.get('default', partner.id)
732 for adr_type in adr_pref:
733 result[adr_type] = result.get(adr_type) or default
736 def view_header_get(self, cr, uid, view_id, view_type, context):
737 res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
739 if not context.get('category_id', False):
741 return _('Partners: ')+self.pool['res.partner.category'].browse(cr, uid, context['category_id'], context).name
743 def main_partner(self, cr, uid):
744 ''' Return the id of the main partner
746 model_data = self.pool['ir.model.data']
747 return model_data.browse(cr, uid,
748 model_data.search(cr, uid, [('module','=','base'),
749 ('name','=','main_partner')])[0],
752 def _display_address(self, cr, uid, address, without_company=False, context=None):
755 The purpose of this function is to build and return an address formatted accordingly to the
756 standards of the country where it belongs.
758 :param address: browse record of the res.partner to format
759 :returns: the address formatted in a display that fit its country habits (or the default ones
760 if not country is specified)
764 # get the information that will be injected into the display format
765 # get the address format
766 address_format = address.country_id and address.country_id.address_format or \
767 "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
769 'state_code': address.state_id and address.state_id.code or '',
770 'state_name': address.state_id and address.state_id.name or '',
771 'country_code': address.country_id and address.country_id.code or '',
772 'country_name': address.country_id and address.country_id.name or '',
773 'company_name': address.parent_id and address.parent_id.name or '',
775 for field in self._address_fields(cr, uid, context=context):
776 args[field] = getattr(address, field) or ''
778 args['company_name'] = ''
779 elif address.parent_id:
780 address_format = '%(company_name)s\n' + address_format
781 return address_format % args
783 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: