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