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