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