BASE: improve copy of res.partner
[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('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=[], operator='ilike', context={}):
59                 ids = self.search(cr, user, [('code','=',name)]+ args)
60                 if not ids:
61                         ids = self.search(cr, user, [('name',operator,name)]+ args)
62                 return self.name_get(cr, user, ids)
63         _order='code'
64 res_country()
65
66 class res_country_state(osv.osv):
67         _description="Country state"
68         _name = 'res.country.state'
69         _columns = {
70                 'country_id': fields.many2one('res.country', 'Country'),
71                 'name': fields.char('State Name', size=64),
72                 'code': fields.char('State Code', size=2),
73         }
74         _order = 'code'
75 res_country_state()
76
77 class res_payterm(osv.osv):
78         _description = 'Payment term'
79         _name = 'res.payterm'
80         _columns = {
81                 'name': fields.char('Payment term (short name)', size=64),
82         }
83 res_payterm()
84
85 class res_partner_category_type(osv.osv):
86         _description='Partner category types'
87         _name = 'res.partner.category.type'
88         _columns = {
89                 'name': fields.char('Category Name', required=True, size=64),
90         }
91         _order = 'name'
92 res_partner_category_type()
93
94 def _cat_type_get(self, cr, uid, context={}):
95         obj = self.pool.get('res.partner.category.type')
96         ids = obj.search(cr, uid, [])
97         res = obj.read(cr, uid, ids, ['name'], context)
98         return [(r['name'], r['name']) for r in res]
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                 'type_id': fields.many2one('res.partner.category.type', 'Category Type'),
131                 'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True),
132                 'complete_name': fields.function(_name_get_fnc, method=True, type="char", string='Name'),
133                 'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Childs Category'),
134                 'active' : fields.boolean('Active'),
135         }
136         _constraints = [
137                 (_check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
138         ]
139         _defaults = {
140                 'active' : lambda *a: 1,
141         }
142         _order = 'parent_id,name'
143 res_partner_category()
144
145 class res_partner_title(osv.osv):
146         _name = 'res.partner.title'
147         _columns = {
148                 'name': fields.char('Title', required=True, size=46, translate=True),
149                 'shortcut': fields.char('Shortcut', required=True, size=16),
150                 'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
151         }
152         _order = 'name'
153 res_partner_title()
154
155 def _contact_title_get(self, cr, uid, context={}):
156         obj = self.pool.get('res.partner.title')
157         ids = obj.search(cr, uid, [('domain', '=', 'contact')])
158         res = obj.read(cr, uid, ids, ['shortcut','name'], context)
159         return [(r['shortcut'], r['name']) for r in res]
160
161 def _partner_title_get(self, cr, uid, context={}):
162         obj = self.pool.get('res.partner.title')
163         ids = obj.search(cr, uid, [('domain', '=', 'partner')])
164         res = obj.read(cr, uid, ids, ['shortcut','name'], context)
165         return [(r['shortcut'], r['name']) for r in res]
166
167 def _lang_get(self, cr, uid, context={}):
168         obj = self.pool.get('res.lang')
169         ids = obj.search(cr, uid, [])
170         res = obj.read(cr, uid, ids, ['code', 'name'], context)
171         res = [(r['code'], r['name']) for r in res]
172         return res + [(False, '')]
173
174 class res_partner(osv.osv):
175         _description='Partner'
176         _name = "res.partner"
177         _order = "name"
178         _columns = {
179                 'name': fields.char('Name', size=128, required=True, select=True),
180                 'date': fields.date('Date'),
181                 'title': fields.selection(_partner_title_get, 'Title', size=32),
182                 'parent_id': fields.many2one('res.partner','Main Company', select=True),
183                 'child_ids': fields.one2many('res.partner', 'parent_id', 'Partner Ref.'),
184                 'ref': fields.char('Code', size=64),
185                 'lang': fields.selection(_lang_get, 'Language', size=5),
186                 'user_id': fields.many2one('res.users', 'Salesman'),
187                 'responsible': fields.many2one('res.users', 'Users'),
188                 'vat': fields.char('VAT',size=32),
189                 'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
190                 'website': fields.char('Website',size=64),
191                 'comment': fields.text('Notes'),
192                 'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'),
193                 'category_id': fields.many2many('res.partner.category', 'res_partner_category_rel', 'partner_id', 'category_id', 'Categories'),
194                 'events': fields.one2many('res.partner.event', 'partner_id', 'events'),
195                 'credit_limit': fields.float(string='Credit Limit'),
196                 'ean13': fields.char('EAN13', size=13),
197                 'active': fields.boolean('Active'),
198         }
199         _defaults = {
200                 'active': lambda *a: 1,
201         }
202         _sql_constraints = [
203                 ('name_uniq', 'unique (name)', 'The name of the partner must be unique !')
204         ]
205
206         def copy(self, cr, uid, id, default=None, context={}):
207                 name = self.read(cr, uid, [id], ['name'])[0]['name']
208                 default.update({'name': name+' (copy)'})
209                 return super(res_partner, self).copy(cr, uid, id, default, context)
210         
211         def _check_ean_key(self, cr, uid, ids):
212                 for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
213                         thisean=partner_o['ean13']
214                         if thisean and thisean!='':
215                                 if len(thisean)!=13:
216                                         return False
217                                 sum=0
218                                 for i in range(12):
219                                         if not (i % 2):
220                                                 sum+=int(thisean[i])
221                                         else:
222                                                 sum+=3*int(thisean[i])
223                                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
224                                         return False
225                 return True
226
227 #       _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
228
229         def name_get(self, cr, uid, ids, context={}):
230                 if not len(ids):
231                         return []
232                 if context.get('show_ref', False):
233                         rec_name = 'ref'
234                 else:
235                         rec_name = 'name'
236                         
237                 res = [(r['id'], r[rec_name]) for r in self.read(cr, uid, ids, [rec_name], context)]
238                 return res
239                 
240         def name_search(self, cr, uid, name, args=[], operator='ilike', context={}, limit=80):
241                 if name:
242                         ids = self.search(cr, uid, [('ref', '=', name)] + args, limit=limit)
243                         if not ids:
244                                 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit)
245                 else:
246                         ids = self.search(cr, uid, args, limit=limit)
247                 return self.name_get(cr, uid, ids, context)
248
249         def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
250                 partners = self.browse(cr, uid, ids)
251                 for partner in partners:
252                         if len(partner.address):
253                                 if partner.address[0].email:
254                                         tools.email_send(email_from, [partner.address[0].email], subject, body, on_error)
255                 return True
256
257         def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
258                 while len(ids):
259                         self.pool.get('ir.cron').create(cr, uid, {
260                                 'name': 'Send Partner Emails',
261                                 'user_id': uid,
262 #                               'nextcall': False,
263                                 'model': 'res.partner',
264                                 'function': '_email_send',
265                                 'args': repr([ids[:16], email_from, subject, body, on_error])
266                         })
267                         ids = ids[16:]
268                 return True
269                 
270         def address_get(self, cr, uid, ids, adr_pref=['default']):
271                 cr.execute('select type,id from res_partner_address where partner_id in ('+','.join(map(str,ids))+')')
272                 res = cr.fetchall()
273                 adr = dict(res)
274                 # get the id of the (first) default address if there is one, 
275                 # otherwise get the id of the first address in the list
276                 if res:
277                         default_address = adr.get('default', res[0][1])
278                 else:
279                         default_address = False
280                 result = {}
281                 for a in adr_pref:
282                         result[a] = adr.get(a, default_address)
283                 return result
284         
285         def gen_next_ref(self, cr, uid, ids):
286                 if len(ids) != 1:
287                         return True
288                         
289                 # compute the next number ref
290                 cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
291                 res = cr.dictfetchall()
292                 ref = res and res[0]['ref'] or '0'
293                 try:
294                         nextref = int(ref)+1
295                 except e:
296                         raise osv.except_osv('Warning', "Couldn't generate the next id because some partners have an alphabetic id !")
297
298                 # update the current partner
299                 cr.execute("update res_partner set ref=%d where id=%d", (nextref, ids[0]))
300                 return True
301 res_partner()
302
303
304 class res_partner_bank_type(osv.osv):
305         _description='Bank Account Type'
306         _name = 'res.partner.bank.type'
307         _columns = {
308                 'name': fields.char('Name', size=64, required=True),
309                 'code': fields.char('Code', size=64),
310                 'elec_pay': fields.char('Electronic Payment', size=64),
311         }
312 res_partner_bank_type()
313
314 class res_partner_bank(osv.osv):
315         _description='Bank Details'
316         _name = "res.partner.bank"
317         _order = "sequence"
318         _columns = {
319                 'name': fields.char('Account Name', size=64, required=True),
320                 'sequence': fields.integer('Sequence'),
321                 'number': fields.char('Account Number', size=64), #TODO : plan migration because of fields modifications
322                 'iban': fields.char('Account Iban', size=34), 
323                 'type_id' : fields.many2one('res.partner.bank.type', 'Account Type', required=True),
324                 'bank_name': fields.char('Bank Name', size=64),
325                 'bank_code': fields.char('Bank Code', size=64),
326                 'bank_guichet': fields.char('Branch', size=64),
327
328                 'street': fields.char('Street', size=128),
329                 'zip': fields.char('Zip', change_default=True, size=24),
330                 'city': fields.char('City', size=128),
331                 'country_id': fields.many2one('res.country', 'Country'),
332                 
333                 'partner_id': fields.many2one('res.partner', 'Partner', required=True, ondelete='cascade', select=True),
334                 'active': fields.boolean('Active'),
335         }
336         _defaults = {
337                 'active': lambda *a: 1,
338                 'type_id': lambda self,cr,uid,context : self.pool.get('res.partner.bank.type').search(cr, uid, [('name','=','Other')])[0],
339         }
340 res_partner_bank()
341
342
343 class res_partner_address(osv.osv):
344         _description ='Partner Contact'
345         _name = 'res.partner.address'
346         _order = 'id'
347         _columns = {
348                 'partner_id': fields.many2one('res.partner', 'Partner', required=True, ondelete='cascade', select=True),
349                 'type': fields.selection( [ ('default','Default'),('invoice','Invoice'), ('delivery','Delivery'), ('contact','Contact'), ('other','Other') ],'Address Type'),
350                 'function': fields.many2one('res.partner.function', 'Function', relate=True),
351                 'title': fields.selection(_contact_title_get, 'Title', size=32),
352                 'name': fields.char('Contact Name', size=64),
353                 'street': fields.char('Street', size=128),
354                 'street2': fields.char('Street2', size=128),
355                 'zip': fields.char('Zip', change_default=True, size=24),
356                 'city': fields.char('City', size=128),
357                 'state_id': fields.many2one("res.country.state", 'State', domain="[('country_id','=',country_id)]"),
358                 'country_id': fields.many2one('res.country', 'Country'),
359                 'email': fields.char('E-Mail', size=64),
360                 'phone': fields.char('Phone', size=64),
361                 'fax': fields.char('Fax', size=64),
362                 'mobile': fields.char('Mobile', size=64),
363                 'birthdate': fields.char('Birthdate', size=64),
364                 'active': fields.boolean('Active'),
365         }
366         _defaults = {
367                 'active': lambda *a: 1,
368         }
369
370         def name_get(self, cr, user, ids, context={}):
371                 if not len(ids):
372                         return []
373                 res = []
374                 for r in self.read(cr, user, ids, ['name','zip','city','partner_id']):
375                         if context.get('contact_display', 'contact')=='partner':
376                                 res.append((r['id'], r['partner_id'][1]))
377                         else:
378                                 addr = str(r['name'] or '')
379                                 if r['name'] and (r['zip'] or r['city']):
380                                         addr += ', '
381                                 addr += str(r['zip'] or '') + ' ' + str(r['city'] or '')
382                                 res.append((r['id'], addr))
383                 return res
384
385         def name_search(self, cr, user, name, args=[], operator='ilike', context={}, limit=80):
386                 if context.get('contact_display', 'contact')=='partner':
387                         ids = self.search(cr, user, [('partner_id',operator,name)], limit=limit)
388                 else:
389                         ids = self.search(cr, user, [('zip','=',name)] + args, limit=limit)
390                         if not ids: 
391                                 ids = self.search(cr, user, [('city',operator,name)] + args, limit=limit)
392                         if name:
393                                 ids += self.search(cr, user, [('name',operator,name)] + args, limit=limit)
394                                 ids += self.search(cr, user, [('partner_id',operator,name)] + args, limit=limit)
395                 return self.name_get(cr, user, ids)
396 res_partner_address()
397
398 # vim:noexpandtab: