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