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