[MERGE] new v8 api by rco
[odoo/odoo.git] / openerp / addons / base / res / res_partner.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import datetime
23 from lxml import etree
24 import math
25 import pytz
26 import urlparse
27
28 import openerp
29 from openerp import tools, api
30 from openerp.osv import osv, fields
31 from openerp.osv.expression import get_unaccent_wrapper
32 from openerp.tools.translate import _
33
34 ADDRESS_FORMAT_LAYOUTS = {
35     '%(city)s %(state_code)s\n%(zip)s': """
36         <div class="address_format">
37             <field name="city" placeholder="City" style="width: 50%%"/>
38             <field name="state_id" class="oe_no_button" placeholder="State" style="width: 47%%" options='{"no_open": true}'/>
39             <br/>
40             <field name="zip" placeholder="ZIP"/>
41         </div>
42     """,
43     '%(zip)s %(city)s': """
44         <div class="address_format">
45             <field name="zip" placeholder="ZIP" style="width: 40%%"/>
46             <field name="city" placeholder="City" style="width: 57%%"/>
47             <br/>
48             <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
49         </div>
50     """,
51     '%(city)s\n%(state_name)s\n%(zip)s': """
52         <div class="address_format">
53             <field name="city" placeholder="City"/>
54             <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
55             <field name="zip" placeholder="ZIP"/>
56         </div>
57     """
58 }
59
60
61 class format_address(object):
62     @api.model
63     def fields_view_get_address(self, arch):
64         fmt = self.env.user.company_id.country_id.address_format or ''
65         for k, v in ADDRESS_FORMAT_LAYOUTS.items():
66             if k in fmt:
67                 doc = etree.fromstring(arch)
68                 for node in doc.xpath("//div[@class='address_format']"):
69                     tree = etree.fromstring(v)
70                     node.getparent().replace(node, tree)
71                 arch = etree.tostring(doc)
72                 break
73         return arch
74
75
76 @api.model
77 def _tz_get(self):
78     # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728
79     return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]
80
81
82 class res_partner_category(osv.Model):
83
84     def name_get(self, cr, uid, ids, context=None):
85         """ Return the categories' display name, including their direct
86             parent by default.
87
88             If ``context['partner_category_display']`` is ``'short'``, the short
89             version of the category name (without the direct parent) is used.
90             The default is the long version.
91         """
92         if not isinstance(ids, list):
93             ids = [ids]
94         if context is None:
95             context = {}
96
97         if context.get('partner_category_display') == 'short':
98             return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
99
100         res = []
101         for category in self.browse(cr, uid, ids, context=context):
102             names = []
103             current = category
104             while current:
105                 names.append(current.name)
106                 current = current.parent_id
107             res.append((category.id, ' / '.join(reversed(names))))
108         return res
109
110     @api.model
111     def name_search(self, name, args=None, operator='ilike', limit=100):
112         args = args or []
113         if name:
114             # Be sure name_search is symetric to name_get
115             name = name.split(' / ')[-1]
116             args = [('name', operator, name)] + args
117         categories = self.search(args, limit=limit)
118         return categories.name_get()
119
120     @api.multi
121     def _name_get_fnc(self, field_name, arg):
122         return dict(self.name_get())
123
124     _description = 'Partner Tags'
125     _name = 'res.partner.category'
126     _columns = {
127         'name': fields.char('Category Name', required=True, 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'),
135     }
136     _constraints = [
137         (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
138     ]
139     _defaults = {
140         'active': 1,
141     }
142     _parent_store = True
143     _parent_order = 'name'
144     _order = 'parent_left'
145
146
147 class res_partner_title(osv.osv):
148     _name = 'res.partner.title'
149     _order = 'name'
150     _columns = {
151         'name': fields.char('Title', required=True, translate=True),
152         'shortcut': fields.char('Abbreviation', translate=True),
153         'domain': fields.selection([('partner', 'Partner'), ('contact', 'Contact')], 'Domain', required=True)
154     }
155     _defaults = {
156         'domain': 'contact',
157     }
158
159
160 @api.model
161 def _lang_get(self):
162     languages = self.env['res.lang'].search([])
163     return [(language.code, language.name) for language in languages]
164
165 # fields copy if 'use_parent_address' is checked
166 ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
167
168
169 class res_partner(osv.Model, format_address):
170     _description = 'Partner'
171     _name = "res.partner"
172
173     def _address_display(self, cr, uid, ids, name, args, context=None):
174         res = {}
175         for partner in self.browse(cr, uid, ids, context=context):
176             res[partner.id] = self._display_address(cr, uid, partner, context=context)
177         return res
178
179     @api.multi
180     def _get_tz_offset(self, name, args):
181         return dict(
182             (p.id, datetime.datetime.now(pytz.timezone(p.tz or 'GMT')).strftime('%z'))
183             for p in self)
184
185     @api.multi
186     def _get_image(self, name, args):
187         return dict((p.id, tools.image_get_resized_images(p.image)) for p in self)
188
189     @api.one
190     def _set_image(self, name, value, args):
191         return self.write({'image': tools.image_resize_image_big(value)})
192
193     @api.multi
194     def _has_image(self, name, args):
195         return dict((p.id, bool(p.image)) for p in self)
196
197     def _commercial_partner_compute(self, cr, uid, ids, name, args, context=None):
198         """ Returns the partner that is considered the commercial
199         entity of this partner. The commercial entity holds the master data
200         for all commercial fields (see :py:meth:`~_commercial_fields`) """
201         result = dict.fromkeys(ids, False)
202         for partner in self.browse(cr, uid, ids, context=context):
203             current_partner = partner 
204             while not current_partner.is_company and current_partner.parent_id:
205                 current_partner = current_partner.parent_id
206             result[partner.id] = current_partner.id
207         return result
208
209     def _display_name_compute(self, cr, uid, ids, name, args, context=None):
210         context = dict(context or {})
211         context.pop('show_address', None)
212         context.pop('show_address_only', None)
213         context.pop('show_email', None)
214         return dict(self.name_get(cr, uid, ids, context=context))
215
216     # indirections to avoid passing a copy of the overridable method when declaring the function field
217     _commercial_partner_id = lambda self, *args, **kwargs: self._commercial_partner_compute(*args, **kwargs)
218     _display_name = lambda self, *args, **kwargs: self._display_name_compute(*args, **kwargs)
219
220     _commercial_partner_store_triggers = {
221         'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
222                         ['parent_id', 'is_company'], 10)
223     }
224     _display_name_store_triggers = {
225         'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
226                         ['parent_id', 'is_company', 'name'], 10)
227     }
228
229     _order = "display_name"
230     _columns = {
231         'name': fields.char('Name', required=True, select=True),
232         'display_name': fields.function(_display_name, type='char', string='Name', store=_display_name_store_triggers, select=True),
233         'date': fields.date('Date', select=1),
234         'title': fields.many2one('res.partner.title', 'Title'),
235         'parent_id': fields.many2one('res.partner', 'Related Company', select=True),
236         'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts', domain=[('active','=',True)]), # force "active_test" domain to bypass _search() override
237         'ref': fields.char('Contact Reference', select=1),
238         'lang': fields.selection(_lang_get, 'Language',
239             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."),
240         'tz': fields.selection(_tz_get,  'Timezone', size=64,
241             help="The partner's timezone, used to output proper date and time values inside printed reports. "
242                  "It is important to set a value for this field. You should use the same timezone "
243                  "that is otherwise used to pick and render date and time values: your computer's timezone."),
244         'tz_offset': fields.function(_get_tz_offset, type='char', size=5, string='Timezone offset', invisible=True),
245         'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this contact if any.'),
246         'vat': fields.char('TIN', help="Tax Identification Number. Check the box if this contact is subjected to taxes. Used by the some of the legal statements."),
247         'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
248         'website': fields.char('Website', help="Website of Partner or Company"),
249         'comment': fields.text('Notes'),
250         'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
251         'credit_limit': fields.float(string='Credit Limit'),
252         'ean13': fields.char('EAN13', size=13),
253         'active': fields.boolean('Active'),
254         'customer': fields.boolean('Customer', help="Check this box if this contact is a customer."),
255         '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."),
256         'employee': fields.boolean('Employee', help="Check this box if this contact is an Employee."),
257         'function': fields.char('Job Position'),
258         'type': fields.selection([('default', 'Default'), ('invoice', 'Invoice'),
259                                    ('delivery', 'Shipping'), ('contact', 'Contact'),
260                                    ('other', 'Other')], 'Address Type',
261             help="Used to select automatically the right address according to the context in sales and purchases documents."),
262         'street': fields.char('Street'),
263         'street2': fields.char('Street2'),
264         'zip': fields.char('Zip', size=24, change_default=True),
265         'city': fields.char('City'),
266         'state_id': fields.many2one("res.country.state", 'State', ondelete='restrict'),
267         'country_id': fields.many2one('res.country', 'Country', ondelete='restrict'),
268         'email': fields.char('Email'),
269         'phone': fields.char('Phone'),
270         'fax': fields.char('Fax'),
271         'mobile': fields.char('Mobile'),
272         'birthdate': fields.char('Birthdate'),
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     @api.model
305     def _default_category(self):
306         category_id = self.env.context.get('category_id', False)
307         return [category_id] if category_id else False
308
309     @api.model
310     def _get_default_image(self, is_company, colorize=False):
311         img_path = openerp.modules.get_module_resource(
312             'base', 'static/src/img', 'company_image.png' if is_company else 'avatar.png')
313         with open(img_path, 'rb') as f:
314             image = f.read()
315
316         # colorize user avatars
317         if not is_company:
318             image = tools.image_colorize(image)
319
320         return tools.image_resize_image_big(image.encode('base64'))
321
322     def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
323         if (not view_id) and (view_type=='form') and context and context.get('force_email', False):
324             view_id = self.pool['ir.model.data'].get_object_reference(cr, user, 'base', 'view_partner_simple_form')[1]
325         res = super(res_partner,self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
326         if view_type == 'form':
327             res['arch'] = self.fields_view_get_address(cr, user, res['arch'], context=context)
328         return res
329
330     @api.model
331     def _default_company(self):
332         return self.env['res.company']._company_default_get('res.partner')
333
334     _defaults = {
335         'active': True,
336         'lang': api.model(lambda self: self.env.lang),
337         'tz': api.model(lambda self: self.env.context.get('tz', False)),
338         'customer': True,
339         'category_id': _default_category,
340         'company_id': _default_company,
341         'color': 0,
342         'is_company': False,
343         'type': 'contact', # type 'default' is wildcard and thus inappropriate
344         'use_parent_address': False,
345         'image': False,
346     }
347
348     _constraints = [
349         (osv.osv._check_recursion, 'You cannot create recursive Partner hierarchies.', ['parent_id']),
350     ]
351
352     @api.one
353     def copy(self, default=None):
354         default = dict(default or {})
355         default['name'] = _('%s (copy)') % self.name
356         return super(res_partner, self).copy(default)
357
358     @api.multi
359     def onchange_type(self, is_company):
360         value = {}
361         value['title'] = False
362         if is_company:
363             value['use_parent_address'] = False
364             domain = {'title': [('domain', '=', 'partner')]}
365         else:
366             domain = {'title': [('domain', '=', 'contact')]}
367         return {'value': value, 'domain': domain}
368
369     def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
370         def value_or_id(val):
371             """ return val or val.id if val is a browse record """
372             return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
373         result = {}
374         if parent_id:
375             if ids:
376                 partner = self.browse(cr, uid, ids[0], context=context)
377                 if partner.parent_id and partner.parent_id.id != parent_id:
378                     result['warning'] = {'title': _('Warning'),
379                                          'message': _('Changing the company of a contact should only be done if it '
380                                                       'was never correctly set. If an existing contact starts working for a new '
381                                                       'company then a new contact should be created under that new '
382                                                       'company. You can use the "Discard" button to abandon this change.')}
383             if use_parent_address:
384                 parent = self.browse(cr, uid, parent_id, context=context)
385                 address_fields = self._address_fields(cr, uid, context=context)
386                 result['value'] = dict((key, value_or_id(parent[key])) for key in address_fields)
387         else:
388             result['value'] = {'use_parent_address': False}
389         return result
390
391     @api.multi
392     def onchange_state(self, state_id):
393         if state_id:
394             state = self.env['res.country.state'].browse(state_id)
395             return {'value': {'country_id': state.country_id.id}}
396         return {}
397
398     def _check_ean_key(self, cr, uid, ids, context=None):
399         for partner_o in self.pool['res.partner'].read(cr, uid, ids, ['ean13',]):
400             thisean=partner_o['ean13']
401             if thisean and thisean!='':
402                 if len(thisean)!=13:
403                     return False
404                 sum=0
405                 for i in range(12):
406                     if not (i % 2):
407                         sum+=int(thisean[i])
408                     else:
409                         sum+=3*int(thisean[i])
410                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
411                     return False
412         return True
413
414 #   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
415
416     def _update_fields_values(self, cr, uid, partner, fields, context=None):
417         """ Returns dict of write() values for synchronizing ``fields`` """
418         values = {}
419         for field in fields:
420             column = self._all_columns[field].column
421             if column._type == 'one2many':
422                 raise AssertionError('One2Many fields cannot be synchronized as part of `commercial_fields` or `address fields`')
423             if column._type == 'many2one':
424                 values[field] = partner[field].id if partner[field] else False
425             elif column._type == 'many2many':
426                 values[field] = [(6,0,[r.id for r in partner[field] or []])]
427             else:
428                 values[field] = partner[field]
429         return values
430
431     def _address_fields(self, cr, uid, context=None):
432         """ Returns the list of address fields that are synced from the parent
433         when the `use_parent_address` flag is set. """
434         return list(ADDRESS_FIELDS)
435
436     def update_address(self, cr, uid, ids, vals, context=None):
437         address_fields = self._address_fields(cr, uid, context=context)
438         addr_vals = dict((key, vals[key]) for key in address_fields if key in vals)
439         if addr_vals:
440             return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
441
442     def _commercial_fields(self, cr, uid, context=None):
443         """ Returns the list of fields that are managed by the commercial entity
444         to which a partner belongs. These fields are meant to be hidden on
445         partners that aren't `commercial entities` themselves, and will be
446         delegated to the parent `commercial entity`. The list is meant to be
447         extended by inheriting classes. """
448         return ['vat']
449
450     def _commercial_sync_from_company(self, cr, uid, partner, context=None):
451         """ Handle sync of commercial fields when a new parent commercial entity is set,
452         as if they were related fields """
453         if partner.commercial_partner_id != partner:
454             commercial_fields = self._commercial_fields(cr, uid, context=context)
455             sync_vals = self._update_fields_values(cr, uid, partner.commercial_partner_id,
456                                                         commercial_fields, context=context)
457             partner.write(sync_vals)
458
459     def _commercial_sync_to_children(self, cr, uid, partner, context=None):
460         """ Handle sync of commercial fields to descendants """
461         commercial_fields = self._commercial_fields(cr, uid, context=context)
462         sync_vals = self._update_fields_values(cr, uid, partner.commercial_partner_id,
463                                                    commercial_fields, context=context)
464         sync_children = [c for c in partner.child_ids if not c.is_company]
465         for child in sync_children:
466             self._commercial_sync_to_children(cr, uid, child, context=context)
467         return self.write(cr, uid, [c.id for c in sync_children], sync_vals, context=context)
468
469     def _fields_sync(self, cr, uid, partner, update_values, context=None):
470         """ Sync commercial fields and address fields from company and to children after create/update,
471         just as if those were all modeled as fields.related to the parent """
472         # 1. From UPSTREAM: sync from parent
473         if update_values.get('parent_id') or update_values.get('use_parent_address'):
474             # 1a. Commercial fields: sync if parent changed
475             if update_values.get('parent_id'):
476                 self._commercial_sync_from_company(cr, uid, partner, context=context)
477             # 1b. Address fields: sync if parent or use_parent changed *and* both are now set 
478             if partner.parent_id and partner.use_parent_address:
479                 onchange_vals = self.onchange_address(cr, uid, [partner.id],
480                                                       use_parent_address=partner.use_parent_address,
481                                                       parent_id=partner.parent_id.id,
482                                                       context=context).get('value', {})
483                 partner.update_address(onchange_vals)
484
485         # 2. To DOWNSTREAM: sync children 
486         if partner.child_ids:
487             # 2a. Commercial Fields: sync if commercial entity
488             if partner.commercial_partner_id == partner:
489                 commercial_fields = self._commercial_fields(cr, uid,
490                                                             context=context)
491                 if any(field in update_values for field in commercial_fields):
492                     self._commercial_sync_to_children(cr, uid, partner,
493                                                       context=context)
494             # 2b. Address fields: sync if address changed
495             address_fields = self._address_fields(cr, uid, context=context)
496             if any(field in update_values for field in address_fields):
497                 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
498                 update_ids = self.search(cr, uid, domain_children, context=context)
499                 self.update_address(cr, uid, update_ids, update_values, context=context)
500
501     def _handle_first_contact_creation(self, cr, uid, partner, context=None):
502         """ On creation of first contact for a company (or root) that has no address, assume contact address
503         was meant to be company address """
504         parent = partner.parent_id
505         address_fields = self._address_fields(cr, uid, context=context)
506         if parent and (parent.is_company or not parent.parent_id) and len(parent.child_ids) == 1 and \
507             any(partner[f] for f in address_fields) and not any(parent[f] for f in address_fields):
508             addr_vals = self._update_fields_values(cr, uid, partner, address_fields, context=context)
509             parent.update_address(addr_vals)
510             if not parent.is_company:
511                 parent.write({'is_company': True})
512
513     def _clean_website(self, website):
514         (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(website)
515         if not scheme:
516             if not netloc:
517                 netloc, path = path, ''
518             website = urlparse.urlunparse(('http', netloc, path, params, query, fragment))
519         return website
520
521     @api.multi
522     def write(self, vals):
523         # res.partner must only allow to set the company_id of a partner if it
524         # is the same as the company of all users that inherit from this partner
525         # (this is to allow the code from res_users to write to the partner!) or
526         # if setting the company_id to False (this is compatible with any user
527         # company)
528         if vals.get('website'):
529             vals['website'] = self._clean_website(vals['website'])
530         if vals.get('company_id'):
531             company = self.env['res.company'].browse(vals['company_id'])
532             for partner in self:
533                 if partner.user_ids:
534                     companies = set(user.company_id for user in partner.user_ids)
535                     if len(companies) > 1 or company not in companies:
536                         raise osv.except_osv(_("Warning"),_("You can not change the company as the partner/user has multiple user linked with different companies."))
537
538         result = super(res_partner, self).write(vals)
539         for partner in self:
540             self._fields_sync(partner, vals)
541         return result
542
543     @api.model
544     def create(self, vals):
545         if vals.get('website'):
546             vals['website'] = self._clean_website(vals['website'])
547         partner = super(res_partner, self).create(vals)
548         self._fields_sync(partner, vals)
549         self._handle_first_contact_creation(partner)
550         return partner
551
552     def open_commercial_entity(self, cr, uid, ids, context=None):
553         """ Utility method used to add an "Open Company" button in partner views """
554         partner = self.browse(cr, uid, ids[0], context=context)
555         return {'type': 'ir.actions.act_window',
556                 'res_model': 'res.partner',
557                 'view_mode': 'form',
558                 'res_id': partner.commercial_partner_id.id,
559                 'target': 'new',
560                 'flags': {'form': {'action_buttons': True}}}
561
562     def open_parent(self, cr, uid, ids, context=None):
563         """ Utility method used to add an "Open Parent" button in partner views """
564         partner = self.browse(cr, uid, ids[0], context=context)
565         return {'type': 'ir.actions.act_window',
566                 'res_model': 'res.partner',
567                 'view_mode': 'form',
568                 'res_id': partner.parent_id.id,
569                 'target': 'new',
570                 'flags': {'form': {'action_buttons': True}}}
571
572     def name_get(self, cr, uid, ids, context=None):
573         if context is None:
574             context = {}
575         if isinstance(ids, (int, long)):
576             ids = [ids]
577         res = []
578         for record in self.browse(cr, uid, ids, context=context):
579             name = record.name
580             if record.parent_id and not record.is_company:
581                 name =  "%s, %s" % (record.parent_id.name, name)
582             if context.get('show_address_only'):
583                 name = self._display_address(cr, uid, record, without_company=True, context=context)
584             if context.get('show_address'):
585                 name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
586             name = name.replace('\n\n','\n')
587             name = name.replace('\n\n','\n')
588             if context.get('show_email') and record.email:
589                 name = "%s <%s>" % (name, record.email)
590             res.append((record.id, name))
591         return res
592
593     def _parse_partner_name(self, text, context=None):
594         """ Supported syntax:
595             - 'Raoul <raoul@grosbedon.fr>': will find name and email address
596             - otherwise: default, everything is set as the name """
597         emails = tools.email_split(text.replace(' ',','))
598         if emails:
599             email = emails[0]
600             name = text[:text.index(email)].replace('"', '').replace('<', '').strip()
601         else:
602             name, email = text, ''
603         return name, email
604
605     def name_create(self, cr, uid, name, context=None):
606         """ Override of orm's name_create method for partners. The purpose is
607             to handle some basic formats to create partners using the
608             name_create.
609             If only an email address is received and that the regex cannot find
610             a name, the name will have the email value.
611             If 'force_email' key in context: must find the email address. """
612         if context is None:
613             context = {}
614         name, email = self._parse_partner_name(name, context=context)
615         if context.get('force_email') and not email:
616             raise osv.except_osv(_('Warning'), _("Couldn't create contact without email address!"))
617         if not name and email:
618             name = email
619         rec_id = self.create(cr, uid, {self._rec_name: name or email, 'email': email or False}, context=context)
620         return self.name_get(cr, uid, [rec_id], context)[0]
621
622     def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
623         """ Override search() to always show inactive children when searching via ``child_of`` operator. The ORM will
624         always call search() with a simple domain of the form [('parent_id', 'in', [ids])]. """
625         # a special ``domain`` is set on the ``child_ids`` o2m to bypass this logic, as it uses similar domain expressions
626         if len(args) == 1 and len(args[0]) == 3 and args[0][:2] == ('parent_id','in') \
627                 and args[0][2] != [False]:
628             context = dict(context or {}, active_test=False)
629         return super(res_partner, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context,
630                                                 count=count, access_rights_uid=access_rights_uid)
631
632     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
633         if not args:
634             args = []
635         if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'):
636
637             self.check_access_rights(cr, uid, 'read')
638             where_query = self._where_calc(cr, uid, args, context=context)
639             self._apply_ir_rules(cr, uid, where_query, 'read', context=context)
640             from_clause, where_clause, where_clause_params = where_query.get_sql()
641             where_str = where_clause and (" WHERE %s AND " % where_clause) or ' WHERE '
642
643             # search on the name of the contacts and of its company
644             search_name = name
645             if operator in ('ilike', 'like'):
646                 search_name = '%%%s%%' % name
647             if operator in ('=ilike', '=like'):
648                 operator = operator[1:]
649
650             unaccent = get_unaccent_wrapper(cr)
651
652             query = """SELECT id
653                          FROM res_partner
654                       {where} ({email} {operator} {percent}
655                            OR {display_name} {operator} {percent})
656                      ORDER BY {display_name}
657                     """.format(where=where_str, operator=operator,
658                                email=unaccent('email'),
659                                display_name=unaccent('display_name'),
660                                percent=unaccent('%s'))
661
662             where_clause_params += [search_name, search_name]
663             if limit:
664                 query += ' limit %s'
665                 where_clause_params.append(limit)
666             cr.execute(query, where_clause_params)
667             ids = map(lambda x: x[0], cr.fetchall())
668
669             if ids:
670                 return self.name_get(cr, uid, ids, context)
671             else:
672                 return []
673         return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
674
675     def find_or_create(self, cr, uid, email, context=None):
676         """ Find a partner with the given ``email`` or use :py:method:`~.name_create`
677             to create one
678
679             :param str email: email-like string, which should contain at least one email,
680                 e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``"""
681         assert email, 'an email is required for find_or_create to work'
682         emails = tools.email_split(email)
683         if emails:
684             email = emails[0]
685         ids = self.search(cr, uid, [('email','ilike',email)], context=context)
686         if not ids:
687             return self.name_create(cr, uid, email, context=context)[0]
688         return ids[0]
689
690     def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
691         partners = self.browse(cr, uid, ids)
692         for partner in partners:
693             if partner.email:
694                 tools.email_send(email_from, [partner.email], subject, body, on_error)
695         return True
696
697     def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
698         while len(ids):
699             self.pool['ir.cron'].create(cr, uid, {
700                 'name': 'Send Partner Emails',
701                 'user_id': uid,
702                 'model': 'res.partner',
703                 'function': '_email_send',
704                 'args': repr([ids[:16], email_from, subject, body, on_error])
705             })
706             ids = ids[16:]
707         return True
708
709     def address_get(self, cr, uid, ids, adr_pref=None, context=None):
710         """ Find contacts/addresses of the right type(s) by doing a depth-first-search
711         through descendants within company boundaries (stop at entities flagged ``is_company``)
712         then continuing the search at the ancestors that are within the same company boundaries.
713         Defaults to partners of type ``'default'`` when the exact type is not found, or to the
714         provided partner itself if no type ``'default'`` is found either. """
715         adr_pref = set(adr_pref or [])
716         if 'default' not in adr_pref:
717             adr_pref.add('default')
718         result = {}
719         visited = set()
720         for partner in self.browse(cr, uid, filter(None, ids), context=context):
721             current_partner = partner
722             while current_partner:
723                 to_scan = [current_partner]
724                 # Scan descendants, DFS
725                 while to_scan:
726                     record = to_scan.pop(0)
727                     visited.add(record)
728                     if record.type in adr_pref and not result.get(record.type):
729                         result[record.type] = record.id
730                     if len(result) == len(adr_pref):
731                         return result
732                     to_scan = [c for c in record.child_ids
733                                  if c not in visited
734                                  if not c.is_company] + to_scan
735
736                 # Continue scanning at ancestor if current_partner is not a commercial entity
737                 if current_partner.is_company or not current_partner.parent_id:
738                     break
739                 current_partner = current_partner.parent_id
740
741         # default to type 'default' or the partner itself
742         default = result.get('default', partner.id)
743         for adr_type in adr_pref:
744             result[adr_type] = result.get(adr_type) or default 
745         return result
746
747     def view_header_get(self, cr, uid, view_id, view_type, context):
748         res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
749         if res: return res
750         if not context.get('category_id', False):
751             return False
752         return _('Partners: ')+self.pool['res.partner.category'].browse(cr, uid, context['category_id'], context).name
753
754     @api.model
755     @api.returns('self')
756     def main_partner(self):
757         ''' Return the main partner '''
758         return self.env.ref('base.main_partner')
759
760     def _display_address(self, cr, uid, address, without_company=False, context=None):
761
762         '''
763         The purpose of this function is to build and return an address formatted accordingly to the
764         standards of the country where it belongs.
765
766         :param address: browse record of the res.partner to format
767         :returns: the address formatted in a display that fit its country habits (or the default ones
768             if not country is specified)
769         :rtype: string
770         '''
771
772         # get the information that will be injected into the display format
773         # get the address format
774         address_format = address.country_id.address_format or \
775               "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
776         args = {
777             'state_code': address.state_id.code or '',
778             'state_name': address.state_id.name or '',
779             'country_code': address.country_id.code or '',
780             'country_name': address.country_id.name or '',
781             'company_name': address.parent_id.name or '',
782         }
783         for field in self._address_fields(cr, uid, context=context):
784             args[field] = getattr(address, field) or ''
785         if without_company:
786             args['company_name'] = ''
787         elif address.parent_id:
788             address_format = '%(company_name)s\n' + address_format
789         return address_format % args
790
791 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: