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