[go: up one dir, main page]

Menu

[r1]: / djrece / views.py  Maximize  Restore  History

Download this file

655 lines (503 with data), 24.7 kB

  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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# -*- coding: utf-8 -*-
# DjRece es una interfase web para utilizar PyRece desde una app de Django
""" DjRece: Copyright 2010 Alan Etkin, hexa662@gmail.com.
Este programa se distribuye bajo los términos de la licencia AGPLv3.
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, version 3 of the License, or 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 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/>.
"""
"""
PyRece - PyAfipWS es copyright de M. Reingart y M. Alániz
http://code.google.com/p/pyafipws/
"""
# Create your views here.
# almacena la direccion del servidor WS a utilizar
url_wsafip = None
url_wsfeafip = None
import configuracion, listas
import socket, pickle, tempfile, json, decimal
import email, os, sys, time, datetime, traceback
import pyrece.php, pyrece.wsfe, pyrece.wsaa
from M2Crypto import BIO, Rand, SMIME, SSL
from pyrece.php import date, SimpleXMLElement, SoapClient, SoapFault, parse_proxy
from pyrece.wsaa import create_tra, sign_tra, call_wsaa
from django.http import HttpResponse
from django.shortcuts import render_to_response
from models import *
# digito_verificador_modulo10 es una función extraída de PyRece
# copyright M.Alániz / M.Reingart
def digito_verificador_modulo10(codigo):
"Rutina para el cálculo del dígito verificador 'módulo 10'"
# http://www.consejo.org.ar/Bib_elect/diciembre04_CT/documentos/rafip1702.htm
# Etapa 1: comenzar desde la izquierda, sumar todos los caracteres ubicados en las posiciones impares.
etapa1 = sum([int(c) for i,c in enumerate(codigo) if not i%2])
# Etapa 2: multiplicar la suma obtenida en la etapa 1 por el número 3
etapa2 = etapa1 * 3
# Etapa 3: comenzar desde la izquierda, sumar todos los caracteres que están ubicados en las posiciones pares.
etapa3 = sum([int(c) for i,c in enumerate(codigo) if i%2])
# Etapa 4: sumar los resultados obtenidos en las etapas 2 y 3.
etapa4 = etapa2 + etapa3
# Etapa 5: buscar el menor número que sumado al resultado obtenido en la etapa 4 de un número múltiplo de 10. Este será el valor del dígito verificador del módulo 10.
digito = 10 - (etapa4 - (int(etapa4 / 10) * 10))
if digito == 10:
digito = 0
return str(digito)
def codigo_de_barras(cuit, tipo_cbt, punto_de_venta, cae, fecha_vto):
""" Devuelve un código de barras para el comprobante sin el dígito verificador.
falta el dígito verificador
"""
cuit = str(cuit)
tipo_cbt = str(tipo_cbt).zfill(2)
punto_de_venta = str(punto_de_venta).zfill(4)
cae = str(cae)
fecha_vto = str(fecha_vto)
barras = ''.join([cuit, tipo_cbt, punto_de_venta, cae, fecha_vto])
dvf = digito_verificador_modulo10(barras)
return barras + dvf
def nombreCbte(elnumero):
try:
elnumero = int(elnumero)
except ValueError:
elnumero = 0
elnombre = ""
for k, v in listas.tipo_cbte.iteritems():
if int(v) == elnumero:
elnombre = k
return elnombre
def imprimirOperacion(request):
""" """
import cbtapdf
# usuario autorizado a ver/imprimir facturas
laoperacion = Operacion.objects.get(pk = int(request.GET.get("operacion")))
if laoperacion == None:
raise Exception(u"No se encontró la operación en la base de datos.")
elcuit = configuracion.cuit
eltipodecbt = laoperacion.tipo_cbte
elpuntodeventa = laoperacion.punto_de_venta.numero
elcae = laoperacion.cae
lafechavto = laoperacion.fecha_vto
# obtener todo item o pago que tenga la operacion como referencia
queryitem = None
querypagos = None
lospagos = list()
lositem = list()
totalpagos = 0.0
totalitem = 0.0
totaloperacion = 0.0
totalliq = 0.0
totalneto = 0.0
netotmp = 0.0
liqtmp = 0.0
codigodebarras = None
cliente = None
fechatmp = None
queryitem = Item_de_Operacion.objects.filter(operacion = laoperacion)
querypagos = Pago.objects.filter(operaciones = laoperacion)
cliente = laoperacion.cliente
fechatmp = laoperacion.fecha.strftime("%d/%m/%y %H:%M:%S")
codigodebarras = codigo_de_barras(elcuit, eltipodecbt, elpuntodeventa, elcae, lafechavto)
for pago in querypagos:
lospagos.append(pago)
totalpagos += float(pago.valor)
for item in queryitem:
lositem.append(item)
netotmp = float(item.precio) * float(item.cantidad)
totalneto += netotmp
liqtmp = float(netotmp)*float(item.iva)/float(100.0)
totalliq += liqtmp
totalitem += liqtmp + netotmp
total_factura_tmp = decimal.Decimal(str(laoperacion.imp_total))
total_iva_tmp = decimal.Decimal(str(laoperacion.imp_liq))
subtotal_tmp = decimal.Decimal(str(laoperacion.imp_neto))
total_factura = moneyfmt(total_factura_tmp)
subtotal = moneyfmt(subtotal_tmp)
total_iva = moneyfmt(total_iva_tmp)
# crear pdf (devuelve un objeto StringIO con el PDF)
losimportes = (subtotal, total_iva, total_factura)
if int(laoperacion.servicios) != 1:
if int(laoperacion.tipo_cbte) in [4, 9]:
sio = cbtapdf.operacionpdf(cliente, laoperacion, lospagos, losimportes, codigodebarras, esrecibo = True)
else:
sio = cbtapdf.operacionpdf(cliente, laoperacion, lositem, losimportes, codigodebarras)
else:
if int(laoperacion.tipo_cbte) in [4, 9]:
sio = cbtapdf.operacionpdf(cliente, laoperacion, lospagos, losimportes, codigodebarras, esrecibo = True, \
servicio = True)
else:
sio = cbtapdf.operacionpdf(cliente, laoperacion, lositem, losimportes, codigodebarras, servicio = True)
sio.seek(0)
contenido = sio.read()
sio.close()
cadenatmp = str(laoperacion.punto_de_venta.numero) + "_" + str(laoperacion.tipo_cbte) + "_" + str(laoperacion.cbt_consultado)
response = HttpResponse(unicode(contenido, "latin-1"), mimetype = "application/pdf")
response['Content-Disposition'] = 'attachment; filename=%s.pdf' % cadenatmp
return response
def nuevocbte(request):
""" Devuelve un formulario genérico para un comprobante."""
clientes = Cliente.objects.all()
productos = Producto.objects.all()
puntos_de_venta = Punto_de_Venta.objects.all()
return render_to_response("djrece/nuevocbte.html", {"clientes": clientes, "productos": productos, "puntos_de_venta": puntos_de_venta, "razon_social": configuracion.razon_social, "cuit": configuracion.cuit})
def tipo_responsable(condicion):
tipo = None
condicion = condicion.upper()
if condicion == "RESPONSABLE INSCRIPTO":
tipo = "01"
elif condicion == "EXENTO":
tipo = "04"
elif condicion == "CONSUMIDOR FINAL":
tipo = "05"
elif condicion == "RESPONSABLE NO INSCRIPTO":
tipo = "02"
else:
pass
return tipo
def tipo_de_cbte(clase, nombre):
tipo = None
# (incompleto) obtener el tipo de cbte. (dos enteros)
if str(clase) == "A":
if str(nombre) == "Factura":
tipo = "01"
elif str(nombre) == "Nota_de_Credito":
tipo = "03"
elif str(nombre) == "Nota_de_Debito":
tipo = "02"
else:
pass
elif str(clase) == "B":
if str(nombre) == "Factura":
tipo = "06"
elif str(nombre) == "Nota_de_Credito":
tipo = "08"
elif str(nombre) == "Nota_de_Debito":
tipo = "07"
else:
pass
elif str(clase) == "C":
if str(nombre) == "Factura":
tipo = "11"
elif str(nombre) == "Nota_de_Credito":
tipo = "13"
elif str(nombre) == "Nota_de_Debito":
tipo = "12"
else:
pass
else:
pass
return tipo
class TicketViejo(Exception):
def __init__(self):
Exception.__init__(self, u'Ticket WSAA vencido. Intente la operación nuevamente.')
class ImporteInvalido(Exception):
def __init__(self):
Exception.__init__(self, u'El importe especificado no es válido.')
# código tomado de http://www.python.org en la documentación de las bibliotecas
# para python 2.6 - Python Software Foundation (c).
def moneyfmt(value, places=2, curr='', sep='.', dp=',',
pos='', neg='-', trailneg=''):
"""Convert Decimal to a money formatted string.
places: required number of places after the decimal point
curr: optional currency symbol before the sign (may be blank)
sep: optional grouping separator (comma, period, space, or blank)
dp: decimal point indicator (comma or period)
only specify as blank when places is zero
pos: optional sign for positive numbers: '+', space or blank
neg: optional sign for negative numbers: '-', '(', space or blank
trailneg:optional trailing minus indicator: '-', ')', space or blank
>>> d = Decimal('-1234567.8901')
>>> moneyfmt(d, curr='$')
'-$1,234,567.89'
>>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
'1.234.568-'
>>> moneyfmt(d, curr='$', neg='(', trailneg=')')
'($1,234,567.89)'
>>> moneyfmt(Decimal(123456789), sep=' ')
'123 456 789.00'
>>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
'<0.02>'
"""
q = decimal.Decimal(10) ** -places # 2 places --> '0.01'
sign, digits, exp = value.quantize(q).as_tuple()
result = []
digits = map(str, digits)
build, next = result.append, digits.pop
if sign:
build(trailneg)
for i in range(places):
build(next() if digits else '0')
build(dp)
if not digits:
build('0')
i = 0
while digits:
build(next())
i += 1
if i == 3 and digits:
i = 0
build(sep)
build(curr)
build(neg if sign else pos)
return ''.join(reversed(result))
def conexion_afip(request):
error = False
try:
lahora = datetime.datetime.now()
mensaje = str()
# datosjson = request.POST.get("datos")
# dictjson = json.loads(datosjson)
# tracedatos = Trace(trace = repr(dictjson))
# tracedatos.save()
ta_creado = None
ta_leido = None
ta_vencido = None
ta = None
tra = None
cms = None
lahora = None
CAE = None
ta_actualizado = False
# error = ""
datos_autenticar = (None, None)
# configuracion del url del servidor de AFIP
if True:
# homologacion
url_wsafip = configuracion.url_homologacion
url_wsfeafip = configuracion.url_fe_homologacion
else:
# produccion
# url_wsafip = url_produccion
# url_wsfeafip = url_fe_produccion
pass
archivo_ta_nombre = str(configuracion.cuit) + ".ta"
# Atencion: Aca la cantidad de archivos temporarios puede generar una saturacion del espacio del servidor y
# bloquear el servicio de autenticacion.
# si existe un ta que no vencio no hay que solicitar uno nuevo
if not (os.path.exists(configuracion.ruta_certificados)):
os.mkdir(configuracion.ruta_certificados)
ta_deltat = 0.0
if (archivo_ta_nombre) in os.listdir(configuracion.ruta_certificados):
# mensaje += ". Se encontro el archivo " + archivo_ta_nombre
# comparar fecha y hora (maxima diferencia 30 min.)
ta_creado = os.path.getmtime((configuracion.ruta_certificados + archivo_ta_nombre))
ta_creado_amdh = time.localtime(ta_creado)
ta_leido = time.time()
ta_leido_amdh = time.localtime(ta_leido)
ta_deltat = ta_leido - ta_creado
# mensaje += ". Delta t: " + str(ta_deltat)
# mensaje += ". TAC: " + str(ta_creado_amdh) + ". TAL: " + str(ta_leido_amdh)
ta_peso = os.path.getsize((configuracion.ruta_certificados + archivo_ta_nombre))
ta_vencido = ta_deltat > 36000.0
# mensaje += ". TA Vencido: " + str(ta_vencido)
if ((ta_vencido == False) and (ta_peso > 10)):
# mensaje += " TA no Vencido/Vacio "
# el ta no vencio
with open((configuracion.ruta_certificados + archivo_ta_nombre), "r") as archivo_ta:
xml = archivo_ta.read()
ta = SimpleXMLElement(xml)
datos_autenticar = (str(ta.credentials.token), str(ta.credentials.sign))
# mensaje += ". TA antes de condicion if: " + str(xml)
else:
pass
if ta == None:
if not (os.path.exists(configuracion.ruta_certificados)):
os.mkdir(configuracion.ruta_certificados)
# El TA vencio. Hay que solicitarlo nuevamente
# (incompleto) Recuperar los certificados para la interfase
# con WS (PyRECE)
# crea un TRA (estructura para cms)
tra = create_tra()
# el cms para solicitar el TA de wsaa
cms = sign_tra(tra, configuracion.certificado, configuracion.clave_privada)
# gestion del ta de wsaa. Obtener tupla (token, sign)
# es mas facil almacenar el xml de WS en un archivo
xml = call_wsaa(cms, url_wsafip)
# generar o abrir un archivo con nombre cuit + .ta (xml a convertir)
with open(configuracion.ruta_certificados + configuracion.cuit + ".ta", "w") as file_ta:
# almacenar el ta en el archivo para futuras solicitudes
file_ta.write(xml)
ta_actualizado = True
ta = SimpleXMLElement(xml)
datos_autenticar = (str(ta.credentials.token), str(ta.credentials.sign))
# para evitar un exceso de tiempo en la solicitud, salir devolviendo un aviso
# raise Exception("El servidor actualizo el permiso para solicitudes a AFIP WS, por favor \
# reintente la operacion.")
raise TicketViejo()
# Soap Client (objeto para conexion con wsfe)
try:
client = SoapClient(url_wsfeafip, action=pyrece.wsfe.SOAP_ACTION, namespace=pyrece.wsfe.SOAP_NS, trace=False, exceptions=True)
except IOError:
# Intento de pyrece de escribir en stdout
# bloqueado por Apache
errorview = Error(error = repr(e) + "\n" + str(traceback.format_exc()))
errorview.save()
raise
# Buscar inconsistencias de datos y cancelar la transaccion
# si la informacion es invalida (fecha, monto, datos).
# Devolver un str: "ERROR. Datos invalidos, no se genero el
# comprobante".
# Nota: falta codigo para validar el comprobante del lado del
# servicio de google para evitar almacenar comprobantes invalidos.
# Pasar los datos al formato compatible con (WSFE)
lpagos = list()
litem = list()
elpuntodeventa = Punto_de_Venta.objects.get(pk = int(request.POST.get("punto_de_venta")))
# obtener el cliente
elcliente = Cliente.objects.get(pk = long(request.POST.get("cliente_id")))
# vendedor
PUNTO_DE_VENTA = long(elpuntodeventa.numero)
CUIT = long(configuracion.cuit)
TIPO_CBTE = long(request.POST.get("tipo_cbte"))
# comprador
TIPO_DOC = long(elcliente.tipo_doc)
NRO_DOC = long(elcliente.numero_doc)
str_it = str(request.POST.get("imp_total"))
str_il = str(request.POST.get("imp_liq"))
str_in = str(request.POST.get("imp_neto"))
if (float(str_it) < 0.01) or (float(str_in) < 0.01):
raise ImporteInvalido()
IMP_TOTAL = decimal.Decimal(str_it)
IMP_LIQ = decimal.Decimal(str_il)
IMP_NETO = decimal.Decimal(str_in)
# Invocar el metodo de wsfe para generar un cbte.
# enviando la informacion con formato.
# dict que almacena el resultado de la transaccion con WSFE
dictaut = dict()
dictaut["error"] = False
ELID = None
ELCBTE = None
exito = False
try:
last_id = pyrece.wsfe.ultnro(client, datos_autenticar[0], datos_autenticar[1], CUIT)
last_cbte = pyrece.wsfe.recuperar_last_cmp(client, datos_autenticar[0], datos_autenticar[1], CUIT, PUNTO_DE_VENTA, TIPO_CBTE)
ELID = last_id +1
ELCBTE = last_cbte +1
except pyrece.wsfe.WSFEError as e:
mensaje += ". Error WSFE: " + str(e.code) + " - " + str(e.msg)
# si no se puede obtener un numero de cbt e id de transaccion, salir
# informando el error
# avisos en el script reenviados
dictaut["mensaje"] = mensaje
dictaut["exito"] = exito
dictaut["error"] = True
respuesta = json.dumps(dictaut)
erroridcbt = Error(error = mensaje)
erroridcbt.save()
raise
except socket.error as e:
errortipo = Error(error = str(type(e)) + " " + str(dir(e)))
errortipo.save()
if int(e.errno) == 104:
# mensaje
# avisos en el script reenviados
dictaut["mensaje"] = u"Error 104: el servidor de AFIP anuló la conexión."
dictaut["exito"] = False
dictaut["error"] = True
raise
raise
# autorizacion de comprobante
# (incompleto). Tomado de wsfe.main()
# crear un registro local de la operacion
# obtener el tipo de responsable
operacion = Operacion(cliente = elcliente, cliente_domicilio = elcliente.domicilio, cliente_localidad = elcliente.localidad.nombre, cliente_provincia = elcliente.provincia.nombre, tipo_cbte = TIPO_CBTE, tipo_cbte_nombre = nombreCbte(TIPO_CBTE), numero_doc_empresa = CUIT, tipo_doc_empresa = configuracion.tipo_doc, cond_iva_empresa = configuracion.cond_iva , cliente_doc = NRO_DOC, cliente_tipo_doc = TIPO_DOC, id_consultado = ELID, cbt_consultado = ELCBTE, \
punto_de_venta = elpuntodeventa, imp_total = float(IMP_TOTAL), \
imp_neto = float(IMP_NETO), imp_liq = float(IMP_LIQ), cliente_nombre = elcliente.razon_social, \
cliente_tipo_responsable = elcliente.condicion_iva, servicios = request.POST.get("presta_serv"), \
servicios_periodo_desde = str(request.POST.get("serv_desde")), servicios_periodo_hasta = str(request.POST.get("serv_hasta")), \
nota = unicode(request.POST.get("nota")))
# confirma el registro en la base de datos local
operacion.forma_de_pago = request.POST.get("forma_de_pago")
operacion.punto_de_venta_numero = elpuntodeventa.numero
operacion.punto_de_venta_domicilio = elpuntodeventa.domicilio
operacion.punto_de_venta_codigo_postal = elpuntodeventa.codigo_postal
operacion.percepcion_iibb = "0"
operacion.jurisd_iibb = "01"
operacion.save()
# registro de item y pagos del cbte. el cliente envía una cantidad x de item y pagos
# con una referencia a la cantidad "cantidad_item" y "cantidad_pagos". los índices son
# desde cero (i_0_id, i_0_cantidad; p_0_tipo, p_0_valor...
cantidad_item = int(request.POST.get("cantidad_item"))
cantidad_pagos = int(request.POST.get("cantidad_pagos"))
for x in range(cantidad_item):
elproducto = Producto.objects.get(pk = int(request.POST.get("i_" + str(x) + "_id")))
lacantidad = request.POST.get("i_" + str(x) + "_cantidad")
elitem = Item_de_Operacion(operacion = operacion, producto = elproducto, nombre = elproducto.nombre_corto, precio = elproducto.precio, iva = elproducto.iva, cantidad = lacantidad, unidad = elproducto.unidad_de_medida, codigo = elproducto.codigo)
elitem.save()
litem.append(elitem)
for x in range(cantidad_pagos):
elpago = Pago(tipo = request.POST.get("p_" + str(x) + "_tipo"), codigo = request.POST.get("p_" + str(x) + "_codigo"), valor = request.POST.get("p_" + str(x) + "_valor"), banco = request.POST.get("p_" + str(x) + "_banco"))
elpago.save()
elpago.operaciones.add(operacion)
elpago.save()
lpagos.append(elpago)
# enviar un comprobante por vez (ELCBTE). Se usa un numero para "desde" y "hasta"
SERVDDE = request.POST.get("serv_desde")
SERVHTA = request.POST.get("serv_hasta")
try:
SERV = int(request.POST.get("presta_serv"))
except ValueError:
SERV = 0
if SERV == 1:
try:
datetime.date(int(SERVHTA[0:4]), int(SERVHTA[4:6]), int(SERVHTA[6:]))
datetime.date(int(SERVDDE[0:4]), int(SERVDDE[4:6]), int(SERVDDE[6:]))
except ValueError, IndexError:
raise Exception(u"Las fechas del servicio no son válidas.")
if (request.POST.get("serv_desde") != "") and (int(SERV) != 0):
SERVDDE = str(request.POST.get("serv_desde"))
SERVHTA = str(request.POST.get("serv_hasta"))
try:
dictaut = pyrece.wsfe.aut(client, datos_autenticar[0], datos_autenticar[1], \
CUIT, ELID, tipo_doc=TIPO_DOC, nro_doc=NRO_DOC, punto_vta=PUNTO_DE_VENTA, \
tipo_cbte=TIPO_CBTE, imp_total=IMP_TOTAL, imp_neto=IMP_NETO, impto_liq=IMP_LIQ, cbt_desde=ELCBTE, \
cbt_hasta=ELCBTE, presta_serv = SERV, fecha_serv_desde = SERVDDE, fecha_serv_hasta = SERVHTA)
# Almacenar el id y los demas datos en una tabla para poder recuperar la transaccion.
# (incompleto)
# Registrar importes y numeros de afip si
# se genero el comprobante
# Actualizar los datos del comprobante en la base de datos local
operacion.cae = str(dictaut["cae"])
# operacion.fecha_vto = lafechadevtotmp
operacion.resultado = dictaut["resultado"]
operacion.motivo = str(dictaut["motivo"])
operacion.reproceso = dictaut["reproceso"]
operacion.fecha_vto = dictaut["fecha_vto"]
operacion.save()
exito = True
# No se puede devolver la transaccion en una cadena simple:
# Hay que registrar el id, el nro de cbte, y el CAE en la b.dd.
dictaut["cbt"] = ELCBTE
dictaut["id"] = ELID
dictaut["tipo_cbt"] = TIPO_CBTE
dictaut["mensaje"] = u"Se completó la operación."
dictaut["exito"] = exito
dictaut["error"] = False
eltrace = Trace(trace = str(dictaut))
eltrace.save()
# incompleto: generar la respuesta en html
return render_to_response("djrece/resultadocbte.html", {"operacion": operacion, "cbte": dictaut["cbt"], "id": dictaut["id"], "tipo_cbt": dictaut["tipo_cbt"], "mensaje": dictaut["mensaje"], "exito": dictaut["exito"], "error": dictaut["error"], "nombres_cbte": listas.tipo_cbte, "razon_social": configuracion.razon_social, "cuit": configuracion.cuit, "pagos": lpagos, "item": litem})
except pyrece.wsfe.WSFEError as e:
mensaje += ". Error WSFE: " + str(e.code) + " - " + str(e.msg)
dictaut["cbt"] = ELCBTE
dictaut["id"] = ELID
dictaut["mensaje"] = mensaje # avisos en el script reenviados
dictaut["exito"] = exito
dictaut["error"] = True
errorwsfe = Error(error = mensaje)
errorwsfe.save()
raise
except TicketViejo as e:
errorview = Error(error = repr(e))
errorview.save()
raise
# previene CUALQUIER error (modificar, no es recomendable)
except Exception as e:
errorview = Error(error = repr(e) + "\n" + str(traceback.format_exc()))
errorview.save()
raise