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
26 from tools.translate import _
30 class res_payterm(osv.osv):
31 _description = 'Payment term'
35 'name': fields.char('Payment Term (short name)', size=64),
38 class res_partner_category(osv.osv):
40 def name_get(self, cr, uid, ids, context=None):
41 """Return the categories' display name, including their direct
44 :param dict context: the ``partner_category_display`` key can be
45 used to select the short version of the
46 category name (without the direct parent),
47 when set to ``'short'``. The default is
51 if context.get('partner_category_display') == 'short':
52 return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
53 if isinstance(ids, (int, long)):
55 reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
59 if record['parent_id']:
60 name = record['parent_id'][1]+' / '+name
61 res.append((record['id'], name))
64 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
70 # Be sure name_search is symetric to name_get
71 name = name.split(' / ')[-1]
72 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
74 ids = self.search(cr, uid, args, limit=limit, context=context)
75 return self.name_get(cr, uid, ids, context)
78 def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
79 res = self.name_get(cr, uid, ids, context=context)
82 _description='Partner Categories'
83 _name = 'res.partner.category'
85 'name': fields.char('Category Name', required=True, size=64, translate=True),
86 'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
87 'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
88 'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
89 'active' : fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
90 'parent_left' : fields.integer('Left parent', select=True),
91 'parent_right' : fields.integer('Right parent', select=True),
92 'partner_ids': fields.many2many('res.partner', 'res_partner_category_rel', 'category_id', 'partner_id', 'Partners'),
95 (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
98 'active' : lambda *a: 1,
101 _parent_order = 'name'
102 _order = 'parent_left'
104 class res_partner_title(osv.osv):
105 _name = 'res.partner.title'
107 'name': fields.char('Title', required=True, size=46, translate=True),
108 'shortcut': fields.char('Abbreviation', required=True, size=16, translate=True),
109 'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
113 def _lang_get(self, cr, uid, context=None):
114 lang_pool = self.pool.get('res.lang')
115 ids = lang_pool.search(cr, uid, [], context=context)
116 res = lang_pool.read(cr, uid, ids, ['code', 'name'], context)
117 return [(r['code'], r['name']) for r in res] + [('','')]
119 POSTAL_ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
120 ADDRESS_FIELDS = POSTAL_ADDRESS_FIELDS + ('email', 'phone', 'fax', 'mobile', 'website', 'ref', 'lang')
122 class res_partner(osv.osv):
123 _description='Partner'
124 _name = "res.partner"
126 def _address_display(self, cr, uid, ids, name, args, context=None):
128 for partner in self.browse(cr, uid, ids, context=context):
129 res[partner.id] =self._display_address(cr, uid, partner, context=context)
134 'name': fields.char('Name', size=128, required=True, select=True),
135 'date': fields.date('Date', select=1),
136 'title': fields.many2one('res.partner.title','Title'),
137 'parent_id': fields.many2one('res.partner','Company'),
138 'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts'),
139 'ref': fields.char('Reference', size=64, select=1),
140 '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."),
141 'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this partner if any.'),
142 '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."),
143 'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
144 'website': fields.char('Website',size=64, help="Website of Partner or Company"),
145 'comment': fields.text('Notes'),
146 'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'), # should be removed in version 7, but kept until then for backward compatibility
147 'category_id': fields.many2many('res.partner.category', 'res_partner_category_rel', 'partner_id', 'category_id', 'Tags'),
148 'credit_limit': fields.float(string='Credit Limit'),
149 'ean13': fields.char('EAN13', size=13),
150 'active': fields.boolean('Active'),
151 'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
152 '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."),
153 'employee': fields.boolean('Employee', help="Check this box if the partner is an Employee."),
154 'function': fields.char('Function', size=128),
155 'type': fields.selection( [('default','Default'),('invoice','Invoice'),
156 ('delivery','Delivery'), ('contact','Contact'),
158 'Address Type', help="Used to select automatically the right address according to the context in sales and purchases documents."),
159 'street': fields.char('Street', size=128),
160 'street2': fields.char('Street2', size=128),
161 'zip': fields.char('Zip', change_default=True, size=24),
162 'city': fields.char('City', size=128),
163 'state_id': fields.many2one("res.country.state", 'State', domain="[('country_id','=',country_id)]"),
164 'country_id': fields.many2one('res.country', 'Country'),
165 'country': fields.related('country_id', type='many2one', relation='res.country', string='Country'), # for backward compatibility
166 'email': fields.char('E-Mail', size=240),
167 'phone': fields.char('Phone', size=64),
168 'fax': fields.char('Fax', size=64),
169 'mobile': fields.char('Mobile', size=64),
170 'birthdate': fields.char('Birthdate', size=64),
171 'is_company': fields.boolean('Company', help="Check if the contact is a company, otherwise it is a person"),
172 'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information for this contact"),
173 'photo': fields.binary('Photo'),
174 'company_id': fields.many2one('res.company', 'Company', select=1),
175 'color': fields.integer('Color Index'),
176 'contact_address': fields.function(_address_display, type='char', string='Complete Address'),
179 def _default_category(self, cr, uid, context=None):
182 if context.get('category_id'):
183 return [context['category_id']]
186 def _get_photo(self, cr, uid, is_company, context=None):
188 path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'company_icon.png')
190 path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'photo.png')
191 return open(path, 'rb').read().encode('base64')
196 'category_id': _default_category,
197 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
201 'use_parent_address': True,
202 'photo': lambda self, cr, uid, context: self._get_photo(cr, uid, False, context),
205 def copy(self, cr, uid, id, default=None, context=None):
208 name = self.read(cr, uid, [id], ['name'], context)[0]['name']
209 default.update({'name': _('%s (copy)')%(name)})
210 return super(res_partner, self).copy(cr, uid, id, default, context)
212 def onchange_type(self, cr, uid, ids, is_company, context=None):
213 value = {'title': False,
214 'photo': self._get_photo(cr, uid, is_company, context)}
216 value['parent_id'] = False
217 domain = {'title': [('domain', '=', 'partner')]}
219 domain = {'title': [('domain', '=', 'contact')]}
220 return {'value': value, 'domain': domain}
222 def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
223 def value_or_id(val):
224 """ return val or val.id if val is a browse record """
225 return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
227 if use_parent_address and parent_id:
228 parent = self.browse(cr, uid, parent_id, context=context)
229 return {'value': dict((key, value_or_id(parent[key])) for key in ADDRESS_FIELDS)}
232 def _check_ean_key(self, cr, uid, ids, context=None):
233 for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
234 thisean=partner_o['ean13']
235 if thisean and thisean!='':
243 sum+=3*int(thisean[i])
244 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
248 # _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
250 def write(self, cr, uid, ids, vals, context=None):
251 # Update parent and siblings or children records
252 if isinstance(ids, (int, long)):
254 if vals.get('is_company')==False:
255 vals.update({'child_ids' : [(5,)]})
256 for partner in self.browse(cr, uid, ids, context=context):
258 if partner.is_company:
259 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
260 update_ids = self.search(cr, uid, domain_children, context=context)
261 elif partner.parent_id:
262 if vals.get('use_parent_address')==True:
263 domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
264 update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
265 if 'use_parent_address' not in vals and partner.use_parent_address:
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 self.update_address(cr, uid, update_ids, vals, context)
269 return super(res_partner,self).write(cr, uid, ids, vals, context=context)
271 def create(self, cr, uid, vals, context=None):
274 # Update parent and siblings records
275 if vals.get('parent_id') and vals.get('use_parent_address'):
276 domain_siblings = [('parent_id', '=', vals['parent_id']), ('use_parent_address', '=', True)]
277 update_ids = [vals['parent_id']] + self.search(cr, uid, domain_siblings, context=context)
278 self.update_address(cr, uid, update_ids, vals, context)
279 if 'photo' not in vals :
280 vals['photo'] = self._get_photo(cr, uid, vals.get('is_company', False) or context.get('default_is_company'), context)
281 return super(res_partner,self).create(cr, uid, vals, context=context)
283 def update_address(self, cr, uid, ids, vals, context=None):
284 addr_vals = dict((key, vals[key]) for key in POSTAL_ADDRESS_FIELDS if vals.get(key))
285 return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
287 def name_get(self, cr, uid, ids, context=None):
290 if isinstance(ids, (int, long)):
293 for record in self.browse(cr, uid, ids, context=context):
296 name = "%s (%s)" % (name, record.parent_id.name)
297 if context.get('show_address'):
298 name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
299 name = name.replace('\n\n','\n')
300 name = name.replace('\n\n','\n')
301 res.append((record.id, name))
304 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
307 if name and operator in ('=', 'ilike', '=ilike', 'like'):
308 # search on the name of the contacts and of its company
309 name2 = operator == '=' and name or '%' + name + '%'
313 limit_str = ' limit %s'
314 query_args += [limit]
315 cr.execute('''SELECT partner.id FROM res_partner partner
316 LEFT JOIN res_partner company ON partner.parent_id = company.id
317 WHERE partner.name || ' (' || COALESCE(company.name,'') || ')'
318 ''' + operator + ''' %s ''' + limit_str, query_args)
319 ids = map(lambda x: x[0], cr.fetchall())
321 ids = self.search(cr, uid, [('id', 'in', ids)] + args, limit=limit, context=context)
323 return self.name_get(cr, uid, ids, context)
324 return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
326 def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
327 partners = self.browse(cr, uid, ids)
328 for partner in partners:
330 tools.email_send(email_from, [partner.email], subject, body, on_error)
333 def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
335 self.pool.get('ir.cron').create(cr, uid, {
336 'name': 'Send Partner Emails',
338 'model': 'res.partner',
339 'function': '_email_send',
340 'args': repr([ids[:16], email_from, subject, body, on_error])
345 def address_get(self, cr, uid, ids, adr_pref=None):
347 adr_pref = ['default']
349 # retrieve addresses from the partner itself and its children
351 # need to fix the ids ,It get False value in list like ids[False]
352 if ids and ids[0]!=False:
353 for p in self.browse(cr, uid, ids):
354 res.append((p.type, p.id))
355 res.extend((c.type, c.id) for c in p.child_ids)
356 address_dict = dict(reversed(res))
357 # get the id of the (first) default address if there is one,
358 # otherwise get the id of the first address in the list
359 default_address = False
361 default_address = address_dict.get('default', res[0][1])
363 result[adr] = address_dict.get(adr, default_address)
366 def gen_next_ref(self, cr, uid, ids):
370 # compute the next number ref
371 cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
372 res = cr.dictfetchall()
373 ref = res and res[0]['ref'] or '0'
377 raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
379 # update the current partner
380 cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
383 def view_header_get(self, cr, uid, view_id, view_type, context):
384 res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
386 if (not context.get('category_id', False)):
388 return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
390 def main_partner(self, cr, uid):
391 ''' Return the id of the main partner
393 model_data = self.pool.get('ir.model.data')
394 return model_data.browse(cr, uid,
395 model_data.search(cr, uid, [('module','=','base'),
396 ('name','=','main_partner')])[0],
399 def _display_address(self, cr, uid, address, without_company=False, context=None):
402 The purpose of this function is to build and return an address formatted accordingly to the
403 standards of the country where it belongs.
405 :param address: browse record of the res.partner.address to format
406 :returns: the address formatted in a display that fit its country habits (or the default ones
407 if not country is specified)
411 # get the information that will be injected into the display format
412 # get the address format
413 address_format = address.country_id and address.country_id.address_format or \
414 '%(company_name)s\n%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s'
416 'state_code': address.state_id and address.state_id.code or '',
417 'state_name': address.state_id and address.state_id.name or '',
418 'country_code': address.country_id and address.country_id.code or '',
419 'country_name': address.country_id and address.country_id.name or '',
420 'company_name': address.parent_id and address.parent_id.name or '',
422 address_field = ['title', 'street', 'street2', 'zip', 'city']
423 for field in address_field :
424 args[field] = getattr(address, field) or ''
426 args['company_name'] = ''
427 return address_format % args
431 # res.partner.address is deprecated; it is still there for backward compability only and will be removed in next version
432 class res_partner_address(osv.osv):
433 _table = "res_partner"
434 _name = 'res.partner.address'
435 _order = 'type, name'
437 'parent_id': fields.many2one('res.partner', 'Company', ondelete='set null', select=True),
438 'partner_id': fields.related('parent_id', type='many2one', relation='res.partner', string='Partner'), # for backward compatibility
439 '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."),
440 'function': fields.char('Function', size=128),
441 'title': fields.many2one('res.partner.title','Title'),
442 'name': fields.char('Contact Name', size=64, select=1),
443 'street': fields.char('Street', size=128),
444 'street2': fields.char('Street2', size=128),
445 'zip': fields.char('Zip', change_default=True, size=24),
446 'city': fields.char('City', size=128),
447 'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
448 'country_id': fields.many2one('res.country', 'Country'),
449 'email': fields.char('E-Mail', size=240),
450 'phone': fields.char('Phone', size=64),
451 'fax': fields.char('Fax', size=64),
452 'mobile': fields.char('Mobile', size=64),
453 'birthdate': fields.char('Birthdate', size=64),
454 'is_customer_add': fields.related('partner_id', 'customer', type='boolean', string='Customer'),
455 'is_supplier_add': fields.related('partner_id', 'supplier', type='boolean', string='Supplier'),
456 'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
457 'company_id': fields.many2one('res.company', 'Company',select=1),
458 'color': fields.integer('Color Index'),
463 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
468 def write(self, cr, uid, ids, vals, context=None):
469 logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
470 if 'partner_id' in vals:
471 vals['parent_id'] = vals.get('partner_id')
472 del(vals['partner_id'])
473 return self.pool.get('res.partner').write(cr, uid, ids, vals, context=context)
475 def create(self, cr, uid, vals, context=None):
476 logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
477 if 'partner_id' in vals:
478 vals['parent_id'] = vals.get('partner_id')
479 del(vals['partner_id'])
480 return self.pool.get('res.partner').create(cr, uid, vals, context=context)
482 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: