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