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 ##############################################################################
25 from osv import osv, fields
28 from tools.translate import _
33 def _tz_get(self,cr,uid, context=None):
34 return [(x, x) for x in pytz.all_timezones]
36 class res_payterm(osv.osv):
37 _description = 'Payment term'
41 'name': fields.char('Payment Term (short name)', size=64),
44 class res_partner_category(osv.osv):
46 def name_get(self, cr, uid, ids, context=None):
47 """Return the categories' display name, including their direct
50 :param dict context: the ``partner_category_display`` key can be
51 used to select the short version of the
52 category name (without the direct parent),
53 when set to ``'short'``. The default is
57 if context.get('partner_category_display') == 'short':
58 return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
59 if isinstance(ids, (int, long)):
61 reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
65 if record['parent_id']:
66 name = record['parent_id'][1]+' / '+name
67 res.append((record['id'], name))
70 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
76 # Be sure name_search is symetric to name_get
77 name = name.split(' / ')[-1]
78 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
80 ids = self.search(cr, uid, args, limit=limit, context=context)
81 return self.name_get(cr, uid, ids, context)
84 def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
85 res = self.name_get(cr, uid, ids, context=context)
88 _description='Partner Categories'
89 _name = 'res.partner.category'
91 'name': fields.char('Category Name', required=True, size=64, translate=True),
92 'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
93 'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
94 'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
95 'active' : fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
96 'parent_left' : fields.integer('Left parent', select=True),
97 'parent_right' : fields.integer('Right parent', select=True),
98 'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'),
101 (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
104 'active' : lambda *a: 1,
107 _parent_order = 'name'
108 _order = 'parent_left'
110 class res_partner_title(osv.osv):
111 _name = 'res.partner.title'
114 'name': fields.char('Title', required=True, size=46, translate=True),
115 'shortcut': fields.char('Abbreviation', size=16, translate=True),
116 'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
122 def _lang_get(self, cr, uid, context=None):
123 lang_pool = self.pool.get('res.lang')
124 ids = lang_pool.search(cr, uid, [], context=context)
125 res = lang_pool.read(cr, uid, ids, ['code', 'name'], context)
126 return [(r['code'], r['name']) for r in res] + [('','')]
128 POSTAL_ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
129 ADDRESS_FIELDS = POSTAL_ADDRESS_FIELDS + ('email', 'phone', 'fax', 'mobile', 'website', 'ref', 'lang')
131 class res_partner(osv.osv):
132 _description='Partner'
133 _name = "res.partner"
135 def _address_display(self, cr, uid, ids, name, args, context=None):
137 for partner in self.browse(cr, uid, ids, context=context):
138 res[partner.id] =self._display_address(cr, uid, partner, context=context)
141 def _get_image(self, cr, uid, ids, name, args, context=None):
142 result = dict.fromkeys(ids, False)
143 for obj in self.browse(cr, uid, ids, context=context):
144 result[obj.id] = tools.image_get_resized_images(obj.image)
147 def _set_image(self, cr, uid, id, name, value, args, context=None):
148 return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
152 'name': fields.char('Name', size=128, required=True, select=True),
153 'date': fields.date('Date', select=1),
154 'title': fields.many2one('res.partner.title','Title'),
155 'parent_id': fields.many2one('res.partner', 'Owned by'),
156 'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts'),
157 'ref': fields.char('Reference', size=64, select=1),
158 'lang': fields.selection(_lang_get, 'Language',
159 help="If the selected language is loaded in the system, all documents related to this partner will be printed in this language. If not, it will be english."),
160 'tz': fields.selection(_tz_get, 'Timezone', size=64,
161 help="The partner's timezone, used to output proper date and time values inside printed reports. "
162 "It is important to set a value for this field. You should use the same timezone "
163 "that is otherwise used to pick and render date and time values: your computer's timezone."),
164 'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this partner if any.'),
165 'vat': fields.char('TIN',size=32 ,help="Tax Identification Number. Check the box if the partner is subjected to taxes. Used by the some of the legal statements."),
166 'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
167 'website': fields.char('Website',size=64, help="Website of Partner or Company"),
168 'comment': fields.text('Notes'),
169 'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'), # should be removed in version 7, but kept until then for backward compatibility
170 'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
171 'credit_limit': fields.float(string='Credit Limit'),
172 'ean13': fields.char('EAN13', size=13),
173 'active': fields.boolean('Active'),
174 'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
175 'supplier': fields.boolean('Supplier', help="Check this box if the partner is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."),
176 'employee': fields.boolean('Employee', help="Check this box if the partner is an Employee."),
177 'function': fields.char('Job Position', size=128),
178 'type': fields.selection( [('default','Default'), ('invoice','Invoice'),
179 ('delivery','Delivery'), ('contact','Contact'),
180 ('other', 'Other')], 'Address Type',
181 help="Used to select automatically the right address according to the context in sales and purchases documents."),
182 'street': fields.char('Street', size=128),
183 'street2': fields.char('Street2', size=128),
184 'zip': fields.char('Zip', change_default=True, size=24),
185 'city': fields.char('City', size=128),
186 'state_id': fields.many2one("res.country.state", 'State'),
187 'country_id': fields.many2one('res.country', 'Country'),
188 'country': fields.related('country_id', type='many2one', relation='res.country', string='Country'), # for backward compatibility
189 'email': fields.char('Email', size=240),
190 'phone': fields.char('Phone', size=64),
191 'fax': fields.char('Fax', size=64),
192 'mobile': fields.char('Mobile', size=64),
193 'birthdate': fields.char('Birthdate', size=64),
194 'is_company': fields.boolean('Company', help="Check if the contact is a company, otherwise it is a person"),
195 'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information for this contact"),
196 'image': fields.binary("Image",
197 help="This field holds the image used as avatar for the "\
198 "partner. The image is base64 encoded, and PIL-supported. "\
199 "It is limited to a 1024x1024 px image."),
200 'image_medium': fields.function(_get_image, fnct_inv=_set_image,
201 string="Medium-sized image", type="binary", multi="_get_image",
203 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
205 help="Medium-sized image of the partner. It is automatically "\
206 "resized as a 180x180 px image, with aspect ratio preserved. "\
207 "Use this field in form views or some kanban views."),
208 'image_small': fields.function(_get_image, fnct_inv=_set_image,
209 string="Small-sized image", type="binary", multi="_get_image",
211 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
213 help="Small-sized image of the partner. It is automatically "\
214 "resized as a 50x50 px image, with aspect ratio preserved. "\
215 "Use this field anywhere a small image is required."),
216 'company_id': fields.many2one('res.company', 'Company', select=1),
217 'color': fields.integer('Color Index'),
218 'contact_address': fields.function(_address_display, type='char', string='Complete Address'),
221 def _default_category(self, cr, uid, context=None):
224 if context.get('category_id'):
225 return [context['category_id']]
228 def _get_default_image(self, cr, uid, is_company, context=None):
230 image_path = openerp.modules.get_module_resource('base', 'static/src/img', 'company_image.png')
232 image_path = openerp.modules.get_module_resource('base', 'static/src/img', 'partner_image.png')
233 return tools.image_resize_image_big(open(image_path, 'rb').read().encode('base64'))
237 'lang': lambda self, cr, uid, context: context.get('lang', 'en_US'),
238 'tz': lambda self, cr, uid, context: context.get('tz', False),
240 'category_id': _default_category,
241 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
245 'use_parent_address': True,
246 'image': lambda self, cr, uid, context: self._get_default_image(cr, uid, False, context),
247 'image_small': lambda self, cr, uid, context: self._get_default_image(cr, uid, False, context),
248 'image_medium': lambda self, cr, uid, context: self._get_default_image(cr, uid, False, context),
251 def copy(self, cr, uid, id, default=None, context=None):
254 name = self.read(cr, uid, [id], ['name'], context)[0]['name']
255 default.update({'name': _('%s (copy)')%(name)})
256 return super(res_partner, self).copy(cr, uid, id, default, context)
258 def onchange_type(self, cr, uid, ids, is_company, context=None):
259 # get value as for an onchange on the image
260 value = tools.image_get_resized_images(self._get_default_image(cr, uid, is_company, context), return_big=True)
261 value['title'] = False
263 value['parent_id'] = False
264 domain = {'title': [('domain', '=', 'partner')]}
266 domain = {'title': [('domain', '=', 'contact')]}
267 return {'value': value, 'domain': domain}
269 def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
270 def value_or_id(val):
271 """ return val or val.id if val is a browse record """
272 return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
274 if use_parent_address and parent_id:
275 parent = self.browse(cr, uid, parent_id, context=context)
276 return {'value': dict((key, value_or_id(parent[key])) for key in ADDRESS_FIELDS)}
279 def _check_ean_key(self, cr, uid, ids, context=None):
280 for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
281 thisean=partner_o['ean13']
282 if thisean and thisean!='':
290 sum+=3*int(thisean[i])
291 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
295 # _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
297 def write(self, cr, uid, ids, vals, context=None):
298 # Update parent and siblings or children records
299 if isinstance(ids, (int, long)):
301 if vals.get('is_company')==False:
302 vals.update({'child_ids' : [(5,)]})
303 for partner in self.browse(cr, uid, ids, context=context):
305 if partner.is_company:
306 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
307 update_ids = self.search(cr, uid, domain_children, context=context)
308 elif partner.parent_id:
309 if vals.get('use_parent_address')==True:
310 domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
311 update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
312 if 'use_parent_address' not in vals and partner.use_parent_address:
313 domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
314 update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
315 self.update_address(cr, uid, update_ids, vals, context)
316 return super(res_partner,self).write(cr, uid, ids, vals, context=context)
318 def create(self, cr, uid, vals, context=None):
321 # Update parent and siblings records
322 if vals.get('parent_id') and vals.get('use_parent_address'):
323 domain_siblings = [('parent_id', '=', vals['parent_id']), ('use_parent_address', '=', True)]
324 update_ids = [vals['parent_id']] + self.search(cr, uid, domain_siblings, context=context)
325 self.update_address(cr, uid, update_ids, vals, context)
326 if 'image' not in vals :
327 image_value = self._get_default_image(cr, uid, vals.get('is_company', False) or context.get('default_is_company'), context)
328 vals.update(tools.image_get_resized_images(image_value, return_big=True))
329 return super(res_partner,self).create(cr, uid, vals, context=context)
331 def update_address(self, cr, uid, ids, vals, context=None):
332 addr_vals = dict((key, vals[key]) for key in POSTAL_ADDRESS_FIELDS if vals.get(key))
334 return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
336 def name_get(self, cr, uid, ids, context=None):
339 if isinstance(ids, (int, long)):
342 for record in self.browse(cr, uid, ids, context=context):
345 name = "%s (%s)" % (name, record.parent_id.name)
346 if context.get('show_address'):
347 name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
348 name = name.replace('\n\n','\n')
349 name = name.replace('\n\n','\n')
350 res.append((record.id, name))
353 def name_create(self, cr, uid, name, context=None):
354 """ Override of orm's name_create method for partners. The purpose is
355 to handle some basic formats to create partners using the
358 - 'raoul@grosbedon.fr': create a partner with name raoul@grosbedon.fr
359 and sets its email to raoul@grosbedon.fr
360 - 'Raoul Grosbedon <raoul@grosbedon.fr>': create a partner with name
361 Raoul Grosbedon, and set its email to raoul@grosbedon.fr
362 - anything else: fall back on the default name_create
364 - ([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8}): raoul@grosbedon.fr
365 - ([\w\s.\\-]+)[\<]([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})[\>]:
366 Raoul Grosbedon, raoul@grosbedon.fr
368 contact_regex = re.compile('([\w\s.\\-]+)[\<]([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})[\>]')
369 email_regex = re.compile('([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})')
370 contact_regex_res = contact_regex.findall(name)
371 email_regex_res = email_regex.findall(name)
372 if contact_regex_res:
373 name = contact_regex_res[0][0].rstrip(' ') # remove extra spaces on the right
374 email = contact_regex_res[0][1]
375 rec_id = self.create(cr, uid, {self._rec_name: name, 'email': email}, context);
376 return self.name_get(cr, uid, [rec_id], context)[0]
377 elif email_regex_res:
378 email = '%s' % (email_regex_res[0])
379 rec_id = self.create(cr, uid, {self._rec_name: email, 'email': email}, context);
380 return self.name_get(cr, uid, [rec_id], context)[0]
382 rec_id = super(res_partner, self).create(cr, uid, {self._rec_name: name}, context)
383 return self.name_get(cr, uid, [rec_id], context)[0]
385 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
388 if name and operator in ('=', 'ilike', '=ilike', 'like'):
389 # search on the name of the contacts and of its company
390 name2 = operator == '=' and name or '%' + name + '%'
394 limit_str = ' limit %s'
395 query_args += [limit]
396 cr.execute('''SELECT partner.id FROM res_partner partner
397 LEFT JOIN res_partner company ON partner.parent_id = company.id
398 WHERE partner.name || ' (' || COALESCE(company.name,'') || ')'
399 ''' + operator + ''' %s ''' + limit_str, query_args)
400 ids = map(lambda x: x[0], cr.fetchall())
402 ids = self.search(cr, uid, [('id', 'in', ids)] + args, limit=limit, context=context)
404 return self.name_get(cr, uid, ids, context)
405 return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
407 def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
408 partners = self.browse(cr, uid, ids)
409 for partner in partners:
411 tools.email_send(email_from, [partner.email], subject, body, on_error)
414 def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
416 self.pool.get('ir.cron').create(cr, uid, {
417 'name': 'Send Partner Emails',
419 'model': 'res.partner',
420 'function': '_email_send',
421 'args': repr([ids[:16], email_from, subject, body, on_error])
426 def address_get(self, cr, uid, ids, adr_pref=None):
428 adr_pref = ['default']
430 # retrieve addresses from the partner itself and its children
432 # need to fix the ids ,It get False value in list like ids[False]
433 if ids and ids[0]!=False:
434 for p in self.browse(cr, uid, ids):
435 res.append((p.type, p.id))
436 res.extend((c.type, c.id) for c in p.child_ids)
437 address_dict = dict(reversed(res))
438 # get the id of the (first) default address if there is one,
439 # otherwise get the id of the first address in the list
440 default_address = False
442 default_address = address_dict.get('default', res[0][1])
444 result[adr] = address_dict.get(adr, default_address)
447 def gen_next_ref(self, cr, uid, ids):
451 # compute the next number ref
452 cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
453 res = cr.dictfetchall()
454 ref = res and res[0]['ref'] or '0'
458 raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
460 # update the current partner
461 cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
464 def view_header_get(self, cr, uid, view_id, view_type, context):
465 res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
467 if (not context.get('category_id', False)):
469 return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
471 def main_partner(self, cr, uid):
472 ''' Return the id of the main partner
474 model_data = self.pool.get('ir.model.data')
475 return model_data.browse(cr, uid,
476 model_data.search(cr, uid, [('module','=','base'),
477 ('name','=','main_partner')])[0],
480 def _display_address(self, cr, uid, address, without_company=False, context=None):
483 The purpose of this function is to build and return an address formatted accordingly to the
484 standards of the country where it belongs.
486 :param address: browse record of the res.partner.address to format
487 :returns: the address formatted in a display that fit its country habits (or the default ones
488 if not country is specified)
492 # get the information that will be injected into the display format
493 # get the address format
494 address_format = address.country_id and address.country_id.address_format or \
495 '%(company_name)s\n%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s'
497 'state_code': address.state_id and address.state_id.code or '',
498 'state_name': address.state_id and address.state_id.name or '',
499 'country_code': address.country_id and address.country_id.code or '',
500 'country_name': address.country_id and address.country_id.name or '',
501 'company_name': address.parent_id and address.parent_id.name or '',
503 address_field = ['title', 'street', 'street2', 'zip', 'city']
504 for field in address_field :
505 args[field] = getattr(address, field) or ''
507 args['company_name'] = ''
508 return address_format % args
512 # res.partner.address is deprecated; it is still there for backward compability only and will be removed in next version
513 class res_partner_address(osv.osv):
514 _table = "res_partner"
515 _name = 'res.partner.address'
516 _order = 'type, name'
518 'parent_id': fields.many2one('res.partner', 'Company', ondelete='set null', select=True),
519 'partner_id': fields.related('parent_id', type='many2one', relation='res.partner', string='Partner'), # for backward compatibility
520 'type': fields.selection( [ ('default','Default'),('invoice','Invoice'), ('delivery','Delivery'), ('contact','Contact'), ('other','Other') ],'Address Type', help="Used to select automatically the right address according to the context in sales and purchases documents."),
521 'function': fields.char('Function', size=128),
522 'title': fields.many2one('res.partner.title','Title'),
523 'name': fields.char('Contact Name', size=64, select=1),
524 'street': fields.char('Street', size=128),
525 'street2': fields.char('Street2', size=128),
526 'zip': fields.char('Zip', change_default=True, size=24),
527 'city': fields.char('City', size=128),
528 'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
529 'country_id': fields.many2one('res.country', 'Country'),
530 'email': fields.char('Email', size=240),
531 'phone': fields.char('Phone', size=64),
532 'fax': fields.char('Fax', size=64),
533 'mobile': fields.char('Mobile', size=64),
534 'birthdate': fields.char('Birthdate', size=64),
535 'is_customer_add': fields.related('partner_id', 'customer', type='boolean', string='Customer'),
536 'is_supplier_add': fields.related('partner_id', 'supplier', type='boolean', string='Supplier'),
537 'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
538 'company_id': fields.many2one('res.company', 'Company',select=1),
539 'color': fields.integer('Color Index'),
544 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
549 def write(self, cr, uid, ids, vals, context=None):
550 logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
551 if 'partner_id' in vals:
552 vals['parent_id'] = vals.get('partner_id')
553 del(vals['partner_id'])
554 return self.pool.get('res.partner').write(cr, uid, ids, vals, context=context)
556 def create(self, cr, uid, vals, context=None):
557 logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
558 if 'partner_id' in vals:
559 vals['parent_id'] = vals.get('partner_id')
560 del(vals['partner_id'])
561 return self.pool.get('res.partner').create(cr, uid, vals, context=context)
563 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: