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