~eduardo-bayardo-bias/openobject-addons/bias_trunk_v8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv
from openerp.tools.translate import _
from operator import itemgetter
from openerp import SUPERUSER_ID

QUERY = """
    SELECT 
        ABS(COALESCE(%s,0)) AS inv_base_0,
        ABS(COALESCE(%s,0)) AS inv_base_exe,
        ABS(COALESCE(%s,0)) AS inv_base_exe_imp,
        ABS(COALESCE(%s,0)) AS inv_base_16,
        ABS(COALESCE(%s,0)) AS inv_base_16_imp,
        ABS(COALESCE(%s,0)) AS inv_base_16_nc,
        ABS(COALESCE(%s,0)) AS inv_base_vat_4,
        ABS(COALESCE(%s,0)) AS inv_base_vat_10,
        ABS(COALESCE(%s,0)) AS inv_base_vat_1067,
        ABS(COALESCE(%s,0)) AS inv_base_isr,
        ABS(COALESCE(%s,0)) AS inv_base_ieps,
        ABS(COALESCE(%s,0)) AS inv_base_ieps_imp,
        ABS(COALESCE(%s,0)) AS inv_vat_16,
        ABS(COALESCE(%s,0)) AS inv_vat_16_imp,
        ABS(COALESCE(%s,0)) AS inv_vat_16_nc,
        ABS(COALESCE(%s,0)) AS inv_retained_vat_4,
        ABS(COALESCE(%s,0)) AS inv_retained_vat_10,
        ABS(COALESCE(%s,0)) AS inv_retained_vat_1067,
        ABS(COALESCE(%s,0)) AS inv_retained_isr,
        ABS(COALESCE(%s,0)) AS inv_ieps,
        ABS(COALESCE(%s,0)) AS inv_ieps_imp,
        ABS(COALESCE(%s,0)) AS inv_total
    """

QUERY_TAX = """
    SELECT 
        p.tax_type,t.account_paid_id,t.account_collected_id 
    FROM 
        account_tax t LEFT JOIN
        account_fiscal_position_transfer p ON p.tax_id=t.id LEFT JOIN
        account_fiscal_position f ON f.id=p.position_id
    WHERE 
        t.company_id=%s AND
        t.account_paid_id IS NOT NULL AND
        t.account_collected_id IS NOT NULL AND
        p.id IS NOT NULL AND
        f.active = True
    GROUP BY p.tax_type,t.account_paid_id,t.account_collected_id 
    ORDER BY tax_type
    """

class account_move_reconcile(osv.osv):
    _inherit = "account.move.reconcile"

    def create(self, cr, uid, vals, context=None, check=True):
        rec_id = super(account_move_reconcile, self).create(cr, uid, vals, context=context)
        # Process Fiscal Lines if move line journal type is is 'bank' and have a partner.
        move_obj = self.pool.get('account.move')
        reconcile = self.browse(cr, uid, rec_id, context=context)
        print '*************** create reconcile', reconcile.read([])
        for line in reconcile.line_id + reconcile.line_partial_ids:
            self.pool.get('account.move.line').create_fiscal_line(cr, uid, line.id, context.get('account_position',False))
        return rec_id

    def write(self, cr, uid, ids, vals, context=None):
        print '************** write=', ids, vals
        res = super(account_period, self).write(cr, uid, ids, vals, context=context)
        return res 


class account_move_line(osv.osv):
    _inherit = "account.move.line"

    #####################################################################################################################
    ## CREATE account_move_fiscal Lines and create tax transfer account_move_line
    #####################################################################################################################
    def create_fiscal_line(self, cr, uid, line_id, account_position=False, context=None):
        print '*************** create_fiscal_line('
        fiscal_obj = self.pool.get('account.move.fiscal')
        if isinstance(line_id,list):
            line_id = line_id[0]
        line = self.browse(cr, uid, line_id)
        # >>>>>>>>>>    Return if journal is not bank or account is not one of the trigger accounts
        account_position, operation_type = self.get_operation_type(cr, uid, line, position=account_position, context=context)
        if not line.journal_id.type == 'bank' or not operation_type: 
            return True
        # >>>>>>>>>>    Return if line debit and credit in zero
        if not line.debit - line.credit:
            return True
        res = self.get_base(cr, uid, line, account_position, operation_type, context=context)
        val = {
            'id': '__export__.account_move_fiscal_' + str(line.id),
            'move_id/.id': line.move_id.id,
            'line_id/.id': line.id,
            'currency_id/.id': line.currency_id.id or line.company_id.currency_id.id,
            'partner_id/.id': line.partner_id.id,
            'account_id/.id': line.account_id.id,
            'journal_id/.id': line.journal_id.id,
            'period_id/.id': line.period_id.id,
            'date':line.date,
            'operation_type': operation_type,
            'account_position/.id': res.get('account_position',False),
            'base_0': res.get('base_0',False),
            'base_exe': res.get('base_exe',False),
            'base_exe_imp': res.get('base_exe_imp',False),
            'base_16': res.get('base_16',False),
            'base_16_imp': res.get('base_16_imp',False),
            'base_16_nc': res.get('base_16_nc',False),
            'base_vat_4': res.get('base_vat_4',False),
            'base_vat_10': res.get('base_vat_10',False),
            'base_vat_1067': res.get('base_vat_1067',False),
            'base_isr':res.get('base_isr',False),
            'base_ieps':res.get('base_ieps',False),
            'base_ieps_imp':res.get('base_ieps_imp',False),
            'vat_16': res.get('vat_16',False),
            'vat_16_imp': res.get('vat_16_imp',False),
            'vat_16_nc': res.get('vat_16_nc',False),
            'retained_vat_4': res.get('retained_vat_4',False),
            'retained_vat_10': res.get('retained_vat_10',False),
            'retained_vat_1067': res.get('retained_vat_1067',False),
            'retained_isr': res.get('retained_isr',False),
            'ieps': res.get('ieps',False),
            'ieps_imp': res.get('ieps_imp',False),
            'total': res.get('total',False),
            'payment': res.get('payment',False),
            'invoice_ids/.id': res.get('invoice_ids',False),
        }
        import_fields = val.keys()
        values = [tuple(val.values())]
        import_result = self.pool['account.move.fiscal'].load(cr, uid, import_fields, values, context=context)
        if import_result['messages']:
            raise osv.except_osv(_('ERROR!'), _('%s')%import_result['messages']) 
        if import_result['ids'] and (val['base_0'] + val['base_exe'] + val['base_exe_imp'] + val['base_16'] + val['base_16_imp'] + val['base_16_nc'] + val['base_ieps'] + val['base_ieps_imp']):
            fiscal_obj.button_tax_xfer(cr, uid, import_result['ids'], context=None)
        return True

    #####################################################################################################################
    ## Get taxes: base, vat, ieps, retensions (vat and isr) from account_move_fiscal Lines
    #####################################################################################################################
    def get_base(self, cr, uid, line, account_position=False, operation_type=False, context=None):
        def compute(cr, uid, line, amount, context=None):
            cur_obj = self.pool.get('res.currency')
            return cur_obj.compute(cr, uid, line.journal_id.currency.id, line.company_id.currency_id.id, amount, context={'date': line.date}, round=False)
        context = context or {}
        tax_obj = self.pool.get('account.tax')
        vat_obj = self.pool.get('account.vat.line')
        vat_16 = vat_16_imp = vat_16_nc = retained_vat_4 = retained_vat_10 = retained_vat_1067 = retained_isr = ieps = ieps_imp = 0.0
        precision = self.get_precision(cr, uid, line, context=context)
        sign = operation_type in ('inter_bank_out','outcome','other_out') and 1 or -1
        payment = line.debit - line.credit
        # >>>>>>>>>>    INTER-BANK TRANSACTION
        if operation_type == 'inter_bank':
            result = {}
        # >>>>>>>>>>    OTHER TRANSACTION
        if operation_type == 'other':
            result = {}
        # >>>>>>>>>>    TRY TO USE INVOICE TAXES: Tax amounts are taken from payed invoices        
        else:
            res = self.amount_invoice_compute(cr, uid, line, context=context)
            invoice_ids = res.get('invoice_ids',[]) and ','.join(map(str,res.get('invoice_ids',[]))) or False
            result = {       
                'base_0': compute(cr, uid, line, res.get('inv_base_0',0.0)),
                'base_exe': compute(cr, uid, line, res.get('inv_base_exe',0.0)),
                'base_exe_imp': compute(cr, uid, line, res.get('inv_base_exe_imp',0.0)),
                'base_16': compute(cr, uid, line, res.get('inv_base_16',0.0)),
                'base_16_imp': compute(cr, uid, line, res.get('inv_base_16_imp',0.0)),
                'base_16_nc': compute(cr, uid, line, res.get('inv_base_16_nc',0.0)),
                'base_vat_4': compute(cr, uid, line, res.get('inv_base_vat_4',0.0)),
                'base_vat_10': compute(cr, uid, line, res.get('inv_base_vat_10',0.0)),
                'base_vat_1067': compute(cr, uid, line, res.get('inv_base_vat_1067',0.0)),
                'base_isr': compute(cr, uid, line, res.get('inv_base_isr',0.0)),
                'base_ieps': compute(cr, uid, line, res.get('inv_base_ieps',0.0)),
                'base_ieps_imp': compute(cr, uid, line, res.get('inv_base_ieps_imp',0.0)),
                'vat_16': compute(cr, uid, line, res.get('inv_vat_16',0.0)),
                'vat_16_imp': compute(cr, uid, line, res.get('inv_vat_16_imp',0.0)),
                'vat_16_nc': compute(cr, uid, line, res.get('inv_vat_16_nc',0.0)),
                'retained_vat_4': compute(cr, uid, line, res.get('inv_retained_vat_4',0.0)),
                'retained_vat_10': compute(cr, uid, line, res.get('inv_retained_vat_10',0.0)),
                'retained_vat_1067': compute(cr, uid, line, res.get('inv_retained_vat_1067',0.0)),
                'retained_isr': compute(cr, uid, line, res.get('inv_retained_isr',0.0)),
                'ieps': compute(cr, uid, line, res.get('inv_ieps',0.0)),
                'ieps_imp': compute(cr, uid, line, res.get('inv_ieps_imp',0.0)),
                'total': compute(cr, uid, line, res.get('inv_total',0.0)),
                'account_position':account_position and account_position.id,
                'invoice_ids':invoice_ids,
            }
        # >>>>>>>>>>    IF THERE ARE NOT RECONCILED INVOICES GET TAX BASED ON PAYMENTS: Tax amounts are taken from Tax Transfer Model
            if not result['invoice_ids']:
                tax_amount = {}
                vat_0 = vat_exe = vat_exe_imp = vat_16 = vat_16_imp = vat_16_nc = retained_vat_4 = retained_vat_10 = retained_vat_1067 = retained_isr = ieps = ieps_imp = 0
                if account_position:
                    account_position = self.pool.get('account.fiscal.position').browse(cr, SUPERUSER_ID, account_position.id)
                    xfer_ids = account_position.xfer_ids
                    taxes = [xfer.tax_id for xfer in xfer_ids if line.account_id in xfer.trigger_account_ids]
                    for tax in taxes:
                        if tax.company_id != line.company_id:
                            raise osv.except_osv(_('Error!'),_('The tax "%s" from fiscal position "%s" belongs to company "%s" and you are working in company "%s"')%(tax.name, account_position.name, tax.company_id.name, line.company_id.name))
                    for tax in tax_obj.compute_inv(cr, uid, taxes, payment, 1, product=None, partner=line.partner_id.id, precision=precision):
                        tax_amount.update({tax['id']:round(tax['amount'], precision)})
                    for xfer in xfer_ids:
                        if line.account_id in xfer.trigger_account_ids:
                            if xfer.tax_type == 'vat_0':
                                vat_0 = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'vat_exe':
                                vat_exe = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'vat_exe_imp':
                                vat_exe_imp = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'vat_16':
                                vat_16 = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'vat_16_imp':
                                vat_16_imp = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'vat_16_nc':
                                vat_16_nc = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'retained_vat_4':
                                retained_vat_4 = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'retained_vat_10':
                                retained_vat_10 = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'retained_vat_1067':
                                retained_vat_1067 = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'retained_isr':
                                retained_isr = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'ieps':
                                ieps = tax_amount.get(xfer.tax_id.id,0.0)
                            elif xfer.tax_type == 'ieps_imp':
                                ieps_imp = tax_amount.get(xfer.tax_id.id,0.0)
                    base = abs(payment)+abs(retained_vat_4 + retained_vat_10 + retained_vat_1067 + retained_isr)-abs(vat_16 + vat_16_imp + vat_16_nc + ieps + ieps_imp)
                    result = {
                        'base_0':abs(vat_0 and base or 0.0),
                        'base_exe':abs(vat_exe and base or 0.0),
                        'base_exe_imp':abs(vat_exe_imp and base or 0.0),
                        'base_16':abs(vat_16 and base or 0.0),
                        'base_16_imp':abs(vat_16_imp and base or 0.0),
                        'base_16_nc':abs(vat_16_nc and base or 0.0),
                        'base_vat_4':abs(retained_vat_4 and base or 0.0),
                        'base_vat_10':abs(retained_vat_10 and base or 0.0),
                        'base_vat_1067':abs(retained_vat_1067 and base or 0.0),
                        'base_isr':abs(retained_isr and base or 0.0),
                        'base_ieps':abs(ieps and base or 0.0),
                        'base_ieps_imp':abs(ieps_imp and base or 0.0),
                        'vat_16':abs(vat_16), 
                        'vat_16_imp':abs(vat_16_imp), 
                        'vat_16_nc':abs(vat_16_nc), 
                        'retained_vat_4':abs(retained_vat_4), 
                        'retained_vat_10':abs(retained_vat_10), 
                        'retained_vat_1067':abs(retained_vat_1067), 
                        'retained_isr':abs(retained_isr), 
                        'ieps':abs(ieps), 
                        'ieps_imp':abs(ieps_imp), 
                        'account_position':account_position.id,
                        'invoice_ids':False,
                    }
        result.update({'payment':abs(payment)*sign})
        return result

    #####################################################################################################################
    #   Return account_position from:
    #       1.- Argument: selected in Aaccount > Journal Entries > Journal Entries > Fiscal > Fiscal Position
    #       2.- Payment line Partner: Customer/Supplier > Accounting > Fiscal Position
    #       3.- The default account position: Accounting > Configuration > Taxes > Fiscal Position > Default
    #   Return type of operation
    #####################################################################################################################
    def get_operation_type(self, cr, uid, line, position=False, context=None):
        cr.execute("""SELECT default_debit_account_id FROM account_journal WHERE type='bank' UNION 
                      SELECT default_credit_account_id FROM account_journal WHERE type='bank' """)
        bank_accounts = map(itemgetter(0), cr.fetchall())
        account_position = self.get_default_position(cr, uid, context=context)
        operation_type = False
        if line.account_id in [line.journal_id.default_debit_account_id, line.journal_id.default_credit_account_id]:    # >>>>>>>>>> journal bank account line
            return False, False
        elif line.account_id.id in bank_accounts:                                                                       # >>>>>>>>>> inter-bank outcome/income line
            operation_type = (line.debit - line.credit) > 0 and 'inter_bank_out' or 'inter_bank_in'                     
            return False, operation_type
        if position:
            account_position = self.pool.get('account.fiscal.position').browse(cr, uid, position)
        elif not line.partner_id:
            pass
        elif not line.partner_id.active:
            raise osv.except_osv(_('Error !'), _('Partner %s is inactive. Entry %s'%(line.partner_id.name, line.move_id.name)))
        elif line.partner_id and line.partner_id.property_account_position:
            account_position = line.partner_id.property_account_position
        if not account_position:
            return False, False
        if line.partner_id.property_account_position and not line.partner_id.property_account_position.active:
            raise osv.except_osv(_('Error !'), _('Account Position defined in Partner %s is inactive. Entry %s'%(line.partner_id.name, line.move_id.name)))
        elif not account_position.xfer_ids:
            raise osv.except_osv(_('Error !'), _('No transfer model defined in Account Position %s. Entry %s'%(line.partner_id.property_account_position.name, line.move_id.name)))
        if not account_position:
            raise osv.except_osv(_('Error !'), _('Not default account position defined.'))
        for xfer in account_position.xfer_ids:
            if line.account_id in xfer.trigger_account_ids:
                operation_type = (line.debit - line.credit) > 0 and 'outcome' or 'income'                               # >>>>>>>>>> trigger outcome/income line
        operation_type = operation_type or (line.debit - line.credit) > 0 and 'other_out' or 'other_in'                 # >>>>>>>>>> other outcome/income line
        return account_position, operation_type

    def get_default_position(self, cr, uid, context=None):
        obj = self.pool.get('account.fiscal.position')
        account_position = False
        default = obj.search(cr, uid, [('default','=',True)])
        if default:
            account_position = obj.browse(cr, uid, default[0])
        return account_position

    def get_precision(self, cr, uid, line, context=None):
        precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account')# return an integer like 2 or 4
        if line.company_id.tax_calculation_rounding_method == 'round_globally':
            precision += 5 #TODO get precition from somewhere
        return precision


    #####################################################################################################################
    ##  Get invoice taxes
    #####################################################################################################################
    def get_tax_accounts(self, cr, uid, company_id, context=None):
        accounts = {'vat_0':[],'vat_exe':[],'vat_exe_imp':[],'vat_16':[],'vat_16_imp':[],'vat_16_nc':[],'retained_vat_4':[],'retained_vat_10':[],'retained_vat_1067':[],'retained_isr':[],'ieps':[],'ieps_imp':[]}
        cr.execute(QUERY_TAX%company_id)
        for reg in cr.dictfetchall():
            accounts[reg['tax_type']] += set([reg['account_paid_id'], reg['account_collected_id']])
        return accounts

    def get_invoice_entry_lines(self, cr, uid, line, context=None):
        # Return all invoice entry lines and all lines reconciled (partial or not) from a bank entry
        reconcile = {'acc_bank':[], 'invoices':[]}
        # list of list (reconciled lines)
        lines = line.reconcile_id and line.reconcile_id.line_id
        if lines:
            acc_bank = [x.id for x in lines if x.journal_id.type == 'bank']     # get bank account move lines
            invoices = [x.invoice.id for x in lines if x.invoice]               # get payed invoices
            reconcile = {'acc_bank':acc_bank, 'invoices':invoices}

        # list of list (partial reconciled lines)
        lines = line.reconcile_partial_id and line.reconcile_partial_id.line_partial_ids
        if lines:
            acc_bank = [x.id for x in lines if x.journal_id.type == 'bank']     # get bank account move lines
            invoices = [x.invoice.id for x in lines if x.invoice]               # get payed invoices
            reconcile = {'acc_bank':acc_bank, 'invoices':invoices}
        return reconcile

    def amount_invoice_compute(self, cr, uid, line, context=None):
        # Inicialize Variables
        res, invoice_ids = {}, []
        arg_base_0 = arg_base_exe = arg_base_exe_imp = arg_base_16 = arg_base_16_imp = arg_base_16_nc = arg_base_vat_4 = arg_base_vat_10 = "0 "
        arg_base_vat_1067 = arg_base_isr = arg_base_ieps = arg_base_ieps_imp = "0 "
        arg_vat_16 = arg_vat_16_imp = arg_vat_16_nc = arg_retained_vat_04 = arg_retained_vat_10 = arg_retained_vat_1067 = arg_retained_isr = arg_ieps = arg_ieps_imp = arg_total = "0 "
        arg_tax = "(select sum(amount) from account_invoice_tax where account_id in %s and invoice_id in %s )"
        arg_base = "(select sum(base) from account_invoice_tax where account_id in %s and invoice_id in %s )"

        # >>>>>>>>>>    Get tax accounts from tax definition
        accounts = self.get_tax_accounts(cr, uid, line.company_id.id, context=context)

        # >>>>>>>>>>    Get full and partial reconciled invoices    <<<<<<<<<<
        invoice_data = self.get_invoice_entry_lines(cr, uid, line, context=context)

        # >>>>>>>>>>    Process partial and full reconciled invoices     <<<<<<<<<<
        invoice_ids = invoice_data['invoices']
        bank_ids = invoice_data['acc_bank']
        arg_invoice = tuple(invoice_ids+[0])
        if invoice_ids:
            arg_total = "(select sum(amount_total) from account_invoice where id in %s )"%(arg_invoice,)
            if accounts['vat_0']:
                arg_base_0 = arg_base%(tuple(accounts['vat_0']+[0]),arg_invoice)
            if accounts['vat_exe']:
                arg_base_exe = arg_base%(tuple(accounts['vat_exe']+[0]),arg_invoice)
            if accounts['vat_exe_imp']:
                arg_base_exe_imp = arg_base%(tuple(accounts['vat_exe_imp']+[0]),arg_invoice)
            if accounts['vat_16']:
                arg_vat_16 = arg_tax%(tuple(accounts['vat_16']+[0]),arg_invoice)
                arg_base_16 = arg_base%(tuple(accounts['vat_16']+[0]),arg_invoice)
            if accounts['vat_16_imp']:
                arg_vat_16_imp = arg_tax%(tuple(accounts['vat_16_imp']+[0]),arg_invoice)
                arg_base_16_imp = arg_base%(tuple(accounts['vat_16_imp']+[0]),arg_invoice)
            if accounts['vat_16_nc']:
                arg_vat_16_nc = arg_tax%(tuple(accounts['vat_16_nc']+[0]),arg_invoice)
                arg_base_16_nc = arg_base%(tuple(accounts['vat_16_nc']+[0]),arg_invoice)
            if accounts['retained_vat_4']:
                arg_retained_vat_04 = arg_tax%(tuple(accounts['retained_vat_4']+[0]),arg_invoice)
                arg_base_vat_4 = arg_base%(tuple(accounts['retained_vat_4']+[0]),arg_invoice)
            if accounts['retained_vat_10']:
                arg_retained_vat_10 = arg_tax%(tuple(accounts['retained_vat_10']+[0]),arg_invoice)
                arg_base_vat_10 = arg_base%(tuple(accounts['retained_vat_10']+[0]),arg_invoice)
            if accounts['retained_vat_1067']:
                arg_retained_vat_1067 = arg_tax%(tuple(accounts['retained_vat_1067']+[0]),arg_invoice)
                arg_base_vat_1067 = arg_base%(tuple(accounts['retained_vat_1067']+[0]),arg_invoice)
            if accounts['retained_isr']:
                arg_retained_isr = arg_tax%(tuple(accounts['retained_isr']+[0]),arg_invoice)
                arg_base_isr = arg_base%(tuple(accounts['retained_isr']+[0]),arg_invoice)
            if accounts['ieps']:
                arg_ieps = arg_tax%(tuple(accounts['ieps']+[0]),arg_invoice)
                arg_base_ieps = arg_base%(tuple(accounts['ieps']+[0]),arg_invoice)
            if accounts['ieps_imp']:
                arg_ieps_imp = arg_tax%(tuple(accounts['ieps_imp']+[0]),arg_invoice)
                arg_base_ieps_imp = arg_base%(tuple(accounts['ieps_imp']+[0]),arg_invoice)
            query = QUERY%(arg_base_0, arg_base_exe, arg_base_exe_imp, arg_base_16, arg_base_16_imp, arg_base_16_nc, arg_base_vat_4, arg_base_vat_10, arg_base_vat_1067, \
                    arg_base_isr, arg_base_ieps, arg_base_ieps_imp, arg_vat_16, arg_vat_16_imp, arg_vat_16_nc, arg_retained_vat_04, arg_retained_vat_10, arg_retained_vat_1067, \
                    arg_retained_isr, arg_ieps, arg_ieps_imp, arg_total)
            cr.execute(query)
            res = cr.dictfetchone()
            print 'res=',query
            line_total = abs(line.debit - line.credit)
            factor = res['inv_total'] and abs(line_total/res['inv_total'])
            if factor:
                res.update({
                    'inv_base_0': res['inv_base_0'] and res['inv_base_0'] * factor or 0.0,
                    'inv_base_exe': res['inv_base_exe'] and res['inv_base_exe'] * factor or 0.0,
                    'inv_base_exe_imp': res['inv_base_exe_imp'] and res['inv_base_exe_imp'] * factor or 0.0,
                    'inv_base_16': res['inv_base_16'] and res['inv_base_16'] * factor or 0.0,
                    'inv_base_16_imp': res['inv_base_16_imp'] and res['inv_base_16_imp'] * factor or 0.0,
                    'inv_base_16_nc': res['inv_base_16_nc'] and res['inv_base_16_nc'] * factor or 0.0,
                    'inv_base_vat_4': res['inv_base_vat_4'] and res['inv_base_vat_4'] * factor or 0.0,
                    'inv_base_vat_10': res['inv_base_vat_10'] and res['inv_base_vat_10'] * factor or 0.0,
                    'inv_base_vat_1067': res['inv_base_vat_1067'] and res['inv_base_vat_1067'] * factor or 0.0,
                    'inv_base_isr': res['inv_base_isr'] and res['inv_base_isr'] * factor or 0.0,
                    'inv_base_ieps': res['inv_base_ieps'] and res['inv_base_ieps'] * factor or 0.0,
                    'inv_base_ieps_imp': res['inv_base_ieps_imp'] and res['inv_base_ieps_imp'] * factor or 0.0,
                    'inv_vat_16': res['inv_vat_16'] and res['inv_vat_16'] * factor or 0.0,
                    'inv_vat_16_imp': res['inv_vat_16_imp'] and res['inv_vat_16_imp'] * factor or 0.0,
                    'inv_vat_16_nc': res['inv_vat_16_nc'] and res['inv_vat_16_nc'] * factor or 0.0,
                    'inv_retained_vat_4': res['inv_retained_vat_4'] and res['inv_retained_vat_4'] * factor or 0.0,
                    'inv_retained_vat_10': res['inv_retained_vat_10'] and res['inv_retained_vat_10'] * factor or 0.0,
                    'inv_retained_vat_1067': res['inv_retained_vat_1067'] and res['inv_retained_vat_1067'] * factor or 0.0,
                    'inv_retained_isr': res['inv_retained_isr'] and res['inv_retained_isr'] * factor or 0.0,
                    'inv_ieps': res['inv_ieps'] and res['inv_ieps'] * factor or 0.0,
                    'inv_ieps_imp': res['inv_ieps_imp'] and res['inv_ieps_imp'] * factor or 0.0,
                    'inv_total': res['inv_total']
                })
        res.update({'invoice_ids':invoice_ids})
        return res



# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: