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