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