[Fix] base/res :fix write method for updation of field based on use_parent_address
[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         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
54         res = []
55         for record in reads:
56             name = record['name']
57             if record['parent_id']:
58                 name = record['parent_id'][1]+' / '+name
59             res.append((record['id'], name))
60         return res
61
62     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
63         if not args:
64             args=[]
65         if not context:
66             context={}
67         if name:
68             # Be sure name_search is symetric to name_get
69             name = name.split(' / ')[-1]
70             ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
71         else:
72             ids = self.search(cr, uid, args, limit=limit, context=context)
73         return self.name_get(cr, uid, ids, context)
74
75
76     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
77         res = self.name_get(cr, uid, ids, context=context)
78         return dict(res)
79
80     _description='Partner Categories'
81     _name = 'res.partner.category'
82     _columns = {
83         'name': fields.char('Category Name', required=True, size=64, translate=True),
84         'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
85         'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
86         'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
87         'active' : fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
88         'parent_left' : fields.integer('Left parent', select=True),
89         'parent_right' : fields.integer('Right parent', select=True),
90         'partner_ids': fields.many2many('res.partner', 'res_partner_category_rel', 'category_id', 'partner_id', 'Partners'),
91     }
92     _constraints = [
93         (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
94     ]
95     _defaults = {
96         'active' : lambda *a: 1,
97     }
98     _parent_store = True
99     _parent_order = 'name'
100     _order = 'parent_left'
101
102 class res_partner_title(osv.osv):
103     _name = 'res.partner.title'
104     _columns = {
105         'name': fields.char('Title', required=True, size=46, translate=True),
106         'shortcut': fields.char('Shortcut', required=True, size=16, translate=True),
107         'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
108     }
109     _order = 'name'
110
111 def _lang_get(self, cr, uid, context=None):
112     lang_pool = self.pool.get('res.lang')
113     ids = lang_pool.search(cr, uid, [], context=context)
114     res = lang_pool.read(cr, uid, ids, ['code', 'name'], context)
115     return [(r['code'], r['name']) for r in res] + [('','')]
116
117 POSTAL_ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
118 ADDRESS_FIELDS = POSTAL_ADDRESS_FIELDS + ('email', 'phone', 'fax', 'mobile', 'website', 'ref', 'lang')
119
120 class res_partner(osv.osv):
121     _description='Partner'
122     _name = "res.partner"
123     _order = "name"
124     _columns = {
125         'name': fields.char('Name', size=128, required=True, select=True),
126         'date': fields.date('Date', select=1),
127         'title': fields.many2one('res.partner.title','Title'),
128         'parent_id': fields.many2one('res.partner','Parent Partner'),
129         'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts'),
130         'ref': fields.char('Reference', size=64, select=1),
131         '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."),
132         'user_id': fields.many2one('res.users', 'Salesman', help='The internal user that is in charge of communicating with this partner if any.'),
133         '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."),
134         'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
135         'website': fields.char('Website',size=64, help="Website of Partner."),
136         'comment': fields.text('Notes'),
137         'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'),   # should be removed in version 7, but kept until then for backward compatibility
138         'category_id': fields.many2many('res.partner.category', 'res_partner_category_rel', 'partner_id', 'category_id', 'Categories'),
139         'events': fields.one2many('res.partner.event', 'partner_id', 'Events'),
140         'credit_limit': fields.float(string='Credit Limit'),
141         'ean13': fields.char('EAN13', size=13),
142         'active': fields.boolean('Active'),
143         'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
144         '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."),
145         'employee': fields.boolean('Employee', help="Check this box if the partner is an Employee."),
146         'function': fields.char('Function', size=128),
147         'type': fields.selection( [('default','Default'),('invoice','Invoice'),
148                                    ('delivery','Delivery'), ('contact','Contact'),
149                                    ('other','Other')],
150                    'Address Type', help="Used to select automatically the right address according to the context in sales and purchases documents."),
151         'street': fields.char('Street', size=128),
152         'street2': fields.char('Street2', size=128),
153         'zip': fields.char('Zip', change_default=True, size=24),
154         'city': fields.char('City', size=128),
155         'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
156         'country_id': fields.many2one('res.country', 'Country'),
157         'country': fields.related('country_id', type='many2one', relation='res.country', string='Country'),   # for backward compatibility
158         'email': fields.char('E-Mail', size=240),
159         'phone': fields.char('Phone', size=64),
160         'fax': fields.char('Fax', size=64),
161         'mobile': fields.char('Mobile', size=64),
162         'birthdate': fields.char('Birthdate', size=64),
163         'is_company': fields.boolean('Company', help="Check if the contact is a company, otherwise it is a person"),
164         'use_parent_address': fields.boolean('Use Company Address', help="Check to use the company's address"),
165         'photo': fields.binary('Photo'),
166         'company_id': fields.many2one('res.company', 'Company', select=1),
167         'color': fields.integer('Color Index'),
168     }
169
170     def _default_category(self, cr, uid, context=None):
171         if context is None:
172             context = {}
173         if context.get('category_id'):
174             return [context['category_id']]
175         return False
176
177     def _get_photo(self, cr, uid, is_company, context=None):
178         if is_company:
179             path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'company_icon.png')
180         else:
181             path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'photo.png')
182         return open(path, 'rb').read().encode('base64')
183
184     _defaults = {
185         'active': True,
186         'customer': True,
187         'category_id': _default_category,
188         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
189         'color': 0,
190         'is_company': False,
191         'type': 'default',
192         'use_parent_address': True,
193         'photo': lambda self, cr, uid, context: self._get_photo(cr, uid, False, context),
194     }
195
196     def copy(self, cr, uid, id, default=None, context=None):
197         if default is None:
198             default = {}
199         name = self.read(cr, uid, [id], ['name'], context)[0]['name']
200         default.update({'name': _('%s (copy)')%(name), 'events':[]})
201         return super(res_partner, self).copy(cr, uid, id, default, context)
202
203     def onchange_type(self, cr, uid, ids, is_company, context=None):
204         value = {'title': False,
205                  'photo': self._get_photo(cr, uid, is_company, context)}
206         if is_company:
207             value['parent_id'] = False
208             domain = {'title': [('domain', '=', 'partner')]}
209         else:
210             domain = {'title': [('domain', '=', 'contact')]}
211         return {'value': value, 'domain': domain}
212
213     def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
214         def value_or_id(val):
215             """ return val or val.id if val is a browse record """
216             return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
217
218         if use_parent_address and parent_id:
219             parent = self.browse(cr, uid, parent_id, context=context)
220             return {'value': dict((key, value_or_id(parent[key])) for key in ADDRESS_FIELDS)}
221         return {}
222
223     def _check_ean_key(self, cr, uid, ids, context=None):
224         for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
225             thisean=partner_o['ean13']
226             if thisean and thisean!='':
227                 if len(thisean)!=13:
228                     return False
229                 sum=0
230                 for i in range(12):
231                     if not (i % 2):
232                         sum+=int(thisean[i])
233                     else:
234                         sum+=3*int(thisean[i])
235                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
236                     return False
237         return True
238
239 #   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
240
241     def write(self, cr, uid, ids, vals, context=None):
242         # Update parent and siblings or children records
243         if isinstance(ids, (int, long)):
244             ids = [ids]
245         if vals.get('is_company')==False:
246             vals.update({'child_ids' : [(5,)]}) 
247         for partner in self.browse(cr, uid, ids, context=context):
248             update_ids = []
249             if partner.is_company:
250                 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
251                 update_ids = self.search(cr, uid, domain_children, context=context)
252             elif vals.get('use_parent_address') ==True and partner.parent_id:
253                 domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
254                 update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
255             self.update_address(cr, uid, update_ids, vals, context)
256         return super(res_partner,self).write(cr, uid, ids, vals, context=context)
257
258     def create(self, cr, uid, vals, context=None):
259         if context is None:
260             context={}
261         # Update parent and siblings records
262         if vals.get('parent_id') and vals.get('use_parent_address'):
263             domain_siblings = [('parent_id', '=', vals['parent_id']), ('use_parent_address', '=', True)]
264             update_ids = [vals['parent_id']] + self.search(cr, uid, domain_siblings, context=context)
265             self.update_address(cr, uid, update_ids, vals, context)
266         if 'photo' not in vals  :
267             vals['photo'] = self._get_photo(cr, uid, vals.get('is_company', False) or context.get('default_is_company'), context)
268         return super(res_partner,self).create(cr, uid, vals, context=context)
269
270     def update_address(self, cr, uid, ids, vals, context=None):
271         addr_vals = dict((key, vals[key]) for key in POSTAL_ADDRESS_FIELDS if vals.get(key))
272         return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
273
274     def name_get(self, cr, uid, ids, context=None):
275         if context is None:
276             context = {}
277         if not len(ids):
278             return []
279         if context.get('show_ref'):
280             rec_name = 'ref'
281         else:
282             rec_name = 'name'
283         reads = self.read(cr, uid, ids, [rec_name,'parent_id'], context=context)
284         res = []
285         for record in reads:
286             name = record.get('name', '/')
287             if record['parent_id']:
288                 name =  "%s (%s)"%(name, record['parent_id'][1])
289             res.append((record['id'], name))
290         return res
291
292     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
293         if not args:
294             args = []
295         if name and operator in ('=', 'ilike', '=ilike', 'like'):
296             # search on the name of the contacts and of its company
297             name2 = operator == '=' and name or '%' + name + '%'
298             cr.execute('''SELECT partner.id FROM res_partner partner 
299                           LEFT JOIN res_partner company ON partner.parent_id = company.id 
300                           WHERE partner.name || ' (' || COALESCE(company.name,'') || ')'
301                           ''' + operator + ''' %s ''', (name2,))
302             ids = map(lambda x: x[0], cr.fetchall())
303             if args:
304                 ids = self.search(cr, uid, [('id', 'in', ids)] + args, limit=limit, context=context)
305             if ids:
306                 return self.name_get(cr, uid, ids, context)
307         return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
308
309     def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
310         partners = self.browse(cr, uid, ids)
311         for partner in partners:
312             if partner.email:
313                 tools.email_send(email_from, [partner.email], subject, body, on_error)
314         return True
315
316     def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
317         while len(ids):
318             self.pool.get('ir.cron').create(cr, uid, {
319                 'name': 'Send Partner Emails',
320                 'user_id': uid,
321                 'model': 'res.partner',
322                 'function': '_email_send',
323                 'args': repr([ids[:16], email_from, subject, body, on_error])
324             })
325             ids = ids[16:]
326         return True
327
328     def address_get(self, cr, uid, ids, adr_pref=None):
329         if adr_pref is None:
330             adr_pref = ['default']
331         result = {}
332         # retrieve addresses from the partner itself and its children
333         res = []
334         # need to fix the ids ,It get  False value in list like ids[False]
335         if ids and ids[0]!=False:
336             for p in self.browse(cr, uid, ids):
337                 res.append((p.type, p.id))
338                 res.extend((c.type, c.id) for c in p.child_ids)
339         addr = dict(reversed(res))
340         # get the id of the (first) default address if there is one,
341         # otherwise get the id of the first address in the list
342         default_address = False
343         if res:
344             default_address = addr.get('default', res[0][1])
345         for adr in adr_pref:
346             result[adr] = addr.get(adr, default_address)
347         return result
348
349     def gen_next_ref(self, cr, uid, ids):
350         if len(ids) != 1:
351             return True
352
353         # compute the next number ref
354         cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
355         res = cr.dictfetchall()
356         ref = res and res[0]['ref'] or '0'
357         try:
358             nextref = int(ref)+1
359         except:
360             raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
361
362         # update the current partner
363         cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
364         return True
365
366     def view_header_get(self, cr, uid, view_id, view_type, context):
367         res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
368         if res: return res
369         if (not context.get('category_id', False)):
370             return False
371         return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
372
373     def main_partner(self, cr, uid):
374         ''' Return the id of the main partner
375         '''
376         model_data = self.pool.get('ir.model.data')
377         return model_data.browse(cr, uid,
378                             model_data.search(cr, uid, [('module','=','base'),
379                                                 ('name','=','main_partner')])[0],
380                 ).res_id
381
382     def _display_address(self, cr, uid, address, type, context=None):
383
384         '''
385         The purpose of this function is to build and return an address formatted accordingly to the
386         standards of the country where it belongs.
387
388         :param address: browse record of the res.partner.address to format
389         :returns: the address formatted in a display that fit its country habits (or the default ones
390             if not country is specified)
391         :rtype: string
392         '''
393
394         if type:
395             if address.is_company and address.child_ids:
396                 for child_id in address.child_ids:
397                     if child_id.type == type:
398                         address = child_id
399
400         # get the information that will be injected into the display format
401         # get the address format
402         address_format = address.country_id and address.country_id.address_format or \
403                                          '%(company_name)s\n%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s'
404         args = {
405             'state_code': address.state_id and address.state_id.code or '',
406             'state_name': address.state_id and address.state_id.name or '',
407             'country_code': address.country_id and address.country_id.code or '',
408             'country_name': address.country_id and address.country_id.name or '',
409             'company_name': address.parent_id and address.parent_id.name or '',
410         }
411         address_field = ['title', 'street', 'street2', 'zip', 'city']
412         for field in address_field :
413             args[field] = getattr(address, field) or ''
414
415         return address_format % args
416
417
418
419 # res.partner.address is deprecated; it is still there for backward compability only and will be removed in next version
420 class res_partner_address(osv.osv):
421     _table = "res_partner"
422     _name = 'res.partner.address'
423     _order = 'type, name'
424     _columns = {
425         'parent_id': fields.many2one('res.partner', 'Company', ondelete='set null', select=True),
426         'partner_id': fields.related('parent_id', type='many2one', relation='res.partner', string='Partner'),   # for backward compatibility
427         '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."),
428         'function': fields.char('Function', size=128),
429         'title': fields.many2one('res.partner.title','Title'),
430         'name': fields.char('Contact Name', size=64, select=1),
431         'street': fields.char('Street', size=128),
432         'street2': fields.char('Street2', size=128),
433         'zip': fields.char('Zip', change_default=True, size=24),
434         'city': fields.char('City', size=128),
435         'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
436         'country_id': fields.many2one('res.country', 'Country'),
437         'email': fields.char('E-Mail', size=240),
438         'phone': fields.char('Phone', size=64),
439         'fax': fields.char('Fax', size=64),
440         'mobile': fields.char('Mobile', size=64),
441         'birthdate': fields.char('Birthdate', size=64),
442         'is_customer_add': fields.related('partner_id', 'customer', type='boolean', string='Customer'),
443         'is_supplier_add': fields.related('partner_id', 'supplier', type='boolean', string='Supplier'),
444         'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
445         'company_id': fields.many2one('res.company', 'Company',select=1),
446         'color': fields.integer('Color Index'),
447     }
448
449     _defaults = {
450         'active': True,
451         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
452         'color': 0,
453         'type': 'default',
454     }
455
456     def write(self, cr, uid, ids, vals, context=None):
457         logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
458         if 'partner_id' in vals:
459             vals['parent_id'] = vals.get('partner_id')
460             del(vals['partner_id'])
461         return self.pool.get('res.partner').write(cr, uid, ids, vals, context=context)
462
463     def create(self, cr, uid, vals, context=None):
464         logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
465         if 'partner_id' in vals:
466             vals['parent_id'] = vals.get('partner_id')
467             del(vals['partner_id'])
468         return self.pool.get('res.partner').create(cr, uid, vals, context=context)
469
470 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: