[FIX] Use the context to use the language from the user
[odoo/odoo.git] / bin / addons / base / res / partner / partner.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 import math
24
25 from osv import fields,osv
26 import tools
27 import ir
28 import pooler
29
30 class res_partner_function(osv.osv):
31     _name = 'res.partner.function'
32     _description = 'Function of the contact'
33     _columns = {
34         'name': fields.char('Function name', size=64, required=True),
35         'code': fields.char('Code', size=8),
36     }
37     _order = 'name'
38 res_partner_function()
39
40
41 class res_payterm(osv.osv):
42     _description = 'Payment term'
43     _name = 'res.payterm'
44     _columns = {
45         'name': fields.char('Payment term (short name)', size=64),
46     }
47 res_payterm()
48
49 class res_partner_category(osv.osv):
50     def name_get(self, cr, uid, ids, context=None):
51         if not len(ids):
52             return []
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_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
63         res = self.name_get(cr, uid, ids, context=context)
64         return dict(res)
65
66     def _check_recursion(self, cr, uid, ids):
67         level = 100
68         while len(ids):
69             cr.execute('select distinct parent_id from res_partner_category where id in ('+','.join(map(str,ids))+')')
70             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
71             if not level:
72                 return False
73             level -= 1
74         return True
75
76     _description='Partner Categories'
77     _name = 'res.partner.category'
78     _columns = {
79         'name': fields.char('Category Name', required=True, size=64, translate=True),
80         'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True),
81         'complete_name': fields.function(_name_get_fnc, method=True, type="char", string='Name'),
82         'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Childs Category'),
83         'active' : fields.boolean('Active', help="The active field allows you to hide the category, without removing it."),
84     }
85     _constraints = [
86         (_check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
87     ]
88     _defaults = {
89         'active' : lambda *a: 1,
90     }
91     _order = 'parent_id,name'
92 res_partner_category()
93
94 class res_partner_title(osv.osv):
95     _name = 'res.partner.title'
96     _columns = {
97         'name': fields.char('Title', required=True, size=46, translate=True),
98         'shortcut': fields.char('Shortcut', required=True, size=16),
99         'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
100     }
101     _order = 'name'
102 res_partner_title()
103
104 def _contact_title_get(self, cr, uid, context={}):
105     obj = self.pool.get('res.partner.title')
106     ids = obj.search(cr, uid, [('domain', '=', 'contact')])
107     res = obj.read(cr, uid, ids, ['shortcut','name'], context)
108     return [(r['shortcut'], r['name']) for r in res] + [('','')]
109
110 def _partner_title_get(self, cr, uid, context={}):
111     obj = self.pool.get('res.partner.title')
112     ids = obj.search(cr, uid, [('domain', '=', 'partner')])
113     res = obj.read(cr, uid, ids, ['shortcut','name'], context)
114     return [(r['shortcut'], r['name']) for r in res]
115
116 def _lang_get(self, cr, uid, context={}):
117     obj = self.pool.get('res.lang')
118     ids = obj.search(cr, uid, [], context=context)
119     res = obj.read(cr, uid, ids, ['code', 'name'], context)
120     return [(r['code'], r['name']) for r in res] + [('','')]
121
122
123 class res_partner(osv.osv):
124     _description='Partner'
125     _name = "res.partner"
126     _order = "name"
127     _columns = {
128         'name': fields.char('Name', size=128, required=True, select=True),
129         'date': fields.date('Date', select=1),
130         'title': fields.selection(_partner_title_get, 'Title', size=32),
131         'parent_id': fields.many2one('res.partner','Main Company', select=2),
132         'child_ids': fields.one2many('res.partner', 'parent_id', 'Partner Ref.'),
133         'ref': fields.char('Code', size=64),
134         'lang': fields.selection(_lang_get, 'Language', size=5, 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."),
135         'user_id': fields.many2one('res.users', 'Dedicated Salesman', help='The internal user that is in charge of communicating with this partner if any.'),
136         '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."),
137         'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
138         'website': fields.char('Website',size=64),
139         'comment': fields.text('Notes'),
140         'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'),
141         'category_id': fields.many2many('res.partner.category', 'res_partner_category_rel', 'partner_id', 'category_id', 'Categories'),
142         'events': fields.one2many('res.partner.event', 'partner_id', 'Events'),
143         'credit_limit': fields.float(string='Credit Limit'),
144         'ean13': fields.char('EAN13', size=13),
145         'active': fields.boolean('Active'),
146         'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
147         '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."),
148         'city':fields.related('address','city',type='char', string='City'),
149         'country':fields.related('address','country_id',type='many2one', relation='res.country', string='Country'),
150     }
151
152     def _default_category(self, cr, uid, context={}):
153         if 'category_id' in context and context['category_id']:
154             return [context['category_id']]
155         return []
156
157     _defaults = {
158         'active': lambda *a: 1,
159         'customer': lambda *a: 1,
160         'category_id': _default_category,
161     }
162     _sql_constraints = [
163         ('name_uniq', 'unique (name)', 'The name of the partner must be unique !')
164     ]
165
166     def copy(self, cr, uid, id, default=None, context={}):
167         name = self.read(cr, uid, [id], ['name'])[0]['name']
168         default.update({'name': name+' (copy)'})
169         return super(res_partner, self).copy(cr, uid, id, default, context)
170
171     def _check_ean_key(self, cr, uid, ids):
172         for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
173             thisean=partner_o['ean13']
174             if thisean and thisean!='':
175                 if len(thisean)!=13:
176                     return False
177                 sum=0
178                 for i in range(12):
179                     if not (i % 2):
180                         sum+=int(thisean[i])
181                     else:
182                         sum+=3*int(thisean[i])
183                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
184                     return False
185         return True
186
187 #   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
188
189     def name_get(self, cr, uid, ids, context={}):
190         if not len(ids):
191             return []
192         if context.get('show_ref', False):
193             rec_name = 'ref'
194         else:
195             rec_name = 'name'
196
197         res = [(r['id'], r[rec_name]) for r in self.read(cr, uid, ids, [rec_name], context)]
198         return res
199
200     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=80):
201         if not args:
202             args=[]
203         if not context:
204             context={}
205         if name:
206             ids = self.search(cr, uid, [('ref', '=', name)] + args, limit=limit, context=context)
207             if not ids:
208                 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
209         else:
210             ids = self.search(cr, uid, args, limit=limit, context=context)
211         return self.name_get(cr, uid, ids, context)
212
213     def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
214         partners = self.browse(cr, uid, ids)
215         for partner in partners:
216             if len(partner.address):
217                 if partner.address[0].email:
218                     tools.email_send(email_from, [partner.address[0].email], subject, body, on_error)
219         return True
220
221     def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
222         while len(ids):
223             self.pool.get('ir.cron').create(cr, uid, {
224                 'name': 'Send Partner Emails',
225                 'user_id': uid,
226 #               'nextcall': False,
227                 'model': 'res.partner',
228                 'function': '_email_send',
229                 'args': repr([ids[:16], email_from, subject, body, on_error])
230             })
231             ids = ids[16:]
232         return True
233
234     def address_get(self, cr, uid, ids, adr_pref=['default']):
235         cr.execute('select type,id from res_partner_address where partner_id in ('+','.join(map(str,ids))+')')
236         res = cr.fetchall()
237         adr = dict(res)
238         # get the id of the (first) default address if there is one,
239         # otherwise get the id of the first address in the list
240         if res:
241             default_address = adr.get('default', res[0][1])
242         else:
243             default_address = False
244         result = {}
245         for a in adr_pref:
246             result[a] = adr.get(a, default_address)
247         return result
248
249     def gen_next_ref(self, cr, uid, ids):
250         if len(ids) != 1:
251             return True
252
253         # compute the next number ref
254         cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
255         res = cr.dictfetchall()
256         ref = res and res[0]['ref'] or '0'
257         try:
258             nextref = int(ref)+1
259         except:
260             raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
261
262         # update the current partner
263         cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
264         return True
265
266     def view_header_get(self, cr, uid, view_id, view_type, context):
267         res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
268         if res: return res
269         if (not context.get('category_id', False)):
270             return False
271         return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
272
273 res_partner()
274
275 class res_partner_address(osv.osv):
276     _description ='Partner Addresses'
277     _name = 'res.partner.address'
278     _order = 'id'
279     _columns = {
280         'partner_id': fields.many2one('res.partner', 'Partner', ondelete='set null', select=True, help="Keep empty for a private address, not related to partner."),
281         '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."),
282         'function': fields.many2one('res.partner.function', 'Function'),
283         'title': fields.selection(_contact_title_get, 'Title', size=32),
284         'name': fields.char('Contact Name', size=64),
285         'street': fields.char('Street', size=128),
286         'street2': fields.char('Street2', size=128),
287         'zip': fields.char('Zip', change_default=True, size=24),
288         'city': fields.char('City', size=128),
289         'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
290         'country_id': fields.many2one('res.country', 'Country'),
291         'email': fields.char('E-Mail', size=240),
292         'phone': fields.char('Phone', size=64),
293         'fax': fields.char('Fax', size=64),
294         'mobile': fields.char('Mobile', size=64),
295         'birthdate': fields.char('Birthdate', size=64),
296         'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
297     }
298     _defaults = {
299         'active': lambda *a: 1,
300     }
301
302     def name_get(self, cr, user, ids, context={}):
303         if not len(ids):
304             return []
305         res = []
306         for r in self.read(cr, user, ids, ['name','zip','city','partner_id', 'street']):
307             if context.get('contact_display', 'contact')=='partner':
308                 res.append((r['id'], r['partner_id'][1]))
309             else:
310                 addr = r['name'] or ''
311                 if r['name'] and (r['zip'] or r['city']):
312                     addr += ', '
313                 addr += (r['street'] or '') + ' ' + (r['zip'] or '') + ' ' + (r['city'] or '')
314                 res.append((r['id'], addr.strip() or '/'))
315         return res
316
317     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
318         if not args:
319             args=[]
320         if not context:
321             context={}
322         if context.get('contact_display', 'contact')=='partner':
323             ids = self.search(cr, user, [('partner_id',operator,name)], limit=limit, context=context)
324         else:
325             ids = self.search(cr, user, [('zip','=',name)] + args, limit=limit, context=context)
326             if not ids:
327                 ids = self.search(cr, user, [('city',operator,name)] + args, limit=limit, context=context)
328             if name:
329                 ids += self.search(cr, user, [('name',operator,name)] + args, limit=limit, context=context)
330                 ids += self.search(cr, user, [('partner_id',operator,name)] + args, limit=limit, context=context)
331         return self.name_get(cr, user, ids, context=context)
332
333     def get_city(self, cr, uid, id):
334         return self.browse(cr, uid, id).city
335
336 res_partner_address()
337
338 class res_partner_bank_type(osv.osv):
339     _description='Bank Account Type'
340     _name = 'res.partner.bank.type'
341     _columns = {
342         'name': fields.char('Name', size=64, required=True, translate=True),
343         'code': fields.char('Code', size=64, required=True),
344         'field_ids': fields.one2many('res.partner.bank.type.field', 'bank_type_id', 'Type fields'),
345     }
346 res_partner_bank_type()
347
348 class res_partner_bank_type_fields(osv.osv):
349     _description='Bank type fields'
350     _name = 'res.partner.bank.type.field'
351     _columns = {
352         'name': fields.char('Field name', size=64, required=True, translate=True),
353         'bank_type_id': fields.many2one('res.partner.bank.type', 'Bank type', required=True, ondelete='cascade'),
354         'required': fields.boolean('Required'),
355         'readonly': fields.boolean('Readonly'),
356         'size': fields.integer('Max. Size'),
357     }
358 res_partner_bank_type_fields()
359
360
361 class res_partner_bank(osv.osv):
362     '''Bank Accounts'''
363     _name = "res.partner.bank"
364     _rec_name = "acc_number"
365     _description = __doc__
366     _order = 'sequence'
367
368     def _bank_type_get(self, cr, uid, context=None):
369         bank_type_obj = self.pool.get('res.partner.bank.type')
370
371         result = []
372         type_ids = bank_type_obj.search(cr, uid, [])
373         bank_types = bank_type_obj.browse(cr, uid, type_ids, context=context)
374         for bank_type in bank_types:
375             result.append((bank_type.code, bank_type.name))
376         return result
377
378     def _default_value(self, cursor, user, field, context=None):
379         if field in ('country_id', 'state_id'):
380             value = False
381         else:
382             value = ''
383         if not context.get('address', False):
384             return value
385         for ham, spam, address in context['address']:
386             if address.get('type', False) == 'default':
387                 return address.get(field, value)
388             elif not address.get('type', False):
389                 value = address.get(field, value)
390         return value
391
392     _columns = {
393         'name': fields.char('Description', size=128),
394         'acc_number': fields.char('Account number', size=64, required=False),
395         'bank': fields.many2one('res.bank', 'Bank'),
396         'owner_name': fields.char('Account owner', size=64),
397         'street': fields.char('Street', size=128),
398         'zip': fields.char('Zip', change_default=True, size=24),
399         'city': fields.char('City', size=128),
400         'country_id': fields.many2one('res.country', 'Country',
401             change_default=True),
402         'state_id': fields.many2one("res.country.state", 'State',
403             change_default=True, domain="[('country_id','=',country_id)]"),
404         'partner_id': fields.many2one('res.partner', 'Partner', required=True,
405             ondelete='cascade', select=True),
406         'state': fields.selection(_bank_type_get, 'Bank type', required=True,
407             change_default=True),
408         'sequence': fields.integer('Sequence'),
409     }
410     _defaults = {
411         'owner_name': lambda obj, cursor, user, context: obj._default_value(
412             cursor, user, 'name', context=context),
413         'street': lambda obj, cursor, user, context: obj._default_value(
414             cursor, user, 'street', context=context),
415         'city': lambda obj, cursor, user, context: obj._default_value(
416             cursor, user, 'city', context=context),
417         'zip': lambda obj, cursor, user, context: obj._default_value(
418             cursor, user, 'zip', context=context),
419         'country_id': lambda obj, cursor, user, context: obj._default_value(
420             cursor, user, 'country_id', context=context),
421         'state_id': lambda obj, cursor, user, context: obj._default_value(
422             cursor, user, 'state_id', context=context),
423     }
424
425     def fields_get(self, cr, uid, fields=None, context=None):
426         res = super(res_partner_bank, self).fields_get(cr, uid, fields, context)
427         bank_type_obj = self.pool.get('res.partner.bank.type')
428         type_ids = bank_type_obj.search(cr, uid, [])
429         types = bank_type_obj.browse(cr, uid, type_ids)
430         for type in types:
431             for field in type.field_ids:
432                 if field.name in res:
433                     res[field.name].setdefault('states', {})
434                     res[field.name]['states'][type.code] = [
435                             ('readonly', field.readonly),
436                             ('required', field.required)]
437         return res
438
439     def name_get(self, cr, uid, ids, context=None):
440         if not len(ids):
441             return []
442         res = []
443         for id in self.browse(cr, uid, ids):
444             res.append((id.id,id.acc_number))
445         return res
446
447 res_partner_bank()
448
449
450
451 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
452