[FIX] base: put back access rules related to res.partner.address (we must keep access...
[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             value['child_ids'] = [(5,)]
211             domain = {'title': [('domain', '=', 'contact')]}
212         return {'value': value, 'domain': domain}
213
214     def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
215         def value_or_id(val):
216             """ return val or val.id if val is a browse record """
217             return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
218
219         if use_parent_address and parent_id:
220             parent = self.browse(cr, uid, parent_id, context=context)
221             return {'value': dict((key, value_or_id(parent[key])) for key in ADDRESS_FIELDS)}
222         return {}
223
224     def _check_ean_key(self, cr, uid, ids, context=None):
225         for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
226             thisean=partner_o['ean13']
227             if thisean and thisean!='':
228                 if len(thisean)!=13:
229                     return False
230                 sum=0
231                 for i in range(12):
232                     if not (i % 2):
233                         sum+=int(thisean[i])
234                     else:
235                         sum+=3*int(thisean[i])
236                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
237                     return False
238         return True
239
240 #   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
241
242     def write(self, cr, uid, ids, vals, context=None):
243         # Update parent and siblings or children records
244         if isinstance(ids, (int, long)):
245             ids = [ids]
246         for partner in self.browse(cr, uid, ids, context=context):
247             update_ids = []
248             if partner.is_company:
249                 domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
250                 update_ids = self.search(cr, uid, domain_children, context=context)
251             elif partner.parent_id:
252                 domain_siblings = [('parent_id', '=', partner.parent_id.id), ('use_parent_address', '=', True)]
253                 update_ids = [partner.parent_id.id] + self.search(cr, uid, domain_siblings, context=context)
254             self.update_address(cr, uid, update_ids, vals, context)
255         return super(res_partner,self).write(cr, uid, ids, vals, context=context)
256
257     def create(self, cr, uid, vals, context=None):
258         if context is None:
259             context={}
260         # Update parent and siblings records
261         if vals.get('parent_id') and vals.get('use_parent_address'):
262             domain_siblings = [('parent_id', '=', vals['parent_id']), ('use_parent_address', '=', True)]
263             update_ids = [vals['parent_id']] + self.search(cr, uid, domain_siblings, context=context)
264             self.update_address(cr, uid, update_ids, vals, context)
265         if 'photo' not in vals  :
266             vals['photo'] = self._get_photo(cr, uid, vals.get('is_company', False) or context.get('default_is_company'), context)
267         return super(res_partner,self).create(cr, uid, vals, context=context)
268
269     def update_address(self, cr, uid, ids, vals, context=None):
270         addr_vals = dict((key, vals[key]) for key in POSTAL_ADDRESS_FIELDS if vals.get(key))
271         return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
272
273     def name_get(self, cr, uid, ids, context=None):
274         if context is None:
275             context = {}
276         if not len(ids):
277             return []
278         if context.get('show_ref'):
279             rec_name = 'ref'
280         else:
281             rec_name = 'name'
282         reads = self.read(cr, uid, ids, [rec_name,'parent_id'], context=context)
283         res = []
284         for record in reads:
285             name = record.get('name', '/')
286             if record['parent_id']:
287                 name =  "%s (%s)"%(name, record['parent_id'][1])
288             res.append((record['id'], name))
289         return res
290
291     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
292         if not args:
293             args = []
294         # short-circuit ref match when possible
295         if name and operator in ('=', 'ilike', '=ilike', 'like'):
296             ids = self.search(cr, uid, [('ref', '=', name)] + args, limit=limit, context=context)
297             if not ids:
298                 names = map(lambda x : x.strip(),name.split('('))
299                 for name in range(len(names)):
300                     domain = [('name', operator, names[name])]
301                     if name > 0:
302                         domain.extend([('id', 'child_of', ids)])
303                     ids = self.search(cr, uid, domain, limit=limit, context=context)
304                 contact_ids = ids
305                 while contact_ids:
306                     contact_ids = self.search(cr, uid, [('parent_id', 'in', contact_ids)], limit=limit, context=context)
307                     ids.extend(contact_ids)
308                 if args:
309                     ids = self.search(cr, uid, [('id', 'in', ids)] + args, limit=limit, context=context)
310             if ids:
311                 return self.name_get(cr, uid, ids, context)
312         return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
313
314     def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
315         partners = self.browse(cr, uid, ids)
316         for partner in partners:
317             if partner.email:
318                 tools.email_send(email_from, [partner.email], subject, body, on_error)
319         return True
320
321     def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
322         while len(ids):
323             self.pool.get('ir.cron').create(cr, uid, {
324                 'name': 'Send Partner Emails',
325                 'user_id': uid,
326                 'model': 'res.partner',
327                 'function': '_email_send',
328                 'args': repr([ids[:16], email_from, subject, body, on_error])
329             })
330             ids = ids[16:]
331         return True
332
333     def address_get(self, cr, uid, ids, adr_pref=None):
334         if adr_pref is None:
335             adr_pref = ['default']
336         result = {}
337         # retrieve addresses from the partner itself and its children
338         res = []
339         # need to fix the ids ,It get  False value in list like ids[False]
340         if ids and ids[0]!=False:
341             for p in self.browse(cr, uid, ids):
342                 res.append((p.type, p.id))
343                 res.extend((c.type, c.id) for c in p.child_ids)
344         addr = dict(reversed(res))
345         # get the id of the (first) default address if there is one,
346         # otherwise get the id of the first address in the list
347         default_address = False
348         if res:
349             default_address = addr.get('default', res[0][1])
350         for adr in adr_pref:
351             result[adr] = addr.get(adr, default_address)
352         return result
353
354     def gen_next_ref(self, cr, uid, ids):
355         if len(ids) != 1:
356             return True
357
358         # compute the next number ref
359         cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
360         res = cr.dictfetchall()
361         ref = res and res[0]['ref'] or '0'
362         try:
363             nextref = int(ref)+1
364         except:
365             raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
366
367         # update the current partner
368         cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
369         return True
370
371     def view_header_get(self, cr, uid, view_id, view_type, context):
372         res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
373         if res: return res
374         if (not context.get('category_id', False)):
375             return False
376         return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
377
378     def main_partner(self, cr, uid):
379         ''' Return the id of the main partner
380         '''
381         model_data = self.pool.get('ir.model.data')
382         return model_data.browse(cr, uid,
383                             model_data.search(cr, uid, [('module','=','base'),
384                                                 ('name','=','main_partner')])[0],
385                 ).res_id
386
387     def _display_address(self, cr, uid, address, type, context=None):
388         '''
389         The purpose of this function is to build and return an address formatted accordingly to the
390         standards of the country where it belongs.
391
392         :param address: browse record of the res.partner.address to format
393         :returns: the address formatted in a display that fit its country habits (or the default ones
394             if not country is specified)
395         :rtype: string
396         '''
397
398         if type:
399             if address.is_company and address.child_ids:
400                 for child_id in address.child_ids:
401                     if child_id.type == type:
402                         address = child_id
403
404         # get the information that will be injected into the display format
405         # get the address format
406         address_format = address.country_id and address.country_id.address_format or \
407                                          '%(company_name)s\n%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s'
408         args = {
409             'state_code': address.state_id and address.state_id.code or '',
410             'state_name': address.state_id and address.state_id.name or '',
411             'country_code': address.country_id and address.country_id.code or '',
412             'country_name': address.country_id and address.country_id.name or '',
413             'company_name': address.parent_id and address.parent_id.name or '',
414         }
415         address_field = ['title', 'street', 'street2', 'zip', 'city']
416         for field in address_field :
417             args[field] = getattr(address, field) or ''
418
419         return address_format % args
420
421
422
423 # res.partner.address is deprecated; it is still there for backward compability only and will be removed in next version
424 class res_partner_address(osv.osv):
425     _table = "res_partner"
426     _name = 'res.partner.address'
427     _order = 'type, name'
428     _columns = {
429         'parent_id': fields.many2one('res.partner', 'Company', ondelete='set null', select=True),
430         'partner_id': fields.related('parent_id', type='many2one', relation='res.partner', string='Partner'),   # for backward compatibility
431         '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."),
432         'function': fields.char('Function', size=128),
433         'title': fields.many2one('res.partner.title','Title'),
434         'name': fields.char('Contact Name', size=64, select=1),
435         'street': fields.char('Street', size=128),
436         'street2': fields.char('Street2', size=128),
437         'zip': fields.char('Zip', change_default=True, size=24),
438         'city': fields.char('City', size=128),
439         'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
440         'country_id': fields.many2one('res.country', 'Country'),
441         'email': fields.char('E-Mail', size=240),
442         'phone': fields.char('Phone', size=64),
443         'fax': fields.char('Fax', size=64),
444         'mobile': fields.char('Mobile', size=64),
445         'birthdate': fields.char('Birthdate', size=64),
446         'is_customer_add': fields.related('partner_id', 'customer', type='boolean', string='Customer'),
447         'is_supplier_add': fields.related('partner_id', 'supplier', type='boolean', string='Supplier'),
448         'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
449         'company_id': fields.many2one('res.company', 'Company',select=1),
450         'color': fields.integer('Color Index'),
451     }
452
453     _defaults = {
454         'active': True,
455         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
456         'color': 0,
457         'type': 'default',
458     }
459
460     def write(self, cr, uid, ids, vals, context=None):
461         logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
462         if 'partner_id' in vals:
463             vals['parent_id'] = vals.get('partner_id')
464             del(vals['partner_id'])
465         return self.pool.get('res.partner').write(cr, uid, ids, vals, context=context)
466
467     def create(self, cr, uid, vals, context=None):
468         logging.getLogger('res.partner').warning("Deprecated use of res.partner.address")
469         if 'partner_id' in vals:
470             vals['parent_id'] = vals.get('partner_id')
471             del(vals['partner_id'])
472         return self.pool.get('res.partner').create(cr, uid, vals, context=context)
473
474 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: