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

« back to all changes in this revision

Viewing changes to l10n_es_extras/l10n_ES_aeat_mod340/wizard/export_mod340.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) 2009 Alejandro Sanchez (http://www.asr-oss.com) All Rights Reserved.
6
 
#                       Alejandro Sanchez <alejandro@asr-oss.com>
7
 
#    $Id$
8
 
#
9
 
#    This program is free software: you can redistribute it and/or modify
10
 
#    it under the terms of the GNU General Public License as published by
11
 
#    the Free Software Foundation, either version 3 of the License, or
12
 
#    (at your option) any later version.
13
 
#
14
 
#    This program is distributed in the hope that it will be useful,
15
 
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 
#    GNU General Public License for more details.
18
 
#
19
 
#    You should have received a copy of the GNU General Public License
20
 
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 
#
22
 
##############################################################################
23
 
 
24
 
import pooler
25
 
import wizard
26
 
import base64
27
 
import mx.DateTime
28
 
from mx.DateTime import now
29
 
import netsvc
30
 
logger = netsvc.Logger()
31
 
 
32
 
mod340_form = """<?xml version="1.0"?>
33
 
<form string="Model 340 export">
34
 
    <label string="Do you want to export Model 340" />
35
 
</form>"""
36
 
 
37
 
mod340_fields = {}
38
 
 
39
 
export_form = """<?xml version="1.0"?>
40
 
<form string="Payment order export">
41
 
    <field name="mod340" filename="pay_fname"/>
42
 
    <field name="mod340_fname" invisible="1"/>
43
 
    <field name="note" colspan="4" nolabel="1"/>
44
 
</form>"""
45
 
 
46
 
export_fields = {
47
 
    'mod340' : {
48
 
        'string':'Modelo 340 file',
49
 
        'type':'binary',
50
 
        'required': False,
51
 
        'readonly':True,
52
 
    },
53
 
    'mod340_fname': {'string':'File name', 'type':'char', 'size':64},
54
 
    'note' : {'string':'Log', 'type':'text'},
55
 
}
56
 
 
57
 
 
58
 
def digitos_cc(cc_in):
59
 
    """Quita los espacios en blanco del número de C.C. (por ej. los que pone el módulo l10n_ES_partner)"""
60
 
    cc = ""
61
 
    for i in cc_in:
62
 
        try:
63
 
            int(i)
64
 
            cc += i
65
 
        except ValueError:
66
 
            pass
67
 
    return cc
68
 
 
69
 
 
70
 
def conv_ascii(text):
71
 
    """Convierte vocales accentuadas, ñ y ç a sus caracteres equivalentes ASCII"""
72
 
    old_chars = ['á','é','í','ó','ú','à','è','ì','ò','ù','ä','ë','ï','ö','ü','â','ê','î','ô','û','Á','É','Í','Ú','Ó','À','È','Ì','Ò','Ù','Ä','Ë','Ï','Ö','Ü','Â','Ê','Î','Ô','Û','ñ','Ñ','ç','Ç','ª','º']
73
 
    new_chars = ['a','e','i','o','u','a','e','i','o','u','a','e','i','o','u','a','e','i','o','u','A','E','I','O','U','A','E','I','O','U','A','E','I','O','U','A','E','I','O','U','n','N','c','C','a','o']
74
 
    for old, new in zip(old_chars, new_chars):
75
 
        text = text.replace(unicode(old,'UTF-8'), new)
76
 
    return text
77
 
 
78
 
def _formatearCadena(cadena, longitud,caracter,derecha):
79
 
    #funcion para rellenar la cadena para la aeat
80
 
    if cadena:
81
 
        posiciones = longitud - len(cadena)
82
 
        if derecha == True:
83
 
            cadena += posiciones * caracter
84
 
        else:
85
 
            cadena = (posiciones * caracter) + cadena 
86
 
    else:
87
 
        cadena = longitud*' '
88
 
    #devuelve la cadena en mayusculas
89
 
    return cadena.upper()
90
 
    
91
 
def _formatearDecimal(numero, enteros, decimales,incluir_signo):
92
 
    #funcion para formatear los numeros para la aeat
93
 
    if numero:
94
 
        cadena = str(numero)
95
 
    else:
96
 
        numero = 0
97
 
        cadena = '0.00'
98
 
 
99
 
    separacion = cadena.partition('.')
100
 
 
101
 
    if numero >= 0 and incluir_signo == True:
102
 
        signo = ' '
103
 
    elif numero < 0 and incluir_signo == True:
104
 
        signo = 'N'
105
 
    else:
106
 
        signo = ''
107
 
 
108
 
    parteEntera = _formatearCadena(separacion[0],enteros,'0',False)
109
 
    parteDecimal = _formatearCadena(separacion[2],decimales,'0',True)
110
 
 
111
 
    return signo + parteEntera + parteDecimal
112
 
 
113
 
class Log(Exception):
114
 
    def __init__(self):
115
 
        self.content = ""
116
 
        self.error = False
117
 
    def add(self, s, error=True):
118
 
        self.content = self.content + s
119
 
        if error:
120
 
            self.error = error
121
 
    def __call__(self):
122
 
        return self.content
123
 
    def __str__(self):
124
 
        return self.content
125
 
 
126
 
 
127
 
def _create_mod340_file(self, cr, uid, data, context):
128
 
 
129
 
    #pediente de solucionar el tema de las secuencia de la declaracion
130
 
    def _number_ident(fiscalyear,period,sequence):
131
 
        return '340' + fiscalyear + period + '0001'
132
 
 
133
 
    def _cabecera_modelo_340(self):
134
 
        #Datos Compañia
135
 
        company_obj = mod340.company_id
136
 
 
137
 
        if _formatearCadena(mod340.type,1,' ',True) == ' ':
138
 
            tipo_declaracion = [' ',' ']
139
 
        elif  _formatearCadena(mod340.type,1,' ',True) == 'C':
140
 
            tipo_declaracion = ['C',' ']
141
 
        elif  _formatearCadena(mod340.type,1,' ',True) == 'S':
142
 
            tipo_declaracion = [' ','S']
143
 
 
144
 
        texto = '1'
145
 
        texto += '340'
146
 
        texto += str(mod340.fiscalyear)
147
 
        texto += _formatearCadena(company_obj.partner_id.vat[2:len(company_obj.partner_id.vat)], 9, ' ', True)
148
 
        texto += _formatearCadena(company_obj.name,40,' ',True)
149
 
        texto += _formatearCadena(mod340.type_support,1,' ',True)
150
 
        texto += _formatearCadena(mod340.phone_contact,9,' ',True)
151
 
        texto += _formatearCadena(mod340.name_contact,40,' ',True)
152
 
        #texto += _formatearCadena('',13,' ',True) #demomento blanco pendiente
153
 
        texto += _number_ident(str(mod340.fiscalyear),_formatearCadena(mod340.period,2,' ',True),'')
154
 
        texto += tipo_declaracion[0] #Declaracion complementaria
155
 
        texto += tipo_declaracion[1] #Declaracion Sustitutiva
156
 
        #texto += _formatearCadena('',13,' ',True) #demomento blanco falta crear campo iden declaracion anterior
157
 
        texto += 13*'0' #demomento blanco falta crear campo iden declaracion anterior
158
 
        texto += _formatearCadena(mod340.period,2,' ',True)
159
 
        texto += _formatearDecimal(mod340.number_records,9,0,False)
160
 
        texto += _formatearDecimal(mod340.total_taxable,15,2,True)
161
 
        texto += _formatearDecimal(mod340.total_sharetax,15,2,True)
162
 
        texto += _formatearDecimal(mod340.total,15,2,True)
163
 
        texto += 190*' '
164
 
        texto += _formatearCadena(mod340.vat_representative,9,' ',True)
165
 
        texto += 101*' '
166
 
        texto += '\r\n'
167
 
        #texto += _formatearCadena(mod340.name_surname,40,' ',True)
168
 
        #logger.notifyChannel('cabecera presentador: ',netsvc.LOG_INFO, texto)
169
 
        return texto
170
 
 
171
 
    def _line_issued_modelo_340(self,linea):
172
 
        #Datos Compañia
173
 
        company_obj = mod340.company_id
174
 
 
175
 
        texto = '2'
176
 
        texto += '340'
177
 
        texto += str(mod340.fiscalyear)
178
 
        texto += _formatearCadena(company_obj.partner_id.vat[2:len(company_obj.partner_id.vat)], 9, ' ', True)
179
 
        texto += _formatearCadena(linea['vat_declared'],9, ' ', True)
180
 
        texto += _formatearCadena(linea['vat_representative'],9, ' ', True)
181
 
        texto += _formatearCadena(linea['partner_name'],40, ' ', True)
182
 
        texto += _formatearCadena(linea['cod_country'],2, ' ', True)
183
 
        texto += _formatearCadena(linea['key_country'],1, ' ', True)
184
 
        texto += _formatearCadena(linea['vat_country'],20, ' ', True)
185
 
        texto += _formatearCadena(linea['key_book'],1, ' ', True)
186
 
        texto += _formatearCadena(linea['key_operation'],1, ' ', True)
187
 
        texto += linea['invoice_date'].replace('-','')
188
 
        texto += linea['operation_date'].replace('-','')
189
 
        texto += _formatearDecimal(linea['rate'],3,2,False)
190
 
        texto += _formatearDecimal(linea['taxable'],11,2,True)
191
 
        texto += _formatearDecimal(linea['share_tax'],11,2,True)
192
 
        texto += _formatearDecimal(linea['total'],11,2,True)
193
 
        texto += _formatearDecimal(linea['taxable_cost'],11,2,True)
194
 
        texto += _formatearCadena(linea['number'],40, ' ', True)
195
 
        texto += _formatearCadena(linea['number_amendment'],18, ' ', True)
196
 
        texto += _formatearDecimal(linea['number_invoices'],8,0,False)
197
 
        texto += _formatearDecimal(linea['number_records'],2,0,False)
198
 
        texto += _formatearCadena(linea['iterval_ini'],40, ' ', True)
199
 
        texto += _formatearCadena(linea['iterval_end'],40, ' ', True)
200
 
        texto += _formatearCadena(linea['invoice_corrected'],40, ' ', True)
201
 
        texto += _formatearDecimal(linea['charge'], 3, 2, False)
202
 
        texto += _formatearDecimal(linea['share_charge'],11, 2, True)
203
 
        texto += 116*' ' + '\r\n'
204
 
        #texto += '\r\n'
205
 
 
206
 
        return texto    
207
 
 
208
 
    txt_mod340 = ''
209
 
    log = Log()
210
 
    try:
211
 
        pool = pooler.get_pool(cr.dbname)
212
 
        mod340 = pool.get('l10n.es.aeat.mod340').browse(cr, uid, data['id'], context)
213
 
        contador = 1
214
 
        lines_issued = []
215
 
        #antes hay que generar las lineas
216
 
        txt_mod340 += _cabecera_modelo_340(self)
217
 
 
218
 
        #Generamos registros correspodientes a facturas expedidas
219
 
        #llenamos el diccionario
220
 
        for l in mod340.issued:
221
 
            lines_issued.append({
222
 
                'vat_declared' : l.vat_declared,
223
 
                'vat_representative' : l.vat_representative,
224
 
                'partner_name' : l.partner_name,
225
 
                'cod_country' : l.cod_country,
226
 
                'key_country' : l.key_country,
227
 
                'vat_country' : l.vat_country,
228
 
                'key_book' : l.key_book,
229
 
                'key_operation' : l.key_operation,
230
 
                'invoice_date' : l.invoice_date,
231
 
                'operation_date' : l.operation_date,
232
 
                'rate' : l.rate,
233
 
                'taxable' : l.taxable,
234
 
                'share_tax' : l.share_tax,
235
 
                'total' : l.total,
236
 
                'taxable_cost' : l.taxable_cost,
237
 
                'number' : l.number,
238
 
                #'number_amendment' : l.number_amendment,
239
 
                'number_amendment' : str(contador),  #demomento un contador hasta que vea como hacerlo bien
240
 
                #'number_invoices' :  l.number_invoices,
241
 
                'number_invoices' :  '1',
242
 
                #'number_records' :  l.number_records,
243
 
                'number_records' :  '1',
244
 
                'iterval_ini' :  l.iterval_ini,
245
 
                'iterval_end' :  l.iterval_end,
246
 
                'invoice_corrected' :  l.invoice_corrected,
247
 
                'charge' :  l.charge,
248
 
                'share_charge' :  l.share_charge,
249
 
            })
250
 
            contador = contador + 1
251
 
        for line_issued in lines_issued:
252
 
            txt_mod340 += _line_issued_modelo_340(self,line_issued)
253
 
 
254
 
    except Log:
255
 
        return {'note':log(), 'reference':mod340.id, 'mod340':False, 'state':'failed'}
256
 
    else:
257
 
        file = base64.encodestring(txt_mod340)
258
 
        #fname = (_('modelo340') + '_' + orden.mode.tipo + '_' + orden.reference + '.txt').replace('/','-')
259
 
        fname = (_('modelo340') + '_' + '.txt').replace('/','-')
260
 
        pool.get('ir.attachment').create(cr, uid, {
261
 
            #'name': _('Modelo340 ') + orden.mode.tipo + ' ' + orden.reference,
262
 
            'name': _('Modelo340 ') ,#+ orden.mode.tipo + ' ' + orden.reference,
263
 
            'datas': file,
264
 
            'datas_fname': fname,
265
 
            'res_model': 'l10n.es.aeat.mod340',
266
 
            'res_id': mod340.id,
267
 
            }, context=context)
268
 
        #log.add(_("Successfully Exported\n\nSummary:\n Total amount paid: %.2f\n Total Number of Payments: %d\n") % (-orden.total, num_recibos))
269
 
        pool.get('l10n.es.aeat.mod340').set_done(cr,uid,mod340.id,context)
270
 
 
271
 
        return {'note':log(), 'reference':mod340.id, 'mod340':file, 'mod340_fname':fname, 'state':'succeeded'}
272
 
 
273
 
class wizard_mod340_file(wizard.interface):
274
 
    states = {
275
 
        'init' : {
276
 
            'actions' : [],
277
 
            'result' : {'type' : 'form',
278
 
                        'arch' : mod340_form,
279
 
                        'fields' : mod340_fields,
280
 
                        'state' : [('end', 'Cancel'),('export', 'Export','gtk-ok') ]}
281
 
        },
282
 
        'export': {
283
 
            'actions' : [_create_mod340_file],
284
 
            'result' : {'type' : 'form',
285
 
                        'arch' : export_form,
286
 
                        'fields' : export_fields,
287
 
                        'state' : [('end', 'Ok','gtk-ok') ]}
288
 
        }
289
 
 
290
 
    }
291
 
wizard_mod340_file('export_mod340_file')
292
 
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
293