[MERGE]: Merge with latest trunk-server
[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 os
23 import math
24 from osv import osv, fields
25 import tools
26 from tools.translate import _
27 import logging
28 import pooler
29
30 class res_payterm(osv.osv):
31     _description = 'Payment term'
32     _name = 'res.payterm'
33     _order = 'name'
34     _columns = {
35         'name': fields.char('Payment Term (short name)', size=64),
36     }
37
38 class res_partner_category(osv.osv):
39
40     def name_get(self, cr, uid, ids, context=None):
41         """Return the categories' display name, including their direct
42            parent by default.
43
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
48                              the long version."""
49         if context is None:
50             context = {}
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)):
54             ids = [ids]
55         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
56         res = []
57         for record in reads:
58             name = record['name']
59             if record['parent_id']:
60                 name = record['parent_id'][1]+' / '+name
61             res.append((record['id'], name))
62         return res
63
64     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
65         if not args:
66             args=[]
67         if not context:
68             context={}
69         if name:
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)
73         else:
74             ids = self.search(cr, uid, args, limit=limit, context=context)
75         return self.name_get(cr, uid, ids, context)
76
77
78     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
79         res = self.name_get(cr, uid, ids, context=context)
80         return dict(res)
81
82     _description='Partner Categories'
83     _name = 'res.partner.category'
84     _columns = {
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', id1='category_id', id2='partner_id', string='Partners'),
93     }
94     _constraints = [
95         (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
96     ]
97     _defaults = {
98         'active' : lambda *a: 1,
99     }
100     _parent_store = True
101     _parent_order = 'name'
102     _order = 'parent_left'
103
104 class res_partner_title(osv.osv):
105     _name = 'res.partner.title'
106     _columns = {
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)
110     }
111     _order = 'name'
112
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] + [('','')]
118
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')
121
122 class res_partner(osv.osv):
123     _description='Partner'
124     _name = "res.partner"
125
126     def _address_display(self, cr, uid, ids, name, args, context=None):
127         res={}
128         for partner in self.browse(cr, uid, ids, context=context):
129             res[partner.id] =self._display_address(cr, uid, partner, context=context)
130         return res
131
132     _order = "name"
133     _columns = {
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', id1='partner_id', id2='category_id', string='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('Job Position', size=128),
155         'type': fields.selection( [('default','Default'),('invoice','Invoice'),
156                                    ('delivery','Delivery'), ('contact','Contact'),
157                                    ('other','Other')],
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('Email', 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'),
177     }
178
179     def _default_category(self, cr, uid, context=None):
180         if context is None:
181             context = {}
182         if context.get('category_id'):
183             return [context['category_id']]
184         return False
185
186     def _get_photo(self, cr, uid, is_company, context=None):
187         if is_company:
188             path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'company_icon.png')
189         else:
190             path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'photo.png')
191         return open(path, 'rb').read().encode('base64')
192
193     _defaults = {
194         'active': True,
195         'customer': True,
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),
198         'color': 0,
199         'is_company': False,
200         'type': 'default',
201         'use_parent_address': True,
202         'photo': lambda self, cr, uid, context: self._get_photo(cr, uid, False, context),
203     }
204
205     def copy(self, cr, uid, id, default=None, context=None):
206         if default is None:
207             default = {}
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)
211
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)}
215         if is_company:
216             value['parent_id'] = False
217             domain = {'title': [('domain', '=', 'partner')]}
218         else:
219             domain = {'title': [('domain', '=', 'contact')]}
220         return {'value': value, 'domain': domain}
221
222     def get_parent_address(self, cr, uid, parent_id, address_fields=POSTAL_ADDRESS_FIELDS, 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
226         parent = self.browse(cr, uid, parent_id, context=context)
227         return dict((key, value_or_id(parent[key])) for key in address_fields)
228  
229     def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
230          if use_parent_address and parent_id:
231             return {'value': self.get_parent_address(cr, uid, parent_id, address_fields=ADDRESS_FIELDS, context=context)}
232          return {}
233
234     def _check_ean_key(self, cr, uid, ids, context=None):
235         for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
236             thisean=partner_o['ean13']
237             if thisean and thisean!='':
238                 if len(thisean)!=13:
239                     return False
240                 sum=0
241                 for i in range(12):
242                     if not (i % 2):
243                         sum+=int(thisean[i])
244                     else:
245                         sum+=3*int(thisean[i])
246                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
247                     return False
248         return True
249
250 #   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
251
252     def write(self, cr, uid, ids, vals, context=None):
253         # Update parent and siblings or children records
254         if isinstance(ids, (int, long)):
255             ids = [ids]
256         if vals.get('is_company')==False:
257             vals.update({'child_ids' : [(5,)]})
258         for partner in self.browse(cr, uid, ids, context=context):
259             update_ids = []
260             if partner.is_company:
261                 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
262                 update_ids = self.search(cr, uid, domain_children, context=context)
263             elif partner.parent_id:
264                  if vals.get('use_parent_address')==True:
265                      domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
266                      update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
267                  if 'use_parent_address' not in vals and  partner.use_parent_address:
268                     domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
269                     update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
270             self.update_address(cr, uid, update_ids, vals, context)
271         return super(res_partner,self).write(cr, uid, ids, vals, context=context)
272
273     def create(self, cr, uid, vals, context=None):
274         if context is None:
275             context={}
276         # Update parent and siblings records
277         if vals.get('parent_id') and vals.get('use_parent_address'):
278             # [RPA] why we need to change the siblings? 
279             # we are creating a child of parent and it should not affect parent and siblings
280             # domain_siblings = [('parent_id', '=', vals['parent_id']), ('use_parent_address', '=', True)]
281             # update_ids = [vals['parent_id']] + self.search(cr, uid, domain_siblings, context=context)
282             # [RPA] the vals we pass in update_address is not of parent so it will do nothing
283             # self.update_address(cr, uid, update_ids, vals, context)
284             vals.update(self.get_parent_address(cr, uid, vals['parent_id'], address_fields=ADDRESS_FIELDS, context=context))
285         if 'photo' not in vals  :
286             vals['photo'] = self._get_photo(cr, uid, vals.get('is_company', False) or context.get('default_is_company'), context)
287         return super(res_partner,self).create(cr, uid, vals, context=context)
288
289     def update_address(self, cr, uid, ids, vals, context=None):
290         addr_vals = dict((key, vals[key]) for key in POSTAL_ADDRESS_FIELDS if vals.get(key))
291         return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
292
293     def name_get(self, cr, uid, ids, context=None):
294         if context is None:
295             context = {}
296         if isinstance(ids, (int, long)):
297             ids = [ids]
298         res = []
299         for record in self.browse(cr, uid, ids, context=context):
300             name = record.name
301             if record.parent_id:
302                 name =  "%s (%s)" % (name, record.parent_id.name)
303             if context.get('show_address'):
304                 name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
305                 name = name.replace('\n\n','\n')
306                 name = name.replace('\n\n','\n')
307             res.append((record.id, name))
308         return res
309
310     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
311         if not args:
312             args = []
313         if name and operator in ('=', 'ilike', '=ilike', 'like'):
314             # search on the name of the contacts and of its company
315             name2 = operator == '=' and name or '%' + name + '%'
316             limit_str = ''
317             query_args = [name2]
318             if limit:
319                 limit_str = ' limit %s'
320                 query_args += [limit]
321             cr.execute('''SELECT partner.id FROM res_partner partner
322                           LEFT JOIN res_partner company ON partner.parent_id = company.id
323                           WHERE partner.name || ' (' || COALESCE(company.name,'') || ')'
324                           ''' + operator + ''' %s ''' + limit_str, query_args)
325             ids = map(lambda x: x[0], cr.fetchall())
326             if args:
327                 ids = self.search(cr, uid, [('id', 'in', ids)] + args, limit=limit, context=context)
328             if ids:
329                 return self.name_get(cr, uid, ids, context)
330         return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
331
332     def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
333         partners = self.browse(cr, uid, ids)
334         for partner in partners:
335             if partner.email:
336                 tools.email_send(email_from, [partner.email], subject, body, on_error)
337         return True
338
339     def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
340         while len(ids):
341             self.pool.get('ir.cron').create(cr, uid, {
342                 'name': 'Send Partner Emails',
343                 'user_id': uid,
344                 'model': 'res.partner',
345                 'function': '_email_send',
346                 'args': repr([ids[:16], email_from, subject, body, on_error])
347             })
348             ids = ids[16:]
349         return True
350
351     def address_get(self, cr, uid, ids, adr_pref=None):
352         if adr_pref is None:
353             adr_pref = ['default']
354         result = {}
355         # retrieve addresses from the partner itself and its children
356         res = []
357         # need to fix the ids ,It get False value in list like ids[False]
358         if ids and ids[0]!=False:
359             for p in self.browse(cr, uid, ids):
360                 res.append((p.type, p.id))
361                 res.extend((c.type, c.id) for c in p.child_ids)
362         address_dict = dict(reversed(res))
363         # get the id of the (first) default address if there is one,
364         # otherwise get the id of the first address in the list
365         default_address = False
366         if res:
367             default_address = address_dict.get('default', res[0][1])
368         for adr in adr_pref:
369             result[adr] = address_dict.get(adr, default_address)
370         return result
371
372     def gen_next_ref(self, cr, uid, ids):
373         if len(ids) != 1:
374             return True
375
376         # compute the next number ref
377         cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
378         res = cr.dictfetchall()
379         ref = res and res[0]['ref'] or '0'
380         try:
381             nextref = int(ref)+1
382         except:
383             raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
384
385         # update the current partner
386         cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
387         return True
388
389     def view_header_get(self, cr, uid, view_id, view_type, context):
390         res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
391         if res: return res
392         if (not context.get('category_id', False)):
393             return False
394         return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
395
396     def main_partner(self, cr, uid):
397         ''' Return the id of the main partner
398         '''
399         model_data = self.pool.get('ir.model.data')
400         return model_data.browse(cr, uid,
401                             model_data.search(cr, uid, [('module','=','base'),
402                                                 ('name','=','main_partner')])[0],
403                 ).res_id
404
405     def _display_address(self, cr, uid, address, without_company=False, context=None):
406
407         '''
408         The purpose of this function is to build and return an address formatted accordingly to the
409         standards of the country where it belongs.
410
411         :param address: browse record of the res.partner.address to format
412         :returns: the address formatted in a display that fit its country habits (or the default ones
413             if not country is specified)
414         :rtype: string
415         '''
416
417         # get the information that will be injected into the display format
418         # get the address format
419         address_format = address.country_id and address.country_id.address_format or \
420                                          '%(company_name)s\n%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s'
421         args = {
422             'state_code': address.state_id and address.state_id.code or '',
423             'state_name': address.state_id and address.state_id.name or '',
424             'country_code': address.country_id and address.country_id.code or '',
425             'country_name': address.country_id and address.country_id.name or '',
426             'company_name': address.parent_id and address.parent_id.name or '',
427         }
428         address_field = ['title', 'street', 'street2', 'zip', 'city']
429         for field in address_field :
430             args[field] = getattr(address, field) or ''
431         if without_company:
432             args['company_name'] = ''
433         return address_format % args
434
435
436
437 # res.partner.address is deprecated; it is still there for backward compability only and will be removed in next version
438 class res_partner_address(osv.osv):
439     _table = "res_partner"
440     _name = 'res.partner.address'
441     _order = 'type, name'
442     _columns = {
443         'parent_id': fields.many2one('res.partner', 'Company', ondelete='set null', select=True),
444         'partner_id': fields.related('parent_id', type='many2one', relation='res.partner', string='Partner'),   # for backward compatibility
445         '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."),
446         'function': fields.char('Function', size=128),
447         'title': fields.many2one('res.partner.title','Title'),
448         'name': fields.char('Contact Name', size=64, select=1),
449         'street': fields.char('Street', size=128),
450         'street2': fields.char('Street2', size=128),
451         'zip': fields.char('Zip', change_default=True, size=24),
452         'city': fields.char('City', size=128),
453         'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
454         'country_id': fields.many2one('res.country', 'Country'),
455         'email': fields.char('Email', size=240),
456         'phone': fields.char('Phone', size=64),
457         'fax': fields.char('Fax', size=64),
458         'mobile': fields.char('Mobile', size=64),
459         'birthdate': fields.char('Birthdate', size=64),
460         'is_customer_add': fields.related('partner_id', 'customer', type='boolean', string='Customer'),
461         'is_supplier_add': fields.related('partner_id', 'supplier', type='boolean', string='Supplier'),
462         'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
463         'company_id': fields.many2one('res.company', 'Company',select=1),
464         'color': fields.integer('Color Index'),
465     }
466
467     _defaults = {
468         'active': True,
469         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
470         'color': 0,
471         'type': 'default',
472     }
473
474     def write(self, cr, uid, ids, vals, context=None):
475         logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
476         if 'partner_id' in vals:
477             vals['parent_id'] = vals.get('partner_id')
478             del(vals['partner_id'])
479         return self.pool.get('res.partner').write(cr, uid, ids, vals, context=context)
480
481     def create(self, cr, uid, vals, context=None):
482         logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
483         if 'partner_id' in vals:
484             vals['parent_id'] = vals.get('partner_id')
485             del(vals['partner_id'])
486         return self.pool.get('res.partner').create(cr, uid, vals, context=context)
487
488 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: