~vauxoo/account-management/hbto_acc_mng_v6_fnctl_field

« back to all changes in this revision

Viewing changes to account_management/model/account_partner.py

  • Committer: Miguel Delgado
  • Date: 2011-11-19 22:11:06 UTC
  • Revision ID: miguel.delgado07@gmail.com-20111119221106-y2bh2g11y48vhzn4

[IMP] se migraron todas las funcionalidades que se encontraban en este modulo
de version 5.0 a version 6.0 para tenerlas disponibles en esta version 

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# -*- encoding: utf-8 -*-
2
2
##############################################################################
3
3
#
4
 
#    OpenERP, Open Source Management Solution    
 
4
#    OpenERP, Open Source Management Solution
5
5
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6
 
#    author.name@company.com
 
6
#    humbertoarocha@gmail.com
 
7
#    Creditos Compartidos con
 
8
#    Copyright (c) 2009 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
 
9
#                       Jordi Esteve <jesteve@zikzakmedia.com>
7
10
#
8
11
#    This program is free software: you can redistribute it and/or modify
9
12
#    it under the terms of the GNU General Public License as published by
21
24
##############################################################################
22
25
from osv import osv
23
26
from osv import fields
24
 
from tools.translate import _
25
 
 
26
 
__HELP__=_('''
27
 
            Enter the pattern of the accounts, for example:
28
 
            Class:           1,
29
 
            Group:           122,
30
 
            Accounts:         122333,
31
 
            Sub-Accounts:      122333444,
32
 
            Accounts Aux.:    1223334445555
33
 
            Then type:  1, 122, 122333, 122333444, 122333444555
34
 
        ''')
35
 
 
36
 
__RES_PARTNER_ACCOUNT_HELP__ = _('''
37
 
This account is used to establish the father of the partners 
38
 
that have the classification this group, together with the sequence, 
39
 
so that if this account has a structure, 107003, then the partner, 
40
 
you have this classification, will have an account as which is 1070030005, 
41
 
if the pattern of accounts in the company is:
 
27
 
 
28
 
 
29
__AYUDA__ = '''
 
30
Escriba el Patron de las cuentas, su estructura, por ejemplo:
 
31
Clase:           1,
 
32
Grupo:           122,
 
33
Cuentas:         122333,
 
34
Subcuentas:      122333444,
 
35
Cuentas Aux.:    1223334445555
 
36
Entonces escriba:  1, 122, 122333, 122333444, 122333444555
 
37
'''
 
38
 
 
39
 
 
40
__TIPO__ = [
 
41
            ('receivable','Cuenta x Cobrar'),
 
42
            ('payable','Cuenta x Pagar'),
 
43
            ]
 
44
 
 
45
__res_partner_account_help__ = '''
 
46
Esta cuenta se usará para establecer el padre
 
47
de los partners que tengan como clasificacion
 
48
este Grupo, en conjunto con la secuencia, de
 
49
tal manera que si esta cuenta tiene una estruc-
 
50
tura, 107003, entonces el partner, que tenga
 
51
esta clasificacion, tendra una cuenta como la
 
52
que sigue 1070030005, si el patron de cuentas
 
53
en la compañía es:
42
54
1, 122, 122333, 1223334444
43
 
 
44
 
It is noteworthy that the account that is selected here must be of the last in the pattern, 
45
 
which for this example is:
46
 
107003 and 122333 square with the provisions
47
 
 ''')
48
 
 
49
 
__RES_PARTNER_ACCOUNT_HELP_DEFAULT__ =_('''
50
 
This account will be established as the account book to use in case the company 
51
 
does not perform operations such as supplier or customer, depending on the case
52
 
 ''')
53
 
 
54
 
__TYPE__ = [
55
 
            ('receivable','Receivable'),
56
 
            ('payable','Payable'),
57
 
            ]
58
 
 
 
55
Es de notarse que la cuenta que aqui se sele-
 
56
cciona debe ser del tipo del ultimo en el pa-
 
57
tron, que para este ejemplo es:
 
58
107003 y cuadra con lo establecido 122333
 
59
 '''
 
60
__res_partner_account_help_default__ = '''
 
61
Esta cuenta se establecera como la cuenta con-
 
62
table a usar en el caso de que la empresa no -
 
63
realice operaciones como proveedor o como cliente,
 
64
dependiendo del caso
 
65
 '''
 
66
 
 
67
__ACC__ = {
 
68
            'customer':  ('property_account_receivable',   'account_kind_rec',       'Cuenta x Cobrar'),
 
69
            'supplier':  ('property_account_payable',      'account_kind_pay',       'Cuenta x Pagar'),
 
70
            }
 
71
 
59
72
class res_partner_account(osv.osv):
60
 
    """
61
 
    OpenERP Model : res_partner_account
62
 
    """
 
73
    _name = 'res.partner.account'
 
74
    _description = 'Partner Accounting Classification'
 
75
    _columns = {
 
76
        'name':fields.char(
 
77
            'Nombre',
 
78
            size = 128,
 
79
            required = True,
 
80
            readonly = False,),
 
81
        'property_account_partner': fields.property(
 
82
            'account.account',
 
83
            type='many2one',
 
84
            relation='account.account',
 
85
            string="Cuenta Anfitriona",
 
86
            method=True,
 
87
            view_load=True,
 
88
            domain="[('type', '=', 'view')]",
 
89
            help=__res_partner_account_help__,
 
90
            required=True,
 
91
            readonly=False),
 
92
        'property_account_partner_default': fields.property(
 
93
            'account.account',
 
94
            type='many2one',
 
95
            relation='account.account',
 
96
            string="Cuenta Contable por Defecto",
 
97
            method=True,
 
98
            view_load=True,
 
99
            domain="[('type', '!=', 'view'),('parent_id', '=', property_account_partner), ('company_id', '=', company_id), ('reconcile', '=', True), ('user_type', '=', user_type), ('type', '=', type),('auto', '=', True), ]",
 
100
            help=__res_partner_account_help_default__,
 
101
            required=True,
 
102
            readonly=False),
 
103
        'company_id':fields.many2one(
 
104
            'res.company',
 
105
            'Compañia',
 
106
            required = True),
 
107
        'user_type': fields.many2one(
 
108
            'account.account.type',
 
109
            'Tipo de Cuenta',
 
110
            required=True),
 
111
        'type': fields.selection(
 
112
            __TIPO__,
 
113
            'Tipo',
 
114
            readonly=False,
 
115
            required=True),
 
116
    }
 
117
    _sql_constraints = [
 
118
                        ('name_uniq','unique(name)', 'Otro registro ya tiene este nombre!'),
 
119
                        ('account_uniq','unique(property_account_partner)', 'Otro registro ya esta usando esta Cuenta!'),
 
120
                        ]
63
121
 
64
122
    def _check(self, cr, uid, vals):
65
 
        accounts=[vals['property_account_partner']]
 
123
        cuentas=[vals['property_account_partner']]
66
124
        pattern = self.pool.get('res.company').browse(cr, uid, vals['company_id']).pattern
67
 
        self.pool.get('res.company')._check_accounts(cr, uid, pattern, accounts)
68
 
 
 
125
        self.pool.get('res.company')._check_accounts(cr, uid, pattern, cuentas)
 
126
        #~ vals['name'] = self._get_name(cr, uid, cuentas)
69
127
        return vals
70
128
 
71
 
    def _get_name(self, cr, uid, accounts):
 
129
    def _get_name(self, cr, uid, cuentas):
72
130
        obj = self.pool.get('account.account')
73
 
        code = obj.browse(cr,uid,accounts[0]).code
74
 
        name = obj.browse(cr,uid,accounts[0]).name
75
 
        print "-...................-GETTING THE NAME"
76
 
        print u'%s %s'%(code, name)
77
 
 
 
131
        code = obj.browse(cr,uid,cuentas[0]).code
 
132
        name = obj.browse(cr,uid,cuentas[0]).name
78
133
        return u'%s %s'%(code, name)
79
134
 
80
135
    def create(self, cr, uid, vals, context=None):
81
136
        self._check(cr, uid, vals)
82
 
 
83
137
        return super(res_partner_account, self).create(cr, uid, vals, context)
84
138
 
85
139
    def write(self, cr, uid, ids, vals, context=None):
 
140
        if not vals.get('company_id',False):
 
141
            vals.update({'company_id':self.browse(cr, uid, ids[0],context=context).company_id.id})
86
142
        self._check(cr, uid, vals)
87
 
 
88
143
        return super(res_partner_account, self).write(cr, uid, ids, vals, context)
89
144
 
90
145
    def _get_account(self, cr, uid, kind_id, account_name, do_account=False, account_id=None, do_write=False, context=None):
96
151
        company_id =    obj.company_id.id
97
152
        user_type =     obj.user_type.id
98
153
        type =          obj.type
 
154
        
99
155
        aa_obj = self.pool.get('account.account')
100
156
        if do_write == False:
101
 
            account_id = aa_obj.create(cr, uid,{
102
 
                                                'auto': True,'name': u'%s - %s'%(parent_name.decode('utf-8').upper(), account_name.decode('utf-8').upper()),
103
 
                                                'user_type': user_type,'type': type,'company_id':company_id,'currency_mode':'current','active':True,
104
 
                                                'reconcile': True, 'parent_id':parent_id,
105
 
                                                })
 
157
            account_id = aa_obj.create(cr, uid, {
 
158
                                'auto': True,
 
159
                                'name': u'%s - %s'%(parent_name.decode('utf-8').upper(), account_name.decode('utf-8').upper()),
 
160
                                'user_type': user_type,
 
161
                                'type': type,
 
162
                                'company_id':company_id,
 
163
                                'currency_mode':'current',
 
164
                                'active': True,
 
165
                                'reconcile': True,
 
166
                                'parent_id':parent_id,
 
167
                            })
106
168
 
107
169
            return account_id
108
 
 
109
170
        else:
110
 
            values ={
111
 
                    'code': codigo,'name': u'%s - %s'%(parent_name.decode('utf-8').upper(), account_name.decode('utf-8').upper()),
112
 
                    'user_type': user_type,'company_id':company_id,'currency_mode':'current','active': True,'reconcile': True,'parent_id':parent_id,
113
 
                    }
114
 
 
 
171
            values = {
 
172
                                'code': codigo,
 
173
                                'name': u'%s - %s'%(parent_name.decode('utf-8').upper(), account_name.decode('utf-8').upper()),
 
174
                                'user_type': user_type,
 
175
                                'company_id':company_id,
 
176
                                'currency_mode':'current',
 
177
                                'active': True,
 
178
                                'reconcile': True,
 
179
                                'parent_id':parent_id,
 
180
                            }
115
181
            return True
116
 
 
117
 
 
118
 
    _name = 'res.partner.account'
119
 
    _description = 'Partner Accounting Classification'
120
 
    
121
 
    _columns = {
122
 
 
123
 
        'name':fields.char('Name',size = 128,required = True,readonly = False,),
124
 
        'property_account_partner': fields.property('account.account',type='many2one',relation='account.account',string="Host account",method=True,view_load=True,domain="[('type','=','view')]",help=__RES_PARTNER_ACCOUNT_HELP__,required=True,readonly=False),
125
 
        'property_account_partner_default': fields.property('account.account',type='many2one',relation='account.account',
126
 
            string="Accounting Default Account",method=True,view_load=True,domain="[('type','<>','view'),('parent_id','=',property_account_partner),('company_id','=',company_id),('reconcile','=',True),('user_type','=',user_type),('type','=',type),]",help=__RES_PARTNER_ACCOUNT_HELP_DEFAULT__,required=True,readonly=False),
127
 
            'company_id':fields.many2one('res.company','Company',required = True),
128
 
        'user_type': fields.many2one('account.account.type','Account type',required=True),
129
 
        'type': fields.selection(__TYPE__,'Type',readonly=False,required=True),
130
 
 
131
 
               }
132
 
 
133
 
_sql_constraints = [
134
 
                    ('name_uniq','unique(name)', 'Another record already has this name!'),
135
 
                    ('account_uniq','unique(property_account_partner)', 'Another record already used this Account!'),
136
 
                   ]
137
 
 
138
182
res_partner_account()
139
183
 
140
184
class res_partner(osv.osv):
 
185
    _inherit = 'res.partner'
 
186
 
 
187
    _columns = {
 
188
        'property_account_payable': fields.property(
 
189
            'account.account',
 
190
            type='many2one',
 
191
            relation='account.account',
 
192
            string="Account Payable",
 
193
            method=True,
 
194
            view_load=True,
 
195
            domain="[('type', '=', 'payable')]",
 
196
            help="This account will be used instead of the default one as the payable account for the current partner",
 
197
            required=False,
 
198
            readonly=False),
 
199
            
 
200
        'property_account_receivable': fields.property(
 
201
            'account.account',
 
202
            type='many2one',
 
203
            relation='account.account',
 
204
            string="Account Receivable",
 
205
            method=True,
 
206
            view_load=True,
 
207
            domain="[('type', '=', 'receivable')]",
 
208
            help="This account will be used instead of the default one as the receivable account for the current partner",
 
209
            required=False,
 
210
            readonly=False),
 
211
            
 
212
        'account_kind_rec':fields.property(
 
213
            'res.partner.account',
 
214
            type='many2one',
 
215
            relation='res.partner.account',
 
216
            string='Tipo de CxC',
 
217
            method=True,
 
218
            view_load=True,
 
219
            domain="[('type', '=', 'receivable')]",
 
220
            help="Este Concepto le permite generar las CxC para\nla empresa de acuerdo a la cuenta contable\ndel grupo en el cual se clasifica",
 
221
            required=False,
 
222
            readonly=False),
 
223
        'account_kind_pay':fields.property(
 
224
            'res.partner.account',
 
225
            type='many2one',
 
226
            relation='res.partner.account',
 
227
            string='Tipo de CxP',
 
228
            method=True,
 
229
            view_load=True,
 
230
            domain="[('type', '=', 'payable')]",
 
231
            help="Este Concepto le permite generar las CxP para\nla empresa de acuerdo a la cuenta contable\ndel grupo en el cual se clasifica",
 
232
            required=False,
 
233
            readonly=False),
 
234
    }
141
235
 
142
236
    def create(self, cr, uid, vals, context=None):
143
 
        rpa = self.pool.get('res.partner.account')
144
 
        vals['property_account_payable'] = rpa._get_account(cr, uid, vals['account_kind_pay'], vals['name'], vals['supplier'])
145
 
        vals['property_account_receivable'] = rpa._get_account(cr, uid, vals['account_kind_rec'], vals['name'], vals['customer'])
146
 
 
 
237
        if context is None:
 
238
            context = {}
 
239
        attributes = ['customer','supplier','name']
 
240
        previous_accounts = {}
 
241
        
 
242
        for k in __ACC__:
 
243
            attr = __ACC__[k][0]
 
244
            if not previous_accounts.has_key(attr):
 
245
                previous_accounts.update({attr:False})
 
246
        
 
247
        for k in __ACC__:
 
248
            attr = __ACC__[k][1]
 
249
            if not previous_accounts.has_key(attr):
 
250
                previous_accounts.update({attr:False})
 
251
        
 
252
        for attr in attributes:
 
253
            if not previous_accounts.has_key(attr):
 
254
                previous_accounts.update({attr:False})
 
255
        
 
256
        
 
257
        context.update({'previous_accounts':previous_accounts})
 
258
        
 
259
        
 
260
        #~ OBTENIENDO LAS CUENTAS CONTABLES QUE NO SE ACTUALIZARON
 
261
        for k in __ACC__:
 
262
            attr = __ACC__[k][0]
 
263
            if not vals.has_key(attr):
 
264
                vals.update({attr:False})
 
265
        
 
266
        for k in __ACC__:
 
267
            attr = __ACC__[k][1]
 
268
            if not vals.has_key(attr):
 
269
                vals.update({attr:False})
 
270
    
 
271
        for attr in attributes:
 
272
            if not vals.has_key(attr):
 
273
                vals.update({attr:False})
 
274
        vals.update(self._update_code(cr, uid, None, vals, context=context))
147
275
        return super(res_partner, self).create(cr, uid, vals, context)
148
276
 
149
 
    def _do_refresh(self, cr, uid, ids, vals, ctxt=None):
150
 
        def _check_default(kind, account, type):
151
 
            if kind and kind.property_account_partner_default and kind.property_account_partner_default.id == account.id:
 
277
    def _switch_accounts(self, cr, uid, ids, k,vals, context=None):
 
278
        prod_id = None
 
279
        if context is None:
 
280
            context={}
 
281
        
 
282
        aml_obj = self.pool.get('account.move.line')
 
283
        ai_obj = self.pool.get('account.invoice')
 
284
        avl_obj = self.pool.get('account.voucher.line')
 
285
    
 
286
        #~ NEEDS REVIEWS
 
287
        previous_accounts={}
 
288
        if context.get('previous_accounts',False):
 
289
            previous_accounts = context['previous_accounts']
 
290
        
 
291
        aml_ids = aml_obj.search(cr, uid, [('account_id','=',previous_accounts[__ACC__[k][0]]),('partner_id','in',ids)],context=context)
 
292
        ai_ids = ai_obj.search(cr, uid, [('account_id','=',previous_accounts[__ACC__[k][0]]),('partner_id','in',ids)],context=context)
 
293
        avl_ids = avl_obj.search(cr, uid, [('account_id','=',previous_accounts[__ACC__[k][0]]),('partner_id','in',ids)],context=context)
 
294
        
 
295
        if aml_ids: 
 
296
            cr.execute('UPDATE account_move_line SET account_id = %s WHERE id in (%s)'%(vals[__ACC__[k][0]],', '.join([str(i) for i in aml_ids])))
 
297
        
 
298
        if ai_ids:
 
299
            cr.execute('UPDATE account_invoice SET account_id = %s WHERE id in (%s)'%(vals[__ACC__[k][0]],', '.join([str(i) for i in ai_ids])))
 
300
        
 
301
        if avl_ids:
 
302
            cr.execute('UPDATE account_voucher_line SET account_id = %s WHERE id in (%s)'%(vals[__ACC__[k][0]],', '.join([str(i) for i in avl_ids])))
 
303
        
 
304
        return True 
 
305
 
 
306
    def _check_unique(self,cr,uid,ids,k,vals,context=None):
 
307
    
 
308
        if context is None:
 
309
            context={}
 
310
        previous_accounts={}
 
311
        if context.get('previous_accounts',False):
 
312
            previous_accounts=context['previous_accounts']
 
313
        
 
314
        pro_obj=self.pool.get('ir.property')
 
315
        
 
316
        part_ids=pro_obj.search(cr,uid,[('name','=',__ACC__[k][0]),('value_reference','=','account.account,%s'%previous_accounts[__ACC__[k][0]]),('res_id','like','res.partner,')])
 
317
        
 
318
        if len(part_ids)==1:
 
319
            return True
 
320
        else:
 
321
            return False
 
322
        
 
323
    def _drop_properties(self, cr, uid, ids, k, context=None):
 
324
        ir_prop_obj = self.pool.get('ir.property')
 
325
        if context is None:
 
326
            context={}
 
327
        if context.get('previous_accounts',False):
 
328
            previous_accounts = context['previous_accounts']
 
329
        
 
330
        res_id = '%s,%s'%('res.partner',ids[0])
 
331
        value_reference = '%s,%s'%('account.account',previous_accounts[__ACC__[k][0]])
 
332
        ir_prop_ids = ir_prop_obj.search(cr, uid, [('res_id','=',res_id),('value_reference','=',value_reference),('name','=',__ACC__[k][0])], context=context)
 
333
        ir_prop_obj.unlink(cr, uid, ir_prop_ids, context=context)
 
334
        
 
335
        return ir_prop_obj.search(cr, uid, [('value_reference','=',value_reference)])
 
336
    
 
337
    def _search_model(self, cr, uid, ids, model, acc, context=None):
 
338
        if context is None:
 
339
            context={}
 
340
        account_ids = self.pool.get('account.account').search(cr, uid, [('id', 'child_of', acc)])
 
341
        return self.pool.get(model).search(cr, uid, [('account_id', 'in', account_ids)]) and True or False
 
342
 
 
343
    def _unlink_account(self, cr, uid, ids, k, vals, context=None):
 
344
        if context is None:
 
345
            context={}
 
346
        if context.get('previous_accounts',False):
 
347
            previous_accounts = context['previous_accounts']
 
348
        else:
 
349
            previous_accounts={}
 
350
 
 
351
        if previous_accounts.get(__ACC__[k][0],False):
 
352
            model= 'account.move.line'
 
353
            aml= self._search_model(cr,uid,ids,model,[previous_accounts[__ACC__[k][0]]],context=context)
 
354
            model= 'account.invoice'
 
355
            ai= self._search_model(cr,uid,ids,model,[previous_accounts[__ACC__[k][0]]],context=context)
 
356
            model= 'account.voucher.line'
 
357
            avl= self._search_model(cr,uid,ids,model,[previous_accounts[__ACC__[k][0]]],context=context)
 
358
            properties = self._drop_properties(cr,uid,ids,k,context=context)
 
359
            if not any([aml,ai,avl,properties]):
 
360
                self.pool.get('account.account').unlink(cr,uid,[previous_accounts[__ACC__[k][0]]], context)
152
361
                return True
 
362
        return False
 
363
    
 
364
    def _assign_account(self,cr,uid,ids,k,vals, context=None):
 
365
        
 
366
        if context is None:
 
367
            context={}
 
368
        previous_accounts={}
 
369
        if context.get('previous_accounts',False):
 
370
            previous_accounts=context['previous_accounts']
 
371
        
 
372
        rpa = self.pool.get('res.partner.account')
 
373
        
 
374
        if self._check_unique(cr,uid,ids,k,vals,context=context):
 
375
            rpa_brw = rpa.browse(cr,uid,vals[__ACC__[k][1]])
 
376
            parent_id = getattr(rpa_brw,'property_account_partner').id
 
377
            parent_name = getattr(rpa_brw,'property_account_partner').name
 
378
            name = str(u'%s - %s'%(parent_name.decode('utf-8').upper(), vals['name'].decode('utf-8').upper())).encode('utf-8')
 
379
            self.pool.get('account.account').write(cr,uid,[previous_accounts[__ACC__[k][0]]],{'parent_id':parent_id,'auto':True,'name':name})
 
380
            vals[__ACC__[k][0]]=previous_accounts[__ACC__[k][0]]
 
381
        else:                        
 
382
            vals[__ACC__[k][0]] = rpa._get_account(cr, uid, vals.get(__ACC__[k][1],False), vals['name'], vals[k])
 
383
            self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
384
            self._unlink_account(cr,uid,ids,k,vals,context=context)
 
385
        
 
386
        return vals
 
387
    
 
388
    def _comparison(self,cr,uid,ids,k,vals, context=None):
 
389
        if context is None:
 
390
            context={}
 
391
        previous_accounts={}
 
392
        if context.get('previous_accounts',False):
 
393
            previous_accounts=context['previous_accounts']
 
394
        
 
395
        rpa = self.pool.get('res.partner.account')
 
396
        #~ This condition indicates if supplier/customer or not
 
397
        if vals.get(k,False):
 
398
            print 'ES %s' % k
 
399
            #~ This condition indicates accounting account was or not assigned
 
400
            if vals.get(__ACC__[k][1],False):
 
401
                if previous_accounts.get(__ACC__[k][1],False) == vals.get(__ACC__[k][1],False):
 
402
                    
 
403
                    if not previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
404
                        vals[__ACC__[k][0]] = rpa._get_account(cr, uid, vals.get(__ACC__[k][1],False), vals['name'], vals[k])
 
405
 
 
406
                    elif not previous_accounts.get(__ACC__[k][0],False) and vals.get(__ACC__[k][0],False):
 
407
                        vals[__ACC__[k][0]] = rpa._get_account(cr, uid, vals.get(__ACC__[k][1],False), vals['name'], vals[k])
 
408
 
 
409
                    elif previous_accounts.get(__ACC__[k][0],False) != vals.get(__ACC__[k][0],False):
 
410
                        
 
411
                        if self._check_unique(cr,uid,ids,k,vals,context=context):
 
412
                            vals[__ACC__[k][0]]=previous_accounts[__ACC__[k][0]]
 
413
                        else:
 
414
                            vals[__ACC__[k][0]] = rpa._get_account(cr, uid, vals.get(__ACC__[k][1],False), vals['name'], vals[k])
 
415
                            self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
416
                            self._unlink_account(cr,uid,ids,k,vals,context=context)
 
417
                    
 
418
                    elif previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
419
                        if self._check_unique(cr,uid,ids,k,vals,context=context):
 
420
                            vals[__ACC__[k][0]]=previous_accounts[__ACC__[k][0]]
 
421
                        else:                        
 
422
                            vals[__ACC__[k][0]] = rpa._get_account(cr, uid, vals.get(__ACC__[k][1],False), vals['name'], vals[k])
 
423
                            self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
424
                            self._unlink_account(cr,uid,ids,k,vals,context=context)
 
425
                            
 
426
                    elif previous_accounts.get(__ACC__[k][0],False) == vals.get(__ACC__[k][0],False):
 
427
                        vals = self._assign_account(cr,uid,ids,k,vals,context=context)
 
428
                    
 
429
                else:
 
430
                    
 
431
                    if not previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
432
                        vals[__ACC__[k][0]] = rpa._get_account(cr, uid, vals.get(__ACC__[k][1],False), vals['name'], vals[k])
 
433
 
 
434
                    elif not previous_accounts.get(__ACC__[k][0],False) and vals.get(__ACC__[k][0],False):
 
435
                        vals[__ACC__[k][0]] = rpa._get_account(cr, uid, vals.get(__ACC__[k][1],False), vals['name'], vals[k])
 
436
 
 
437
                    elif previous_accounts.get(__ACC__[k][0],False) != vals.get(__ACC__[k][0],False):
 
438
                        vals = self._assign_account(cr,uid,ids,k,vals,context=context)
 
439
                    
 
440
                    elif previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
441
                        vals = self._assign_account(cr,uid,ids,k,vals,context=context)
 
442
                            
 
443
                    elif previous_accounts.get(__ACC__[k][0],False) == vals.get(__ACC__[k][0],False):
 
444
                        vals = self._assign_account(cr,uid,ids,k,vals,context=context)
 
445
                    
153
446
            else:
154
 
                return False
155
 
        obj = self.browse(cr, uid, ids[0])
156
 
        aa_obj_pay = obj.property_account_payable
157
 
        aa_obj_rec = obj.property_account_receivable
158
 
        rpa = self.pool.get('res.partner.account')
159
 
        vals['name'] = vals['name'] if vals.has_key('name') else obj.name
160
 
        
161
 
        # FOR ACCOUNTS RECEIVABLE
162
 
        
163
 
        if not aa_obj_pay:  # Check if the account does not exist to create
164
 
            vals['account_kind_pay'] = vals['account_kind_pay'] if vals.has_key('account_kind_pay') else obj.account_kind_pay.id
165
 
            vals['supplier'] = vals['supplier'] if vals.has_key('supplier') else obj.supplier
166
 
            #Create the Account
167
 
            vals['property_account_payable'] = rpa._get_account(cr, uid, vals['account_kind_pay'], vals['name'], vals['supplier'])
168
 
        else:               #Check to see if there has been any change in status that implies a need to assign their own
169
 
                            #or reassign the generic account to another account, or reassign the account to another account group
170
 
            if vals.has_key('supplier') and vals['supplier']:
171
 
 
172
 
                #verify if the CxP has been assigned a partner that corresponds to the generic account of their initial classification
173
 
                if _check_default(obj.account_kind_pay, aa_obj_pay, 'property_account_payable'):
174
 
 
175
 
                    # The partner had a generic account in the CXP do not know if this update will change the type vals ['account_kind_pay']
176
 
 
177
 
                    # In this assignment we emerge from this doubt, which have been changed that there equal, we will have the appropriate value for vals ['account_kind_pay']
178
 
 
179
 
                    vals['account_kind_pay'] = vals['account_kind_pay'] if vals.has_key('account_kind_pay') else obj.account_kind_pay.id
180
 
                    vals['property_account_payable'] = rpa._get_account(cr, uid, vals['account_kind_pay'], vals['name'], vals['supplier'])
181
 
 
182
 
        if not aa_obj_rec:
183
 
            vals['account_kind_rec'] = vals['account_kind_rec'] if vals.has_key('account_kind_rec') else obj.account_kind_rec.id
184
 
            vals['customer'] = vals['customer'] if vals.has_key('customer') else obj.customer
185
 
            vals['property_account_receivable'] = rpa._get_account(cr, uid, vals['account_kind_rec'], vals['name'], vals['customer'])
186
 
 
 
447
                if not previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
448
                    raise osv.except_osv(('Atencion !'), ('La %s para este partner no puede ser nula')%(__ACC__[k][2]))
 
449
                elif not previous_accounts.get(__ACC__[k][0],False) and vals.get(__ACC__[k][0],False):
 
450
                    pass
 
451
                elif previous_accounts.get(__ACC__[k][0],False) != vals.get(__ACC__[k][0],False):
 
452
                    self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
453
                    self._unlink_account(cr,uid,ids,k,vals,context=context)
 
454
 
 
455
                elif previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
456
                    vals[__ACC__[k][0]]=previous_accounts[__ACC__[k][0]]
 
457
                        
 
458
                elif previous_accounts.get(__ACC__[k][0],False) == vals.get(__ACC__[k][0],False):
 
459
                    pass
 
460
            
187
461
        else:
188
 
            if vals.has_key('customer') and vals['customer']:
189
 
                if _check_default(obj.account_kind_rec, aa_obj_rec, 'property_account_receivable'):
190
 
                    vals['account_kind_rec'] = vals['account_kind_rec'] if vals.has_key('account_kind_rec') else obj.account_kind_rec.id
191
 
                    vals['property_account_receivable'] = rpa._get_account(cr, uid, vals['account_kind_rec'], vals['name'], vals['customer'])
192
 
 
193
 
        return vals
194
 
 
 
462
            if vals.get(__ACC__[k][1],False):
 
463
                if previous_accounts.get(__ACC__[k][1],False) == vals.get(__ACC__[k][1],False):
 
464
                    if not previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
465
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
466
                    elif not previous_accounts.get(__ACC__[k][0],False) and vals.get(__ACC__[k][0],False):
 
467
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
468
                    elif previous_accounts.get(__ACC__[k][0],False) != vals.get(__ACC__[k][0],False):
 
469
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
470
                        self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
471
                        self._unlink_account(cr,uid,ids,k,vals,context=context)
 
472
                    
 
473
                    elif previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
474
                        vals[__ACC__[k][0]]=previous_accounts[__ACC__[k][0]]
 
475
 
 
476
                    elif previous_accounts.get(__ACC__[k][0],False) == vals.get(__ACC__[k][0],False):
 
477
                        
 
478
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
479
                        self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
480
                        self._unlink_account(cr,uid,ids,k,vals,context=context)
 
481
                    
 
482
                else:
 
483
                    if not previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
484
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
485
                    
 
486
                    elif not previous_accounts.get(__ACC__[k][0],False) and vals.get(__ACC__[k][0],False):
 
487
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
488
                    
 
489
                    elif previous_accounts.get(__ACC__[k][0],False) != vals.get(__ACC__[k][0],False):
 
490
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
491
                        self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
492
                        self._unlink_account(cr,uid,ids,k,vals,context=context)
 
493
                    
 
494
                    elif previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
495
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
496
                        self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
497
                        self._unlink_account(cr,uid,ids,k,vals,context=context)
 
498
                
 
499
                    elif previous_accounts.get(__ACC__[k][0],False) == vals.get(__ACC__[k][0],False):
 
500
                        vals[__ACC__[k][0]] = getattr(rpa.browse(cr,uid,vals[__ACC__[k][1]]),'property_account_partner_default').id
 
501
                        self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
502
                        self._unlink_account(cr,uid,ids,k,vals,context=context)
 
503
                    
 
504
            else:
 
505
                if not previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
506
                    raise osv.except_osv(('Atencion !'), ('La %s para este partner no puede ser nula')%(__ACC__[k][2]))
 
507
 
 
508
                elif not previous_accounts.get(__ACC__[k][0],False) and vals.get(__ACC__[k][0],False):
 
509
                    pass
 
510
 
 
511
                elif previous_accounts.get(__ACC__[k][0],False) != vals.get(__ACC__[k][0],False):
 
512
                    self._switch_accounts(cr,uid,ids,k,vals,context=context)
 
513
                    self._unlink_account(cr,uid,ids,k,vals,context=context)
 
514
 
 
515
                elif previous_accounts.get(__ACC__[k][0],False) and not vals.get(__ACC__[k][0],False):
 
516
                    raise osv.except_osv(('Atencion !'), ('La %s para este partner no puede ser nula')%(__ACC__[k][2]))
 
517
 
 
518
                elif previous_accounts.get(__ACC__[k][0],False) == vals.get(__ACC__[k][0],False):
 
519
                    pass
 
520
        return vals
 
521
 
 
522
    def _update_code(self, cr, uid,ids,vals, context=None):
 
523
        if context is None:
 
524
            context={}
 
525
        
 
526
        for k in __ACC__:
 
527
            vals = self._comparison(cr, uid,ids,k,vals,context=context)
 
528
        return vals
 
529
    
195
530
    def write(self, cr, uid, ids, vals, context=None):
196
 
        print 'account_partner write method, vals: ', vals
197
 
        if 'customer' in vals.keys() or 'supplier' in vals.keys() or 'account_kind_rec' in vals.keys() or 'account_kind_pay' in vals.keys(): 
198
 
            vals = self._do_refresh(cr, uid, ids, vals, context)
199
 
 
200
 
        return super(res_partner, self).write(cr, uid, ids, vals, context)
201
 
 
202
 
    _inherit = 'res.partner'
203
 
    _columns = {
204
 
 
205
 
        'property_account_payable': fields.property('account.account',type='many2one',relation='account.account',string="Account Payable",method=True,view_load=True,domain="[('type', '=', 'payable')]",help="This account will be used instead of the default one as the payable account for the current partner",required=False,readonly=True),
206
 
 
207
 
        'property_account_receivable': fields.property('account.account',type='many2one',relation='account.account', string="Account Receivable",method=True,view_load=True,domain="[('type', '=', 'receivable')]",help="This account will be used instead of the default one as the receivable account for the current partner",required=False,readonly=True),
208
 
 
209
 
        'account_kind_rec':fields.property('res.partner.account',type='many2one',relation='res.partner.account',string='Type of CxC',method=True,view_load=True,domain="[('type', '=', 'receivable')]",help="This concept allows you to generate CxC for\nthe company according to the accounting account\nof the group which is classified",required=True,readonly=False),
210
 
 
211
 
        'account_kind_pay':fields.property('res.partner.account',type='many2one',relation='res.partner.account',string='Type of CxP',method=True,view_load=True,domain="[('type', '=', 'payable')]",help="This concept allows you to generate CxP for\nthe company according to the accounting account\nof the group which is classified",required=True,readonly=False),
212
 
 
213
 
            }
214
 
 
215
 
 
 
531
        print 'vals en el write', vals
 
532
        if context is None:
 
533
            context = {}
 
534
        
 
535
        
 
536
        if not set(vals.keys()) & set(['customer','supplier' ,'property_account_receivable', 'property_account_payable' ,'account_kind_rec', 'account_kind_pay']):
 
537
            return super(res_partner, self).write(cr, uid, ids, vals, context)
 
538
        
 
539
        attributes = ['customer','supplier','name']
 
540
        self_brw = self.browse(cr,uid,ids[0],context)
 
541
        previous_accounts = {}
 
542
        
 
543
        
 
544
        for k in __ACC__:
 
545
            attr = __ACC__[k][0]
 
546
            if not previous_accounts.has_key(attr):
 
547
                previous_accounts.update({attr:getattr(self_brw,attr) and getattr(self_brw,attr).id})
 
548
        
 
549
        for k in __ACC__:
 
550
            attr = __ACC__[k][1]
 
551
            if not previous_accounts.has_key(attr):
 
552
                previous_accounts.update({attr:getattr(self_brw,attr) and getattr(self_brw,attr).id})
 
553
        
 
554
        for attr in attributes:
 
555
            if not previous_accounts.has_key(attr):
 
556
                previous_accounts.update({attr:getattr(self_brw, attr)})
 
557
        
 
558
        
 
559
        context.update({'previous_accounts':previous_accounts})
 
560
        
 
561
        
 
562
        #~ OBTENIENDO LAS CUENTAS CONTABLES QUE NO SE ACTUALIZARON
 
563
        for k in __ACC__:
 
564
            attr = __ACC__[k][0]
 
565
            if not vals.has_key(attr):
 
566
                vals.update({attr:getattr(self_brw, attr) and getattr(self_brw, attr).id})
 
567
        
 
568
        for k in __ACC__:
 
569
            attr = __ACC__[k][1]
 
570
            if not vals.has_key(attr):
 
571
                vals.update({attr:getattr(self_brw, attr) and getattr(self_brw, attr).id})
 
572
    
 
573
        for attr in attributes:
 
574
            if not vals.has_key(attr):
 
575
                vals.update({attr:getattr(self_brw, attr)})
 
576
                
 
577
        
 
578
        
 
579
        keys_in_vals = vals.keys()
 
580
        vals.update(self._update_code(cr, uid, ids, vals, context=context))
 
581
 
 
582
        valuex = {}
 
583
        for i in keys_in_vals:
 
584
            valuex[i]=vals[i]
 
585
        #~ res = super(product_template, self).write(cr, uid, ids, valuex, context)
 
586
        return super(res_partner, self).write(cr, uid, ids, valuex, context)
 
587
    
 
588
    def search_aml(self, cr, uid, id, context=None):
 
589
        if context is None:
 
590
            context = {}
 
591
        aml_obj = self.pool.get('account.move.line')
 
592
        return  aml_obj.search(cr, uid, [('partner_id','=',id)],context=context)
 
593
        
 
594
    
 
595
    def search_ai(self, cr, uid, id, context=None):
 
596
        if context is None:
 
597
            context = {}
 
598
        ai_obj = self.pool.get('account.invoice')
 
599
        return ai_obj.search(cr, uid, [('partner_id','=',id)],context=context)
 
600
        
 
601
            
 
602
    def search_so(self, cr, uid, id, context=None):
 
603
        if context is None:
 
604
            context = {}
 
605
        so_obj = self.pool.get('sale.order')
 
606
        return so_obj.search(cr, uid, [('partner_id','=',id)],context=context)
 
607
    
 
608
    def search_po(self, cr, uid, id, context=None):
 
609
        if context is None:
 
610
            context = {}
 
611
        po_obj = self.pool.get('purchase.order')
 
612
        return po_obj.search(cr, uid, [('partner_id','=',id)],context=context)
 
613
        
 
614
    def search_avl(self, cr, uid, id, context=None):
 
615
        if context is None:
 
616
            context = {}
 
617
        avl_obj = self.pool.get('account.voucher.line')
 
618
        return avl_obj.search(cr, uid, [('partner_id','=',id)],context=context)
 
619
            
 
620
    def _test_unlink(self, cr, uid, id, context=None): 
 
621
        if context is None:
 
622
            context = {}
 
623
        # TODO OR COMPLETE THE REMAINING FUNCTIONS SO IT COULD BE
 
624
        # POSIBLE TO CHECK ALL THE POSSIBILITIES.
 
625
        test = []
 
626
        test.append(all([self.search_aml(cr, uid, id, context=context) and True]))
 
627
        test.append(all([self.search_ai(cr, uid, id, context=context) and True]))
 
628
        test.append(all([self.search_so(cr, uid, id, context=context) and True]))
 
629
        test.append(all([self.search_po(cr, uid, id, context=context) and True]))
 
630
        test.append(all([self.search_avl(cr, uid, id, context=context) and True]))
 
631
        return test
 
632
 
 
633
    def _try_unlink(self, cr, uid, id, context=None):
 
634
        if context is None:
 
635
            context = {}
 
636
        attributes = ['customer','supplier']
 
637
        self_brw = self.browse(cr,uid,id,context)
 
638
        previous_accounts = {}
 
639
        vals={}
 
640
        
 
641
        for k in __ACC__:
 
642
            attr = __ACC__[k][0]
 
643
            previous_accounts.update({attr:getattr(self_brw,attr) and getattr(self_brw,attr).id})
 
644
        
 
645
        for k in __ACC__:
 
646
            attr = __ACC__[k][1]
 
647
            previous_accounts.update({attr:getattr(self_brw,attr) and getattr(self_brw,attr).id})
 
648
        
 
649
        for attr in attributes:
 
650
            previous_accounts.update({attr:getattr(self_brw, attr)})
 
651
        
 
652
        
 
653
        context.update({'previous_accounts':previous_accounts})
 
654
        
 
655
        
 
656
        #~ OBTENIENDO LAS CUENTAS CONTABLES QUE NO SE ACTUALIZARON
 
657
        for k in __ACC__:
 
658
            attr = __ACC__[k][0]
 
659
            vals.update({attr:False})
 
660
        
 
661
        for k in __ACC__:
 
662
            attr = __ACC__[k][1]
 
663
            vals.update({attr:False})
 
664
            
 
665
        for attr in attributes:
 
666
            vals.update({attr:False})
 
667
            
 
668
        if not any(self._test_unlink(cr, uid, id, context=context)):
 
669
            test=[True]
 
670
            for k in __ACC__:
 
671
                if self._check_unique(cr,uid,id,k,vals,context=context):
 
672
                    test.append(self._unlink_account(cr,uid,[id],k,vals,context=context))
 
673
                else:
 
674
                    test.append(True)
 
675
            return all(test)
 
676
        return False
 
677
 
 
678
    def unlink(self, cr, uid, ids,context=None):
 
679
        if context is None: 
 
680
            context = {}
 
681
        
 
682
        res = [id for id in ids if self._try_unlink(cr, uid, id, context=context)]
 
683
        if res:
 
684
            return super(res_partner,self).unlink(cr, uid, res, context=context)
 
685
        return False
216
686
res_partner()