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