~openerp-spain-team/openerp-spain/6.0-git

« back to all changes in this revision

Viewing changes to l10n_es_extras/l10n_ES_remesas/wizard/export_remesas.py

  • Committer: Borja L.S.
  • Date: 2010-10-18 10:04:25 UTC
  • Revision ID: git-v1:271c47a993616dbba60585d48b8b98d603199d93
[REF] *: Refactorización para portar a 6.0 - Paso 1.

- Se han renombrado los módulos para usar la nomenclatura propuesta
  por OpenERP: l10n_es para el módulo base de localización (plan de 
  cuentas), l10n_es_* para el resto de módulos.

- Se eliminan los módulos extra_addons/* que deberían moverse a 
  los extra-addons genéricos (no son específicos de España).

- Se renombran los __terp__.py por __openerp__.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- encoding: utf-8 -*-
2
 
##############################################################################
3
 
#
4
 
#    OpenERP, Open Source Management Solution
5
 
#    Copyright (c) 2006 ACYSOS S.L. (http://acysos.com) All Rights Reserved.
6
 
#                       Pedro Tarrafeta <pedro@acysos.com>
7
 
#    Copyright (c) 2008 Pablo Rocandio. All Rights Reserved.
8
 
#    Copyright (c) 2009 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
9
 
#                       Jordi Esteve <jesteve@zikzakmedia.com>
10
 
#    $Id$
11
 
#
12
 
# Corregido para instalación TinyERP estándar 4.2.0: Zikzakmedia S.L. 2008
13
 
#   Jordi Esteve <jesteve@zikzakmedia.com>
14
 
#
15
 
# Añadidas cuentas de remesas y tipos de pago. 2008
16
 
#    Pablo Rocandio <salbet@gmail.com>
17
 
#
18
 
# Rehecho de nuevo para instalación OpenERP 5.0.0 sobre account_payment_extension: Zikzakmedia S.L. 2009
19
 
#   Jordi Esteve <jesteve@zikzakmedia.com>
20
 
#
21
 
#    This program is free software: you can redistribute it and/or modify
22
 
#    it under the terms of the GNU General Public License as published by
23
 
#    the Free Software Foundation, either version 3 of the License, or
24
 
#    (at your option) any later version.
25
 
#
26
 
#    This program is distributed in the hope that it will be useful,
27
 
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
28
 
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29
 
#    GNU General Public License for more details.
30
 
#
31
 
#    You should have received a copy of the GNU General Public License
32
 
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
33
 
#
34
 
##############################################################################
35
 
 
36
 
import pooler
37
 
import wizard
38
 
import base64
39
 
import mx.DateTime
40
 
from mx.DateTime import now
41
 
from datetime import datetime
42
 
from tools.translate import _
43
 
from converter import *
44
 
import csb_19
45
 
import csb_32
46
 
import csb_34
47
 
import csb_58
48
 
 
49
 
join_form = """<?xml version="1.0"?>
50
 
<form string="Payment order export">
51
 
    <field name="join"/>
52
 
</form>"""
53
 
 
54
 
join_fields = {
55
 
    'join' : {'string':'Join payment lines of the same partner and bank account', 'type':'boolean'},
56
 
}
57
 
 
58
 
export_form = """<?xml version="1.0"?>
59
 
<form string="Payment order export">
60
 
    <field name="pay" filename="pay_fname"/>
61
 
    <field name="pay_fname" invisible="1"/>
62
 
    <field name="note" colspan="4" nolabel="1"/>
63
 
</form>"""
64
 
 
65
 
export_fields = {
66
 
    'pay' : {
67
 
        'string':'Payment order file',
68
 
        'type':'binary',
69
 
        'required': False,
70
 
        'readonly':True,
71
 
    },
72
 
    'pay_fname': {'string':'File name', 'type':'char', 'size':64},
73
 
    'note' : {'string':'Log', 'type':'text'},
74
 
}
75
 
 
76
 
 
77
 
def _create_payment_file(self, cr, uid, data, context):
78
 
 
79
 
    txt_remesa = ''
80
 
    num_lineas_opc = 0
81
 
 
82
 
    try:
83
 
        pool = pooler.get_pool(cr.dbname)
84
 
        orden = pool.get('payment.order').browse(cr, uid, data['id'], context)
85
 
        if not orden.line_ids:
86
 
            raise Log( _('User error:\n\nWizard can not generate export file, there are not payment lines.'), True )
87
 
 
88
 
        # Comprobamos que exista número de C.C. y que tenga 20 dígitos
89
 
        if not orden.mode.bank_id:
90
 
            raise Log( _('User error:\n\nThe bank account of the company %s is not defined.') % (orden.mode.partner_id.name), True )
91
 
        cc = digits_only(orden.mode.bank_id.acc_number)
92
 
        if len(cc) != 20:
93
 
            raise Log( _('User error:\n\nThe bank account number of the company %s has not 20 digits.') % (orden.mode.partner_id.name), True)
94
 
 
95
 
        # Comprobamos que exista el CIF de la compañía asociada al C.C. del modo de pago
96
 
        if not orden.mode.bank_id.partner_id.vat:
97
 
            raise Log(_('User error:\n\nThe company VAT number related to the bank account of the payment mode is not defined.'), True)
98
 
 
99
 
        recibos = []
100
 
        if data['form']['join']:
101
 
            # Lista con todos los partners+bancos diferentes de la remesa
102
 
            partner_bank_l = reduce(lambda l, x: x not in l and l.append(x) or l,
103
 
                                     [(recibo.partner_id,recibo.bank_id) for recibo in orden.line_ids], [])
104
 
            # Cómputo de la lista de recibos agrupados por mismo partner+banco.
105
 
            # Los importes se suman, los textos se concatenan con un espacio en blanco y las fechas se escoge el máximo
106
 
            for partner,bank in partner_bank_l:
107
 
                lineas = [recibo for recibo in orden.line_ids if recibo.partner_id==partner and recibo.bank_id==bank]
108
 
                recibos.append({
109
 
                    'partner_id': partner,
110
 
                    'bank_id': bank,
111
 
                    'name': partner.ref,
112
 
                    'amount': reduce(lambda x, y: x+y, [l.amount for l in lineas], 0),
113
 
                    'communication': reduce(lambda x, y: x+' '+(y or ''), [l.name+' '+l.communication for l in lineas], ''),
114
 
                    'communication2': reduce(lambda x, y: x+' '+(y or ''), [l.communication2 for l in lineas], ''),
115
 
                    'date': max([l.date for l in lineas]),
116
 
                    'ml_maturity_date': max([l.ml_maturity_date]),
117
 
                    'create_date': max([l.create_date]),
118
 
                    'ml_date_created': max([l.ml_date_created]),
119
 
                })
120
 
        else:
121
 
            # Cada línea de pago es un recibo
122
 
            for l in orden.line_ids:
123
 
                recibos.append({
124
 
                    'partner_id': l.partner_id,
125
 
                    'bank_id': l.bank_id,
126
 
                    'name': l.partner_id.ref,
127
 
                    'amount': l.amount,
128
 
                    'communication': l.name+' '+l.communication,
129
 
                    'communication2': l.communication2,
130
 
                    'date': l.date,
131
 
                    'ml_maturity_date': l.ml_maturity_date,
132
 
                    'create_date': l.create_date,
133
 
                    'ml_date_created': l.ml_date_created,
134
 
                })
135
 
 
136
 
        if orden.mode.require_bank_account:
137
 
            for line in recibos:
138
 
                ccc = line['bank_id'] and line['bank_id'].acc_number or False
139
 
                if not ccc:
140
 
                    raise Log(_('User error:\n\nThe bank account number of the customer %s is not defined and current payment mode enforces all lines to have a bank account.') % (line['partner_id'].name), True)
141
 
                ccc = digits_only(ccc)
142
 
                if len(ccc) != 20:
143
 
                    raise Log(_('User error:\n\nThe bank account number of the customer %s has not 20 digits.') % (line['partner_id'].name), True)
144
 
 
145
 
        if orden.mode.tipo == 'csb_19':
146
 
            csb = csb_19.csb_19()
147
 
        elif orden.mode.tipo == 'csb_32':
148
 
            csb = csb_32.csb_32()
149
 
        elif orden.mode.tipo == 'csb_34':
150
 
            csb = csb_34.csb_34()
151
 
        elif orden.mode.tipo == 'csb_58':
152
 
            csb = csb_58.csb_58()
153
 
        else:
154
 
            raise Log(_('User error:\n\nThe payment mode is not CSB 19, CSB 32, CSB 34 or CSB 58'), True)
155
 
        txt_remesa = csb.create_file(pool, cr, uid, orden, recibos, context)
156
 
 
157
 
    except Log, log:
158
 
        return {
159
 
            'note': log(), 
160
 
            'reference': orden.id, 
161
 
            'pay': False, 
162
 
            'state':'failed'
163
 
        }
164
 
    else:
165
 
        # Ensure line breaks use MS-DOS (CRLF) format as standards require.
166
 
        txt_remesa = txt_remesa.replace('\r\n','\n').replace('\n','\r\n')
167
 
 
168
 
        file = base64.encodestring(txt_remesa)
169
 
        fname = (_('remesa') + '_' + orden.mode.tipo + '_' + orden.reference + '.txt').replace('/','-')
170
 
        pool.get('ir.attachment').create(cr, uid, {
171
 
            'name': _('Remesa ') + orden.mode.tipo + ' ' + orden.reference,
172
 
            'datas': file,
173
 
            'datas_fname': fname,
174
 
            'res_model': 'payment.order',
175
 
            'res_id': orden.id,
176
 
            }, context=context)
177
 
        log = _("Successfully Exported\n\nSummary:\n Total amount paid: %.2f\n Total Number of Payments: %d\n") % (-orden.total, len(recibos))
178
 
        pool.get('payment.order').set_done(cr,uid,orden.id,context)
179
 
        return {
180
 
            'note': log, 
181
 
            'reference': orden.id, 
182
 
            'pay': file, 
183
 
            'pay_fname': fname, 
184
 
            'state': 'succeeded',
185
 
        }
186
 
 
187
 
 
188
 
class wizard_payment_file_spain(wizard.interface):
189
 
    states = {
190
 
        'init' : {
191
 
            'actions' : [],
192
 
            'result' : {'type' : 'form',
193
 
                        'arch' : join_form,
194
 
                        'fields' : join_fields,
195
 
                        'state' : [('export', 'Ok','gtk-ok') ]}
196
 
        },
197
 
        'export': {
198
 
            'actions' : [_create_payment_file],
199
 
            'result' : {'type' : 'form',
200
 
                        'arch' : export_form,
201
 
                        'fields' : export_fields,
202
 
                        'state' : [('end', 'Ok','gtk-ok') ]}
203
 
        }
204
 
 
205
 
    }
206
 
wizard_payment_file_spain('export_payment_file_spain')
207
 
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
208