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 ##############################################################################
24 from osv import osv, fields
27 from tools.translate import _
31 class res_payterm(osv.osv):
32 _description = 'Payment term'
36 'name': fields.char('Payment Term (short name)', size=64),
39 class res_partner_category(osv.osv):
41 def name_get(self, cr, uid, ids, context=None):
42 """Return the categories' display name, including their direct
45 :param dict context: the ``partner_category_display`` key can be
46 used to select the short version of the
47 category name (without the direct parent),
48 when set to ``'short'``. The default is
52 if context.get('partner_category_display') == 'short':
53 return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
54 if isinstance(ids, (int, long)):
56 reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
60 if record['parent_id']:
61 name = record['parent_id'][1]+' / '+name
62 res.append((record['id'], name))
65 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
71 # Be sure name_search is symetric to name_get
72 name = name.split(' / ')[-1]
73 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
75 ids = self.search(cr, uid, args, limit=limit, context=context)
76 return self.name_get(cr, uid, ids, context)
79 def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
80 res = self.name_get(cr, uid, ids, context=context)
83 _description='Partner Categories'
84 _name = 'res.partner.category'
86 'name': fields.char('Category Name', required=True, size=64, translate=True),
87 'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
88 'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
89 'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
90 'active' : fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
91 'parent_left' : fields.integer('Left parent', select=True),
92 'parent_right' : fields.integer('Right parent', select=True),
93 'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'),
96 (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
99 'active' : lambda *a: 1,
102 _parent_order = 'name'
103 _order = 'parent_left'
105 class res_partner_title(osv.osv):
106 _name = 'res.partner.title'
108 'name': fields.char('Title', required=True, size=46, translate=True),
109 'shortcut': fields.char('Abbreviation', required=True, size=16, translate=True),
110 'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
114 def _lang_get(self, cr, uid, context=None):
115 lang_pool = self.pool.get('res.lang')
116 ids = lang_pool.search(cr, uid, [], context=context)
117 res = lang_pool.read(cr, uid, ids, ['code', 'name'], context)
118 return [(r['code'], r['name']) for r in res] + [('','')]
120 POSTAL_ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
121 ADDRESS_FIELDS = POSTAL_ADDRESS_FIELDS + ('email', 'phone', 'fax', 'mobile', 'website', 'ref', 'lang')
123 class res_partner(osv.osv):
124 _description='Partner'
125 _name = "res.partner"
127 def _address_display(self, cr, uid, ids, name, args, context=None):
129 for partner in self.browse(cr, uid, ids, context=context):
130 res[partner.id] =self._display_address(cr, uid, partner, context=context)
135 'name': fields.char('Name', size=128, required=True, select=True),
136 'date': fields.date('Date', select=1),
137 'title': fields.many2one('res.partner.title','Title'),
138 'parent_id': fields.many2one('res.partner','Company'),
139 'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts'),
140 'ref': fields.char('Reference', size=64, select=1),
141 'lang': fields.selection(_lang_get, 'Language', 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."),
142 'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this partner if any.'),
143 'vat': fields.char('VAT',size=32 ,help="Value Added Tax number. Check the box if the partner is subjected to the VAT. Used by the VAT legal statement."),
144 'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
145 'website': fields.char('Website',size=64, help="Website of Partner or Company"),
146 'comment': fields.text('Notes'),
147 'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'), # should be removed in version 7, but kept until then for backward compatibility
148 'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
149 'credit_limit': fields.float(string='Credit Limit'),
150 'ean13': fields.char('EAN13', size=13),
151 'active': fields.boolean('Active'),
152 'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
153 '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."),
154 'employee': fields.boolean('Employee', help="Check this box if the partner is an Employee."),
155 'function': fields.char('Job Position', size=128),
156 'type': fields.selection( [('default','Default'),('invoice','Invoice'),
157 ('delivery','Delivery'), ('contact','Contact'),
159 'Address Type', help="Used to select automatically the right address according to the context in sales and purchases documents."),
160 'street': fields.char('Street', size=128),
161 'street2': fields.char('Street2', size=128),
162 'zip': fields.char('Zip', change_default=True, size=24),
163 'city': fields.char('City', size=128),
164 'state_id': fields.many2one("res.country.state", 'State', domain="[('country_id','=',country_id)]"),
165 'country_id': fields.many2one('res.country', 'Country'),
166 'country': fields.related('country_id', type='many2one', relation='res.country', string='Country'), # for backward compatibility
167 'email': fields.char('Email', size=240),
168 'phone': fields.char('Phone', size=64),
169 'fax': fields.char('Fax', size=64),
170 'mobile': fields.char('Mobile', size=64),
171 'birthdate': fields.char('Birthdate', size=64),
172 'is_company': fields.boolean('Company', help="Check if the contact is a company, otherwise it is a person"),
173 'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information for this contact"),
174 'photo': fields.binary('Photo'),
175 'company_id': fields.many2one('res.company', 'Company', select=1),
176 'color': fields.integer('Color Index'),
177 'contact_address': fields.function(_address_display, type='char', string='Complete Address'),
180 def _default_category(self, cr, uid, context=None):
183 if context.get('category_id'):
184 return [context['category_id']]
187 def _get_photo(self, cr, uid, is_company, context=None):
189 path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'company_icon.png')
191 path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'photo.png')
192 return open(path, 'rb').read().encode('base64')
197 'category_id': _default_category,
198 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
202 'use_parent_address': True,
203 'photo': lambda self, cr, uid, context: self._get_photo(cr, uid, False, context),
206 def copy(self, cr, uid, id, default=None, context=None):
209 name = self.read(cr, uid, [id], ['name'], context)[0]['name']
210 default.update({'name': _('%s (copy)')%(name)})
211 return super(res_partner, self).copy(cr, uid, id, default, context)
213 def onchange_type(self, cr, uid, ids, is_company, context=None):
214 value = {'title': False,
215 'photo': self._get_photo(cr, uid, is_company, context)}
217 value['parent_id'] = False
218 domain = {'title': [('domain', '=', 'partner')]}
220 domain = {'title': [('domain', '=', 'contact')]}
221 return {'value': value, 'domain': domain}
223 def get_parent_address(self, cr, uid, parent_id, address_fields=POSTAL_ADDRESS_FIELDS, context=None):
224 def value_or_id(val):
225 """ return val or val.id if val is a browse record """
226 return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
227 parent = self.browse(cr, uid, parent_id, context=context)
228 return dict((key, value_or_id(parent[key])) for key in address_fields)
230 def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
231 if use_parent_address and parent_id:
232 return {'value': self.get_parent_address(cr, uid, parent_id, address_fields=ADDRESS_FIELDS, context=context)}
235 def _check_ean_key(self, cr, uid, ids, context=None):
236 for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
237 thisean=partner_o['ean13']
238 if thisean and thisean!='':
246 sum+=3*int(thisean[i])
247 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
251 # _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
253 def write(self, cr, uid, ids, vals, context=None):
254 # Update parent and siblings or children records
255 if isinstance(ids, (int, long)):
257 if vals.get('is_company')==False:
258 vals.update({'child_ids' : [(5,)]})
259 for partner in self.browse(cr, uid, ids, context=context):
261 if partner.is_company:
262 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
263 update_ids = self.search(cr, uid, domain_children, context=context)
264 elif partner.parent_id:
265 if vals.get('use_parent_address')==True:
266 domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
267 update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
268 if 'use_parent_address' not in vals and partner.use_parent_address:
269 domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
270 update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
271 self.update_address(cr, uid, update_ids, vals, context)
272 return super(res_partner,self).write(cr, uid, ids, vals, context=context)
274 def create(self, cr, uid, vals, context=None):
277 # Update parent and siblings records
278 if vals.get('parent_id') and vals.get('use_parent_address'):
279 # [RPA] why we need to change the siblings?
280 # we are creating a child of parent and it should not affect parent and siblings
281 # domain_siblings = [('parent_id', '=', vals['parent_id']), ('use_parent_address', '=', True)]
282 # update_ids = [vals['parent_id']] + self.search(cr, uid, domain_siblings, context=context)
283 # [RPA] the vals we pass in update_address is not of parent so it will do nothing
284 # self.update_address(cr, uid, update_ids, vals, context)
285 vals.update(self.get_parent_address(cr, uid, vals['parent_id'], address_fields=ADDRESS_FIELDS, context=context))
286 if 'photo' not in vals :
287 vals['photo'] = self._get_photo(cr, uid, vals.get('is_company', False) or context.get('default_is_company'), context)
288 return super(res_partner,self).create(cr, uid, vals, context=context)
290 def update_address(self, cr, uid, ids, vals, context=None):
291 addr_vals = dict((key, vals[key]) for key in POSTAL_ADDRESS_FIELDS if vals.get(key))
292 return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
294 def name_get(self, cr, uid, ids, context=None):
297 if isinstance(ids, (int, long)):
300 for record in self.browse(cr, uid, ids, context=context):
303 name = "%s (%s)" % (name, record.parent_id.name)
304 if context.get('show_address'):
305 name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
306 name = name.replace('\n\n','\n')
307 name = name.replace('\n\n','\n')
308 res.append((record.id, name))
311 def name_create(self, cr, uid, name, context=None):
312 """ Override of orm's name_create method for partners. The purpose is
313 to handle some basic formats to create partners using the
316 - 'raoul@grosbedon.fr': create a partner with name raoul@grosbedon.fr
317 and sets its email to raoul@grosbedon.fr
318 - 'Raoul Grosbedon <raoul@grosbedon.fr>': create a partner with name
319 Raoul Grosbedon, and set its email to raoul@grosbedon.fr
320 - anything else: fall back on the default name_create
322 - ([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8}): raoul@grosbedon.fr
323 - ([\w\s.\\-]+)[\<]([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})[\>]:
324 Raoul Grosbedon, raoul@grosbedon.fr
326 contact_regex = re.compile('([\w\s.\\-]+)[\<]([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})[\>]')
327 email_regex = re.compile('([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})')
328 contact_regex_res = contact_regex.findall(name)
329 email_regex_res = email_regex.findall(name)
330 if contact_regex_res:
331 name = contact_regex_res[0][0].rstrip(' ') # remove extra spaces on the right
332 email = contact_regex_res[0][1]
333 rec_id = self.create(cr, uid, {self._rec_name: name, 'email': email}, context);
334 return self.name_get(cr, uid, [rec_id], context)[0]
336 email = '%s' % (email_regex_res[0])
337 rec_id = self.create(cr, uid, {self._rec_name: email, 'email': email}, context);
338 return self.name_get(cr, uid, [rec_id], context)[0]
340 return super(res_partner, self).create(cr, uid, name, context)
342 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
345 if name and operator in ('=', 'ilike', '=ilike', 'like'):
346 # search on the name of the contacts and of its company
347 name2 = operator == '=' and name or '%' + name + '%'
351 limit_str = ' limit %s'
352 query_args += [limit]
353 cr.execute('''SELECT partner.id FROM res_partner partner
354 LEFT JOIN res_partner company ON partner.parent_id = company.id
355 WHERE partner.name || ' (' || COALESCE(company.name,'') || ')'
356 ''' + operator + ''' %s ''' + limit_str, query_args)
357 ids = map(lambda x: x[0], cr.fetchall())
359 ids = self.search(cr, uid, [('id', 'in', ids)] + args, limit=limit, context=context)
361 return self.name_get(cr, uid, ids, context)
362 return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
364 def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
365 partners = self.browse(cr, uid, ids)
366 for partner in partners:
368 tools.email_send(email_from, [partner.email], subject, body, on_error)
371 def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
373 self.pool.get('ir.cron').create(cr, uid, {
374 'name': 'Send Partner Emails',
376 'model': 'res.partner',
377 'function': '_email_send',
378 'args': repr([ids[:16], email_from, subject, body, on_error])
383 def address_get(self, cr, uid, ids, adr_pref=None):
385 adr_pref = ['default']
387 # retrieve addresses from the partner itself and its children
389 # need to fix the ids ,It get False value in list like ids[False]
390 if ids and ids[0]!=False:
391 for p in self.browse(cr, uid, ids):
392 res.append((p.type, p.id))
393 res.extend((c.type, c.id) for c in p.child_ids)
394 address_dict = dict(reversed(res))
395 # get the id of the (first) default address if there is one,
396 # otherwise get the id of the first address in the list
397 default_address = False
399 default_address = address_dict.get('default', res[0][1])
401 result[adr] = address_dict.get(adr, default_address)
404 def gen_next_ref(self, cr, uid, ids):
408 # compute the next number ref
409 cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
410 res = cr.dictfetchall()
411 ref = res and res[0]['ref'] or '0'
415 raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
417 # update the current partner
418 cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
421 def view_header_get(self, cr, uid, view_id, view_type, context):
422 res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
424 if (not context.get('category_id', False)):
426 return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
428 def main_partner(self, cr, uid):
429 ''' Return the id of the main partner
431 model_data = self.pool.get('ir.model.data')
432 return model_data.browse(cr, uid,
433 model_data.search(cr, uid, [('module','=','base'),
434 ('name','=','main_partner')])[0],
437 def _display_address(self, cr, uid, address, without_company=False, context=None):
440 The purpose of this function is to build and return an address formatted accordingly to the
441 standards of the country where it belongs.
443 :param address: browse record of the res.partner.address to format
444 :returns: the address formatted in a display that fit its country habits (or the default ones
445 if not country is specified)
449 # get the information that will be injected into the display format
450 # get the address format
451 address_format = address.country_id and address.country_id.address_format or \
452 '%(company_name)s\n%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s'
454 'state_code': address.state_id and address.state_id.code or '',
455 'state_name': address.state_id and address.state_id.name or '',
456 'country_code': address.country_id and address.country_id.code or '',
457 'country_name': address.country_id and address.country_id.name or '',
458 'company_name': address.parent_id and address.parent_id.name or '',
460 address_field = ['title', 'street', 'street2', 'zip', 'city']
461 for field in address_field :
462 args[field] = getattr(address, field) or ''
464 args['company_name'] = ''
465 return address_format % args
469 # res.partner.address is deprecated; it is still there for backward compability only and will be removed in next version
470 class res_partner_address(osv.osv):
471 _table = "res_partner"
472 _name = 'res.partner.address'
473 _order = 'type, name'
475 'parent_id': fields.many2one('res.partner', 'Company', ondelete='set null', select=True),
476 'partner_id': fields.related('parent_id', type='many2one', relation='res.partner', string='Partner'), # for backward compatibility
477 '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."),
478 'function': fields.char('Function', size=128),
479 'title': fields.many2one('res.partner.title','Title'),
480 'name': fields.char('Contact Name', size=64, select=1),
481 'street': fields.char('Street', size=128),
482 'street2': fields.char('Street2', size=128),
483 'zip': fields.char('Zip', change_default=True, size=24),
484 'city': fields.char('City', size=128),
485 'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
486 'country_id': fields.many2one('res.country', 'Country'),
487 'email': fields.char('Email', size=240),
488 'phone': fields.char('Phone', size=64),
489 'fax': fields.char('Fax', size=64),
490 'mobile': fields.char('Mobile', size=64),
491 'birthdate': fields.char('Birthdate', size=64),
492 'is_customer_add': fields.related('partner_id', 'customer', type='boolean', string='Customer'),
493 'is_supplier_add': fields.related('partner_id', 'supplier', type='boolean', string='Supplier'),
494 'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
495 'company_id': fields.many2one('res.company', 'Company',select=1),
496 'color': fields.integer('Color Index'),
501 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
506 def write(self, cr, uid, ids, vals, context=None):
507 logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
508 if 'partner_id' in vals:
509 vals['parent_id'] = vals.get('partner_id')
510 del(vals['partner_id'])
511 return self.pool.get('res.partner').write(cr, uid, ids, vals, context=context)
513 def create(self, cr, uid, vals, context=None):
514 logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
515 if 'partner_id' in vals:
516 vals['parent_id'] = vals.get('partner_id')
517 del(vals['partner_id'])
518 return self.pool.get('res.partner').create(cr, uid, vals, context=context)
520 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: