def __init__(self, privada, certificado, cuit): # instanciar el componente para factura electrónica mercado interno self.webservice = WSFEv1() self.webservice.LanzarExcepciones = True # datos de conexión (cambiar URL para producción) cache = None wsdl = AFIP_WSDL_URL proxy = "" wrapper = "" cacert = None # conectar try: self.webservice.Conectar(cache, wsdl, proxy, wrapper, cacert) except (ExpatError, ServerNotFoundError, SoapFault): raise AfipErrorRed("Error en la conexion inicial con la AFIP.") self.cert = certificado # archivos a tramitar previamente ante AFIP self.clave = privada self.wsaa_url = AFIP_WSAA_URL self.wsaa = WSAA() self.autenticar() self.webservice.Cuit = cuit
def _get_ws(self, afip_ws): """ Method to be inherited """ ws = super(AfipwsConnection, self)._get_ws(afip_ws) if afip_ws == 'wsfe': from pyafipws.wsfev1 import WSFEv1 ws = WSFEv1() elif afip_ws == "wsfex": from pyafipws.wsfexv1 import WSFEXv1 ws = WSFEXv1() elif afip_ws == "wsmtxca": from pyafipws.wsmtx import WSMTXCA ws = WSMTXCA() elif afip_ws == "wscdc": from pyafipws.wscdc import WSCDC ws = WSCDC() elif afip_ws == "ws_sr_padron_a4": from pyafipws.ws_sr_padron import WSSrPadronA4 ws = WSSrPadronA4() if self.type == 'production': ws.H**O = False ws.WSDL = "https://aws.afip.gov.ar/sr-padron/webservices/personaServiceA4?wsdl" elif afip_ws == "ws_sr_constancia_inscripcion": from pyafipws.ws_sr_padron import WSSrPadronA5 ws = WSSrPadronA5() if self.type == 'production': ws.H**O = False ws.WSDL = "https://aws.afip.gov.ar/sr-padron/webservices/personaServiceA5?wsdl" return ws
def setUp(self): sys.argv.append("--trace") # TODO: use logging self.wsfev1 = wsfev1 = WSFEv1() wsfev1.Cuit = CUIT wsfev1.Token = wsaa.Token wsfev1.Sign = wsaa.Sign wsfev1.Conectar(CACHE, WSDL)
def test_pyafipws_dummy(self, cr, uid, ids, context=None): for journal in self.browse(cr, uid, ids): company = journal.company_id tipo_cbte = journal.pyafipws_invoice_type punto_vta = journal.pyafipws_point_of_sale service = journal.pyafipws_electronic_invoice_service # import AFIP webservice helper for electronic invoice if service == "wsfe": from pyafipws.wsfev1 import WSFEv1 ws = WSFEv1() elif service == "wsfex": from pyafipws.wsfexv1 import WSFEXv1 ws = WSFEXv1() elif service == "wsmtxca": from pyafipws.wsmtx import WSMTXCA ws = WSMTXCA() # create the proxy and get the configuration system parameters: cfg = self.pool.get('ir.config_parameter') cache = cfg.get_param(cr, uid, 'pyafipws.cache', context=context) proxy = cfg.get_param(cr, uid, 'pyafipws.proxy', context=context) wsdl = cfg.get_param(cr, uid, 'pyafipws.%s.url' % service, context=context) # connect to the webservice and call to the test method ws.Conectar(cache or "", wsdl or "", proxy or "") ws.Dummy() msg = "AFIP service %s " \ "AppServerStatus: %s DbServerStatus: %s AuthServerStatus: %s" msg = msg % ( service, ws.AppServerStatus, ws.DbServerStatus, ws.AuthServerStatus) self.log(cr, uid, ids[0], msg) return {}
def _get_afip(): """Build and authenticate AFIP structure.""" # AFIP init wsaa = WSAA() wsfev1 = WSFEv1() # get access ticket (token y sign) certificate = settings.AFIP['auth_cert_path'] private_key = settings.AFIP['auth_key_path'] if not os.path.exists(certificate): raise ValueError( "Auth certificate can not be found (got {!r})".format(certificate)) if not os.path.exists(private_key): raise ValueError( "Auth key can not be found (got {!r})".format(private_key)) ta = wsaa.Autenticar("wsfe", certificate, private_key, wsdl=settings.AFIP['url_wsaa'], cache=CACHE, debug=True) wsfev1.Cuit = settings.AFIP['cuit'] wsfev1.SetTicketAcceso(ta) wsfev1.Conectar(CACHE, settings.AFIP['url_wsfev1']) return wsfev1
def test_pyafipws_point_of_sales(self, cr, uid, ids, context=None): for journal in self.browse(cr, uid, ids): company = journal.company_id tipo_cbte = journal.pyafipws_invoice_type punto_vta = journal.pyafipws_point_of_sale service = journal.pyafipws_electronic_invoice_service # authenticate against AFIP: auth_data = company.pyafipws_authenticate(service=service) # import AFIP webservice helper for electronic invoice from pyafipws.wsfev1 import WSFEv1 wsfev1 = WSFEv1() # create the proxy and get the configuration system parameters: cfg = self.pool.get('ir.config_parameter') cache = cfg.get_param(cr, uid, 'pyafipws.cache', context=context) proxy = cfg.get_param(cr, uid, 'pyafipws.proxy', context=context) wsdl = cfg.get_param(cr, uid, 'pyafipws.%s.url' % service, context=context) # connect to the webservice and call to the test method wsfev1.Conectar(cache or "", wsdl or "", proxy or "") # set AFIP webservice credentials: wsfev1.Cuit = company.pyafipws_cuit wsfev1.Token = auth_data['token'] wsfev1.Sign = auth_data['sign'] # call the webservice method to get the enabled point of sales: ret = wsfev1.ParamGetPtosVenta(sep=" ") msg = "Pts.Vta. Habilitados en AFIP: " + '. '.join(ret) msg += " - ".join([wsfev1.Excepcion, wsfev1.ErrMsg, wsfev1.Obs]) self.log(cr, uid, ids[0], msg) return {}
def get_afip_rate(self, service='wsfex'): ''' get rate from afip webservice. ''' pool = Pool() Company = pool.get('company.company') company_id = Transaction().context.get('company') if not company_id: logger.error('The company is not defined') cls.raise_user_error('company_not_defined') company = Company(company_id) # authenticate against AFIP: auth_data = company.pyafipws_authenticate(service=service) if service == 'wsfe': ws = WSFEv1() if company.pyafipws_mode_cert == 'homologacion': WSDL = 'https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL' elif company.pyafipws_mode_cert == 'produccion': WSDL = ( 'https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL') elif service == 'wsfex': ws = WSFEXv1() if company.pyafipws_mode_cert == 'homologacion': WSDL = 'https://wswhomo.afip.gov.ar/wsfexv1/service.asmx?WSDL' elif company.pyafipws_mode_cert == 'produccion': WSDL = ( 'https://servicios1.afip.gov.ar/wsfexv1/service.asmx?WSDL') else: logger.critical('AFIP ws is not yet supported! %s', service) cls.raise_user_error('webservice_not_supported', service) cache_dir = afip_auth.get_cache_dir() ws.LanzarExcepciones = True try: ws.Conectar(wsdl=wsdl, cache=cache_dir) except Exception as e: msg = ws.Excepcion + ' ' + str(e) logger.error('WSAA connecting to afip: %s' % msg) cls.raise_user_error('wsaa_error', msg) ws.Cuit = vat_number ws.Token = auth_data['token'] ws.Sign = auth_data['sign'] if not date: Date = pool.get('ir.date') today = Date.today().strftime("%Y%m%d") if not self.currency.afip_code: logger.error('AFIP code is empty %s', self.currency.code) cls.raise_user_error('afip_code_empty') self.rate = Decimal(ws.GetParamCtz('DOL')) self.date = datetime.datetime.strptime(ws.FchCotiz, '%Y%m%d').date()
def get_afip_rate(self, service='wsfex'): ''' get rate from afip webservice. ''' pool = Pool() Company = pool.get('company.company') company_id = Transaction().context.get('company') if not company_id: logger.error('The company is not defined') raise UserError( gettext('account_invoice_ar.msg_company_not_defined')) company = Company(company_id) # authenticate against AFIP: ta = company.pyafipws_authenticate(service=service) if service == 'wsfe': ws = WSFEv1() if company.pyafipws_mode_cert == 'homologacion': WSDL = 'https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL' elif company.pyafipws_mode_cert == 'produccion': WSDL = ( 'https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL') elif service == 'wsfex': ws = WSFEXv1() if company.pyafipws_mode_cert == 'homologacion': WSDL = 'https://wswhomo.afip.gov.ar/wsfexv1/service.asmx?WSDL' elif company.pyafipws_mode_cert == 'produccion': WSDL = ( 'https://servicios1.afip.gov.ar/wsfexv1/service.asmx?WSDL') else: logger.critical('AFIP ws is not yet supported! %s', service) raise UserError( gettext('account_invoice_ar.msg_webservice_not_supported', service=service)) cache = Company.get_cache_dir() ws.LanzarExcepciones = True try: ws.Conectar(wsdl=WSDL, cache=cache, cacert=True) except Exception as e: msg = ws.Excepcion + ' ' + str(e) logger.error('WSAA connecting to afip: %s' % msg) raise UserError( gettext('account_invoice_ar.msg_wsaa_error', msg=msg)) ws.SetTicketAcceso(ta) ws.Cuit = company.party.vat_number if not self.currency.afip_code: logger.error('AFIP code is empty %s', self.currency.code) raise UserError(gettext('account_invoice_ar.msg_afip_code_empty')) self.rate = Decimal(ws.GetParamCtz('DOL')) self.date = datetime.datetime.strptime(ws.FchCotiz, '%Y%m%d').date()
def _get_ws(self, afip_ws): """ Method to be inherited """ ws = super(AfipwsConnection, self)._get_ws(afip_ws) if afip_ws == 'wsfe': from pyafipws.wsfev1 import WSFEv1 ws = WSFEv1() elif afip_ws == "wsfex": from pyafipws.wsfexv1 import WSFEXv1 ws = WSFEXv1() elif afip_ws == "wsmtxca": from pyafipws.wsmtx import WSMTXCA ws = WSMTXCA() return ws
def get_wsfev1(company=None, config=None): "return wsfev1 object" if not company: company = get_company() company = set_afip_certs(company, config) URL_WSAA = "https://wsaahomo.afip.gov.ar/ws/services/LoginCms?wsdl" URL_WSFEv1 = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL" crt = get_filename('party_ar/tests/gcoop.crt') key = get_filename('party_ar/tests/gcoop.key') ta = WSAA().Autenticar('wsfe', crt, key, URL_WSAA, cacert=True) wsfev1 = WSFEv1() wsfev1.LanzarExcepciones = True wsfev1.SetTicketAcceso(ta) wsfev1.Cuit = company.party.vat_number wsfev1.Conectar(wsdl=URL_WSFEv1, cacert=True) return wsfev1
def get_pyafipws_last_invoice(self, cr, uid, ids, fields_name=None, arg=None, context=None): ret = {} for journal in self.browse(cr, uid, ids): company = journal.company_id tipo_cbte = journal.pyafipws_invoice_type punto_vta = journal.pyafipws_point_of_sale service = journal.pyafipws_electronic_invoice_service # authenticate: auth_data = company.pyafipws_authenticate(service=service) # import AFIP webservice helper for electronic invoice if service == "wsfe": from pyafipws.wsfev1 import WSFEv1 ws = WSFEv1() elif service == "wsfex": from pyafipws.wsfexv1 import WSFEXv1 ws = WSFEXv1() elif service == "wsmtxca": from pyafipws.wsmtx import WSMTXCA ws = WSMTXCA() # create the proxy and get the configuration system parameters: cfg = self.pool.get('ir.config_parameter') cache = cfg.get_param(cr, uid, 'pyafipws.cache', context=context) proxy = cfg.get_param(cr, uid, 'pyafipws.proxy', context=context) wsdl = cfg.get_param(cr, uid, 'pyafipws.%s.url' % service, context=context) # connect to the webservice and call to the query method ws.Conectar(cache or "", wsdl or "", proxy or "") if auth_data['token']: # set AFIP webservice credentials: ws.Cuit = company.pyafipws_cuit ws.Token = auth_data['token'] ws.Sign = auth_data['sign'] # call the webservice method to get the last invoice at AFIP: if service == "wsfe" or service == "wsmtxca": ult = ws.CompUltimoAutorizado(tipo_cbte, punto_vta) elif service == "wsfex": ult = ws.GetLastCMP(tipo_cbte, punto_vta) msg = " - ".join([ws.Excepcion, ws.ErrMsg, ws.Obs]) self.log(cr, uid, ids[0], u"Ult.Cbte: N° %s %s" % (ult, msg)) ret[journal.id] = str(ult) else: msg = auth_data['err_msg'] raise osv.except_osv(_("ERROR"), msg) return ret
def ultimo_cpb_afip(request, tipo_cpb, pto_vta): empresa = empresa_actual(request) H**O = empresa.homologacion if H**O: WSDL = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaahomo.afip.gov.ar/ws/services/LoginCms" else: WSDL = "https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaa.afip.gov.ar/ws/services/LoginCms" appserver_status = '' dbserver_status = '' authserver_status = '' #try: fecha = datetime.now().strftime("%Y%m%d") wsfev1 = WSFEv1() wsfev1.Conectar(wsdl=WSDL) cuit = empresa.cuit # cuit = 30714843571 wsfev1.Cuit = cuit crt = empresa.fe_crt key = empresa.fe_key wsfev1.Token, wsfev1.Sign = _autenticar(request, crt=crt, key=key, cuit=cuit) wsfev1.Dummy() appserver_status = wsfev1.AppServerStatus dbserver_status = wsfev1.DbServerStatus authserver_status = wsfev1.AuthServerStatus ult_nro = long(wsfev1.CompUltimoAutorizado(tipo_cpb, pto_vta) or 0) return ult_nro
def import_afip_countrys(cls, configs): ''' Import AFIP countrys. ''' pool = Pool() Company = pool.get('company.company') AFIPCountry = pool.get('afip.country') company = Company(Transaction().context.get('company')) service = 'wsfe' auth_data = company.pyafipws_authenticate(service=service) ws = WSFEv1() if company.pyafipws_mode_cert == 'homologacion': WSDL = 'https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL' elif company.pyafipws_mode_cert == 'produccion': WSDL = ( 'https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL') else: logger.error('Webservice not configured!') return cache_dir = company.get_cache_dir() ws.Conectar(wsdl=WSDL, cache=cache_dir) ws.Cuit = company.party.vat_number ws.Token = auth_data['token'] ws.Sign = auth_data['sign'] countrys = ws.ParamGetTiposPaises(sep=';') for country in countrys: afip_country = AFIPCountry() (code, name) = country.split(';') try: country_tmp, = AFIPCountry.search([('code', '=', code)]) except ValueError: afip_country.code = code afip_country.name = name afip_country.save() Transaction().cursor.commit() logger.info('code: %s; dst: %s' % (code, name))
def facturarAFIP_simulac(request, idCpb): empresa = empresa_actual(request) H**O = empresa.homologacion if H**O: WSDL = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaahomo.afip.gov.ar/ws/services/LoginCms" else: WSDL = "https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaa.afip.gov.ar/ws/services/LoginCms" token = '' sign = '' cae = '' fecha_vencimiento = '' cpb_nro = '' resultado = '' motivo = '' reproceso = '' observaciones = '' concepto = '' tipo_cpb = '' pto_vta = '' fecha_cbte = '' imp_total = '' imp_tot_conc = '' imp_neto = '' imp_op_ex = '' imp_trib = '' imp_iva = '' moneda_id = '' moneda_ctz = '' detalle = '' ult_nro = '' errores = '' factura = '' data = { 'token': token, 'sign': sign, 'cae': cae, 'fecha_vencimiento': fecha_vencimiento, 'cpb_nro': cpb_nro, 'resultado': resultado, 'motivo': motivo, 'reproceso': reproceso, 'observaciones': observaciones, 'concepto': concepto, 'tipo_cbte': tipo_cpb, 'punto_vta': pto_vta, 'fecha_cbte': fecha_cbte, 'imp_total': imp_total, 'imp_tot_conc': imp_tot_conc, 'imp_neto': imp_neto, 'imp_op_ex': imp_op_ex, 'imp_trib': imp_trib, 'imp_iva': imp_iva, 'moneda_id': moneda_id, 'moneda_ctz': moneda_ctz, 'detalle': detalle, 'ult_nro': ult_nro, 'excepcion': '', 'traceback': '', 'XmlRequest': '', 'XmlResponse': '', 'appserver_status': '', 'dbserver_status': '', 'authserver_status': '', 'errores': errores, 'factura': factura, } try: cpb = cpb_comprobante.objects.get(pk=idCpb) except: cpb = None if not cpb: data['errores'] = u'¡El comprobante no es válido!' return data resultado = validarAFIP(idCpb) if resultado != '': data['errores'] = resultado return data cpb_nafip = cpb.get_nro_afip() #Traigo el comprobante try: cpb_nafip = cpb.get_nro_afip() tipo_cpb = cpb_nafip pto_vta = int(cpb.pto_vta) nro_cpb = int(cpb.numero) except: data['errores'] = u'¡El comprobante no es válido!' return data #Si el pto_vta no admite factura electrónica if not cpb.get_pto_vta().fe_electronica: data[ 'errores'] = u'¡El Punto de Venta seleccionado no admite factura electrónica!' return data appserver_status = '' dbserver_status = '' authserver_status = '' # import time # time.sleep(25) # print data # return data fecha = datetime.now().strftime("%Y%m%d") wsfev1 = WSFEv1() wsfev1.Conectar(wsdl=WSDL) f = cpb cuit = cpb.get_pto_vta().cuit # cuit = 30714843571 wsfev1.Cuit = cuit #wsfev1.Cuit = 30715026178 if H**O: crt = empresa.fe_crt key = empresa.fe_key else: try: #crt = "COPYFAST_PRUEBA.crt" crt = cpb.get_pto_vta().fe_crt except: data['errores'] = u'¡fe_crt no es válido!' return data try: key = cpb.get_pto_vta().fe_key #key= "COPYFAST_PRUEBA.key" except: data['errores'] = u'¡fe_key no es válido!' return data wsfev1.Token, wsfev1.Sign = _autenticar(request, crt=crt, key=key, cuit=cuit) token = wsfev1.Token sign = wsfev1.Sign wsfev1.Dummy() appserver_status = wsfev1.AppServerStatus dbserver_status = wsfev1.DbServerStatus authserver_status = wsfev1.AuthServerStatus ultimo_cbte_afip = long( wsfev1.CompUltimoAutorizado(tipo_cpb, pto_vta) or 0) try: ultimo_cbte_sistema = obtener_ultimo_cpb_afip(request, cpb.cpb_tipo, cpb.pto_vta).numero except: ultimo_cbte_sistema = ultimo_cbte_afip #Si el ultimo de afip no existe en el sistema lo genero, sinó lo recupero if (ultimo_cbte_afip > ultimo_cbte_sistema): datos_cpb = recuperar_cpb_afip(request, tipo_cpb, pto_vta, ultimo_cbte_afip) data.update(factura=datos_cpb['factura']) return data else: cbt_desde = ultimo_cbte_afip + 1 cbt_hasta = ultimo_cbte_afip + 1 #sigo con la creacion del cpb y obtengo el CAE print "Ultimo CPB Autorizado en AFIP %s y en el Sistema %s" % ( ultimo_cbte_afip, ultimo_cbte_sistema) print u"Comprobante Nº: %s CAE Nº: %s Fecha Venc: %s" % ( data['cpb_nro'], data['cae'], data['fecha_vencimiento']) print data['factura'] return data
def facturarAFIP(request, idCpb): empresa = empresa_actual(request) H**O = empresa.homologacion if H**O: WSDL = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaahomo.afip.gov.ar/ws/services/LoginCms" else: WSDL = "https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaa.afip.gov.ar/ws/services/LoginCms" token = '' sign = '' cae = '' fecha_vencimiento = '' cpb_nro = '' resultado = '' motivo = '' reproceso = '' observaciones = '' concepto = '' tipo_cpb = '' pto_vta = '' fecha_cbte = '' imp_total = '' imp_tot_conc = '' imp_neto = '' imp_op_ex = '' imp_trib = '' imp_iva = '' moneda_id = '' moneda_ctz = '' detalle = '' ult_nro = '' errores = '' data = { 'token': token, 'sign': sign, 'cae': cae, 'fecha_vencimiento': fecha_vencimiento, 'cpb_nro': cpb_nro, 'resultado': resultado, 'motivo': motivo, 'reproceso': reproceso, 'observaciones': observaciones, 'concepto': concepto, 'tipo_cbte': tipo_cpb, 'punto_vta': pto_vta, 'fecha_cbte': fecha_cbte, 'imp_total': imp_total, 'imp_tot_conc': imp_tot_conc, 'imp_neto': imp_neto, 'imp_op_ex': imp_op_ex, 'imp_trib': imp_trib, 'imp_iva': imp_iva, 'moneda_id': moneda_id, 'moneda_ctz': moneda_ctz, 'detalle': detalle, 'ult_nro': ult_nro, 'excepcion': '', 'traceback': '', 'XmlRequest': '', 'XmlResponse': '', 'appserver_status': '', 'dbserver_status': '', 'authserver_status': '', 'errores': errores, } try: cpb = cpb_comprobante.objects.get(pk=idCpb) except: cpb = None if not cpb: data['errores'] = u'¡El comprobante no es válido!' return data resultado = validarAFIP(idCpb) if resultado != '': data['errores'] = resultado return data cpb_nafip = cpb.get_nro_afip() #Traigo el comprobante try: cpb_nafip = cpb.get_nro_afip() tipo_cpb = cpb_nafip pto_vta = int(cpb.pto_vta) nro_cpb = int(cpb.numero) except: data['errores'] = u'¡El comprobante no es válido!' return data #Si el pto_vta no admite factura electrónica if not cpb.get_pto_vta().fe_electronica: data[ 'errores'] = u'¡El Punto de Venta seleccionado no admite factura electrónica!' return data appserver_status = '' dbserver_status = '' authserver_status = '' try: wsfev1 = WSFEv1() wsfev1.Conectar(wsdl=WSDL) f = cpb cuit = cpb.get_pto_vta().cuit # cuit = 30714843571 wsfev1.Cuit = cuit #wsfev1.Cuit = 30715026178 if H**O: crt = empresa.fe_crt key = empresa.fe_key else: try: #crt = "COPYFAST_PRUEBA.crt" crt = cpb.get_pto_vta().fe_crt except: data['errores'] = u'¡fe_crt no es válido!' return data try: key = cpb.get_pto_vta().fe_key #key= "COPYFAST_PRUEBA.key" except: data['errores'] = u'¡fe_key no es válido!' return data wsfev1.Token, wsfev1.Sign = _autenticar(request, crt=crt, key=key, cuit=cuit) token = wsfev1.Token sign = wsfev1.Sign wsfev1.Dummy() appserver_status = wsfev1.AppServerStatus dbserver_status = wsfev1.DbServerStatus authserver_status = wsfev1.AuthServerStatus ultimo_cbte_afip = long( wsfev1.CompUltimoAutorizado(tipo_cpb, pto_vta) or 0) except Exception as e: data['excepcion'] = wsfev1.Excepcion data['traceback'] = wsfev1.Traceback data['XmlRequest'] = wsfev1.XmlRequest data['XmlResponse'] = wsfev1.XmlResponse data['appserver_status'] = appserver_status data['dbserver_status'] = dbserver_status data['authserver_status'] = authserver_status data[ 'errores'] = u'¡Falló la comunicación con los servidores de AFIP / Certificados NO VALIDOS! (' + str( e) + ')' #data['errores']= str(e) return data try: fecha = datetime.now().strftime("%Y%m%d") concepto = 3 #Productos y Servicios #tipo_doc = f.entidad.tipo_doc nro_doc, tipo_doc = f.entidad.get_nro_doc_afip() if not tipo_doc: data['errores'] = u'¡Debe cargar un tipo de Documento válido!' return data if nro_doc == '': data['errores'] = u'¡Debe cargar un Nº de Documento válido!' data['excepcion'] = wsfev1.Excepcion data['traceback'] = wsfev1.Traceback data['XmlRequest'] = wsfev1.XmlRequest data['XmlResponse'] = wsfev1.XmlResponse data['appserver_status'] = appserver_status data['dbserver_status'] = dbserver_status data['authserver_status'] = authserver_status return data # try: # ultimo_cbte_sistema = obtener_ultimo_cpb_afip(request,cpb.cpb_tipo,cpb.pto_vta).numero # except: # ultimo_cbte_sistema = ultimo_cbte_afip # #Si el ultimo de afip no existe en el sistema genero los faltantes en el sistema y sigo # if (ultimo_cbte_afip>ultimo_cbte_sistema): # # data['errores']=u'¡El ultimo nro de AFIP es %s, verifique!'%ultimo_cbte_afip # # data['excepcion']=wsfev1.Excepcion # # data['traceback']=wsfev1.Traceback # # data['XmlRequest']=wsfev1.XmlRequest # # data['XmlResponse']=wsfev1.XmlResponse # # data['appserver_status']=appserver_status # # data['dbserver_status']=dbserver_status # # data['authserver_status']=authserver_status # # datos_cpb = recuperar_cpb_afip(request,tipo_cpb,pto_vta,ultimo_cbte_afip) # # return data # ultimo_cbte_sistema = ultimo_cbte_afip cbt_desde = ultimo_cbte_afip + 1 cbt_hasta = ultimo_cbte_afip + 1 #Informar o no IVA #Datos de http://www.sistemasagiles.com.ar/trac/wiki/ManualPyAfipWs#FacturaCMonotributoExento if f.letra == 'C': imp_total = f.importe_total imp_tot_conc = 0 imp_neto = f.importe_total imp_iva = 0 imp_trib = 0 imp_op_ex = 0 else: imp_total = f.importe_total imp_tot_conc = f.importe_no_gravado imp_neto = f.importe_gravado imp_iva = f.importe_iva imp_trib = f.importe_perc_imp imp_op_ex = f.importe_exento fecha_cbte = f.fecha_cpb.strftime("%Y%m%d") fecha_venc_pago = f.fecha_cpb.strftime("%Y%m%d") # Fechas del período del servicio facturado (solo si concepto = 1?) fecha_serv_desde = f.fecha_cpb.strftime("%Y%m%d") fecha_serv_hasta = f.fecha_cpb.strftime("%Y%m%d") moneda_id = 'PES' moneda_ctz = '1.000' # Inicializo la factura interna con los datos de la cabecera ok = wsfev1.CrearFactura(concepto, tipo_doc, nro_doc, tipo_cpb, pto_vta, cbt_desde, cbt_hasta, imp_total, imp_tot_conc, imp_neto, imp_iva, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, fecha_serv_desde, fecha_serv_hasta, moneda_id, moneda_ctz) #Si crea el cpb ya se lo guardo if ok: cpb.numero = int(cbt_desde) cpb.save() else: data['errores'] = u'¡No pudo crearse el CPB en AFIP!' data['excepcion'] = wsfev1.Excepcion data['traceback'] = wsfev1.Traceback data['XmlRequest'] = wsfev1.XmlRequest data['XmlResponse'] = wsfev1.XmlResponse data['appserver_status'] = appserver_status data['dbserver_status'] = dbserver_status data['authserver_status'] = authserver_status return data if f.letra != 'C': #Traigo los coeficientes de IVA # iva_id: código Alícuota de IVA (según tabla de parámetros AFIP) # base_imp: base imponible (importe) # importe_iva: importe liquidado (base_imp por alicuota) cpb_iva = cpb_comprobante_tot_iva.objects.filter(cpb_comprobante=f) for c in cpb_iva: id = c.tasa_iva.id_afip # 21% base_imp = c.importe_base importe = c.importe_total if importe == 0: id = 3 wsfev1.AgregarIva(id, base_imp, importe) if len(cpb_iva) == 0: wsfev1.AgregarIva(3, 0, 0) #Traigo las percepciones de IVA # tributo_id: código tipo de impuesto (según tabla de parámetros AFIP) # desc: descripción del tributo (por ej. "Impuesto Municipal Matanza") # base_imp: base imponible (importe) # alic: alicuota (porcentaje) # importe: importe liquidado cpb_perc = cpb_comprobante_perc_imp.objects.filter( cpb_comprobante=f) for p in cpb_perc: if p.perc_imp: id = p.perc_imp.id if (id == 99) and (p.detalle): desc = p.detalle else: desc = p.perc_imp.nombre base_imp = p.importe_total alic = 100 importe = p.importe_total wsfev1.AgregarTributo(id, desc, base_imp, alic, importe) # Agrego los comprobantes asociados (solo para notas de crédito y débito): if (f.cpb_tipo.tipo in [2, 3, 22, 23]) and (f.id_cpb_padre): p = f.id_cpb_padre p_nafip = cpb_nro_afip.objects.get(cpb_tipo=p.cpb_tipo.tipo, letra=p.letra).numero_afip p_tipo = p_nafip p_fecha = p.fecha_cpb.strftime("%Y%m%d") p_pv = int(p.pto_vta) p_nro = int(p.numero) p_tipo_doc = p.entidad.tipo_doc if p_tipo_doc == 99: p_cuit = None elif tipo_doc == 96: p_cuit = None elif tipo_doc == 80: p_cuit = p.entidad.fact_cuit else: p_cuit = p.entidad.fact_cuit wsfev1.AgregarCmpAsoc(p_tipo, p_pv, p_nro, p_cuit) #Si es FactCredElectr debo informar tb el CBU if (f.cpb_tipo.tipo in [21, 22, 23]): wsfev1.AgregarOpcional(2101, f.empresa.cbu) # CBU # import unicodedata # import StringIO # alias = unicodedata.normalize('NFKD', (f.empresa.nombre[:20])).encode('ASCII', 'ignore') # print alias #wsfev1.AgregarOpcional(2102, f.empresa.cbu_alias) # alias if f.cpb_tipo.tipo in [22, 23]: wsfev1.AgregarOpcional(22, "S") #http://www.sistemasagiles.com.ar/trac/wiki/ManualPyAfipWs#M%C3%A9todosprincipalesdeWSFEv1 wsfev1.CAESolicitar() cae = wsfev1.CAE resultado = wsfev1.Resultado cpb_nro = wsfev1.CbteNro ult_nro = cpb_nro detalle = '' motivo = wsfev1.Motivo observaciones = wsfev1.Observaciones if cae == '': detalle = u"La página esta caida o la respuesta es inválida" elif (wsfev1.Resultado != "A"): detalle = u"No se asignó CAE (Rechazado). Motivos:%s" % motivo elif observaciones != []: detalle = u"Se asignó CAE pero con advertencias. Motivos: %s" % observaciones fecha_vencimiento = None fecha_cbte = None EmisionTipo = '' if cae != '': fecha_vencimiento = datetime.strptime(wsfev1.Vencimiento, '%Y%m%d') EmisionTipo = wsfev1.EmisionTipo fecha_cbte = datetime.strptime(wsfev1.FechaCbte, '%Y%m%d') reproceso = wsfev1.Reproceso imp_total = wsfev1.ImpTotal concepto = wsfev1.ObtenerCampoFactura('concepto') imp_tot_conc = wsfev1.ObtenerCampoFactura('imp_tot_conc') imp_neto = wsfev1.ImpNeto imp_op_ex = wsfev1.ImpOpEx imp_trib = wsfev1.ImpTrib imp_iva = wsfev1.ImpIVA moneda_id = wsfev1.ObtenerCampoFactura('moneda_id') moneda_ctz = wsfev1.ObtenerCampoFactura('moneda_ctz') errores = wsfev1.ErrMsg data = { 'token': token, 'sign': sign, 'cae': cae, 'fecha_vencimiento': fecha_vencimiento, 'cpb_nro': cpb_nro, 'resultado': resultado, 'motivo': motivo, 'reproceso': reproceso, 'observaciones': observaciones, 'concepto': concepto, 'tipo_cbte': tipo_cpb, 'punto_vta': pto_vta, 'fecha_cbte': fecha_cbte, 'imp_total': imp_total, 'imp_tot_conc': imp_tot_conc, 'imp_neto': imp_neto, 'imp_op_ex': imp_op_ex, 'imp_trib': imp_trib, 'imp_iva': imp_iva, 'moneda_id': moneda_id, 'moneda_ctz': moneda_ctz, 'detalle': detalle, 'ult_nro': ult_nro, 'excepcion': wsfev1.Excepcion, 'traceback': wsfev1.Traceback, 'XmlRequest': wsfev1.XmlRequest, 'XmlResponse': wsfev1.XmlResponse, 'appserver_status': appserver_status, 'dbserver_status': dbserver_status, 'authserver_status': authserver_status, 'errores': errores, } except Exception as e: if wsfev1: data = { 'token': token, 'sign': sign, 'cae': cae, 'fecha_vencimiento': fecha_vencimiento, 'cpb_nro': cpb_nro, 'resultado': resultado, 'motivo': motivo, 'reproceso': reproceso, 'observaciones': observaciones, 'concepto': concepto, 'tipo_cbte': tipo_cpb, 'punto_vta': pto_vta, 'fecha_cbte': fecha_cbte, 'imp_total': imp_total, 'imp_tot_conc': imp_tot_conc, 'imp_neto': imp_neto, 'imp_op_ex': imp_op_ex, 'imp_trib': imp_trib, 'imp_iva': imp_iva, 'moneda_id': moneda_id, 'moneda_ctz': moneda_ctz, 'detalle': detalle, 'ult_nro': ult_nro, 'excepcion': wsfev1.Excepcion, 'traceback': wsfev1.Traceback, 'XmlRequest': wsfev1.XmlRequest, 'XmlResponse': wsfev1.XmlResponse, 'appserver_status': appserver_status, 'dbserver_status': dbserver_status, 'authserver_status': authserver_status, 'errores': wsfev1.ErrMsg + '' + str(e), } else: data = dict(errores=errores + '' + str(e)) return data
def consultar_cae(request, idcpb): empresa = empresa_actual(request) H**O = empresa.homologacion if H**O: WSDL = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaahomo.afip.gov.ar/ws/services/LoginCms" else: WSDL = "https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaa.afip.gov.ar/ws/services/LoginCms" #Traigo el comprobante token = '' sign = '' cae = '' fecha_vencimiento = '' cpb_nro = '' resultado = '' motivo = '' reproceso = '' observaciones = '' concepto = '' tipo_cpb = '' pto_vta = '' fecha_cbte = '' imp_total = '' imp_tot_conc = '' imp_neto = '' imp_op_ex = '' imp_trib = '' imp_iva = '' moneda_id = '' moneda_ctz = '' detalle = '' ult_nro = '' errores = '' data = { 'token': token, 'sign': sign, 'cae': cae, 'fecha_vencimiento': fecha_vencimiento, 'cpb_nro': cpb_nro, 'resultado': resultado, 'motivo': motivo, 'reproceso': reproceso, 'observaciones': observaciones, 'concepto': concepto, 'tipo_cbte': tipo_cpb, 'punto_vta': pto_vta, 'fecha_cbte': fecha_cbte, 'imp_total': imp_total, 'imp_tot_conc': imp_tot_conc, 'imp_neto': imp_neto, 'imp_op_ex': imp_op_ex, 'imp_trib': imp_trib, 'imp_iva': imp_iva, 'moneda_id': moneda_id, 'moneda_ctz': moneda_ctz, 'detalle': detalle, 'ult_nro': ult_nro, 'excepcion': '', 'traceback': '', 'XmlRequest': '', 'XmlResponse': '', 'appserver_status': '', 'dbserver_status': '', 'authserver_status': '', 'errores': errores, } try: cpb = cpb_comprobante.objects.get(id=idcpb) except: cpb = None if not cpb: data['errores'] = u'¡El comprobante no es válido!' return data try: cpb_nafip = cpb.get_nro_afip() tipo_cpb = cpb_nafip pto_vta = int(cpb.pto_vta) nro_cpb = int(cpb.numero) except: data['errores'] = u'¡El comprobante no es válido!' return data #Si el pto_vta no admite factura electrónica if not cpb.get_pto_vta().fe_electronica: data['errores'] = u'¡El comprobante no es válido!' return data appserver_status = '' dbserver_status = '' authserver_status = '' #try: fecha = datetime.now().strftime("%Y%m%d") wsfev1 = WSFEv1() wsfev1.Conectar(wsdl=WSDL) cuit = cpb.get_pto_vta().cuit # cuit = 30714843571 wsfev1.Cuit = cuit if H**O: crt = empresa.fe_crt key = empresa.fe_key else: try: #crt = "COPYFAST_PRUEBA.crt" crt = cpb.get_pto_vta().fe_crt except: data['errores'] = u'¡fe_crt no es válido!' return data try: key = cpb.get_pto_vta().fe_key #key= "COPYFAST_PRUEBA.key" except: data['errores'] = u'¡fe_key no es válido!' return data wsfev1.Token, wsfev1.Sign = _autenticar(request, crt=crt, key=key, cuit=cuit) wsfev1.Dummy() appserver_status = wsfev1.AppServerStatus dbserver_status = wsfev1.DbServerStatus authserver_status = wsfev1.AuthServerStatus # except: # data['excepcion']=wsfev1.Excepcion # data['traceback']=wsfev1.Traceback # data['XmlRequest']=wsfev1.XmlRequest # data['XmlResponse']=wsfev1.XmlResponse # data['appserver_status']=appserver_status # data['dbserver_status']=dbserver_status # data['authserver_status']=authserver_status # data['errores']=u'¡Falló la comunicación con los servidores de AFIP!' # return data data = recuperar_cpb_afip(request, wsfev1, tipo_cpb, pto_vta, nro_cpb) return data
def recuperar_cpb_afip(request, tipo_cpb, pto_vta, nro_cpb): empresa = empresa_actual(request) H**O = empresa.homologacion if H**O: WSDL = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaahomo.afip.gov.ar/ws/services/LoginCms" else: WSDL = "https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL" WSAA_URL = "https://wsaa.afip.gov.ar/ws/services/LoginCms" #Traigo el comprobante token = '' sign = '' cae = '' fecha_vencimiento = '' resultado = '' motivo = '' reproceso = '' observaciones = '' concepto = '' fecha_cbte = '' imp_total = '' imp_tot_conc = '' imp_neto = '' imp_op_ex = '' imp_trib = '' imp_iva = '' moneda_id = '' moneda_ctz = '' detalle = '' ult_nro = '' errores = '' data = { 'cae': cae, 'fecha_vencimiento': fecha_vencimiento, 'cpb_nro': nro_cpb, 'resultado': resultado, 'motivo': motivo, 'reproceso': reproceso, 'observaciones': observaciones, 'concepto': concepto, 'tipo_cbte': tipo_cpb, 'punto_vta': pto_vta, 'fecha_cbte': fecha_cbte, 'imp_total': imp_total, 'imp_tot_conc': imp_tot_conc, 'imp_neto': imp_neto, 'imp_op_ex': imp_op_ex, 'imp_trib': imp_trib, 'imp_iva': imp_iva, 'moneda_id': moneda_id, 'moneda_ctz': moneda_ctz, 'detalle': detalle, 'ult_nro': ult_nro, 'errores': errores, 'factura': '', } appserver_status = '' dbserver_status = '' authserver_status = '' #try: fecha = datetime.now().strftime("%Y%m%d") wsfev1 = WSFEv1() wsfev1.Conectar(wsdl=WSDL) cuit = empresa.cuit # cuit = 30714843571 wsfev1.Cuit = cuit crt = empresa.fe_crt key = empresa.fe_key wsfev1.Token, wsfev1.Sign = _autenticar(request, crt=crt, key=key, cuit=cuit) wsfev1.Dummy() appserver_status = wsfev1.AppServerStatus dbserver_status = wsfev1.DbServerStatus authserver_status = wsfev1.AuthServerStatus wsfev1.CompConsultar(tipo_cpb, pto_vta, nro_cpb) cpb_nro = wsfev1.CbteNro fecha_vencimiento = wsfev1.Vencimiento resultado = wsfev1.Resultado motivo = wsfev1.Motivo reproceso = wsfev1.Reproceso imp_total = wsfev1.ImpTotal cae = wsfev1.CAE observaciones = wsfev1.Observaciones fecha_cbte = wsfev1.FechaCbte concepto = wsfev1.ObtenerCampoFactura('concepto') imp_tot_conc = wsfev1.ObtenerCampoFactura('imp_tot_conc') imp_neto = wsfev1.ImpNeto imp_op_ex = wsfev1.ImpOpEx imp_trib = wsfev1.ImpTrib imp_iva = wsfev1.ImpIVA moneda_id = wsfev1.ObtenerCampoFactura('moneda_id') moneda_ctz = wsfev1.ObtenerCampoFactura('moneda_ctz') factura = wsfev1.factura errores = wsfev1.ErrMsg detalle = '' if cae == '': detalle = u"La página esta caida o la respuesta es inválida" elif (wsfev1.Resultado != "A"): detalle = u"No se asignó CAE (Rechazado). Motivos:%s" % wsfev1.Motivo elif wsfev1.Observaciones != "": detalle = u"Se asignó CAE pero con advertencias. Motivos: %s" % wsfev1.Observaciones fecha_vencimiento = None fecha_cbte = None EmisionTipo = '' if cae: fecha_vencimiento = datetime.strptime(wsfev1.Vencimiento, '%Y%m%d') EmisionTipo = wsfev1.EmisionTipo fecha_cbte = datetime.strptime(wsfev1.FechaCbte, '%Y%m%d') ult_nro = long(wsfev1.CompUltimoAutorizado(tipo_cpb, pto_vta) or 0) data = { 'cae': cae, 'fecha_vencimiento': fecha_vencimiento, 'cpb_nro': cpb_nro, 'resultado': resultado, 'motivo': motivo, 'reproceso': reproceso, 'observaciones': observaciones, 'concepto': concepto, 'tipo_cbte': tipo_cpb, 'punto_vta': pto_vta, 'fecha_cbte': fecha_cbte, 'imp_total': imp_total, 'imp_tot_conc': imp_tot_conc, 'imp_neto': imp_neto, 'imp_op_ex': imp_op_ex, 'imp_trib': imp_trib, 'imp_iva': imp_iva, 'moneda_id': moneda_id, 'moneda_ctz': moneda_ctz, 'detalle': detalle, 'ult_nro': ult_nro, 'errores': errores, 'factura': factura, } return data
def obtener_cae(): # web service de factura electronica: wsfev1 = WSFEv1() wsfev1.LanzarExcepciones = True # obteniendo el TA para pruebas ta = WSAA().Autenticar("wsfe", "/home/rodrigo/pyafipws/staff.crt", "/home/rodrigo/pyafipws/staff.key", debug=True) wsfev1.SetTicketAcceso(ta) wsfev1.Cuit = "20267565393" ok = wsfev1.Conectar() tipo_cbte = 6 punto_vta = 4001 cbte_nro = long(wsfev1.CompUltimoAutorizado(tipo_cbte, punto_vta) or 0) fecha = datetime.datetime.now().strftime("%Y%m%d") concepto = 1 tipo_doc = 80 # 80: CUIT, 96: DNI nro_doc = "30500010912" # del cliente cbt_desde = cbte_nro + 1; cbt_hasta = cbte_nro + 1 imp_total = "222.00" imp_tot_conc = "0.00" imp_neto = "200.00" imp_iva = "21.00" imp_trib = "1.00" imp_op_ex = "0.00" fecha_cbte = fecha # Fechas del per�odo del servicio facturado y vencimiento de pago: if concepto > 1: fecha_venc_pago = fecha fecha_serv_desde = fecha fecha_serv_hasta = fecha else: fecha_venc_pago = fecha_serv_desde = fecha_serv_hasta = None moneda_id = 'PES' moneda_ctz = '1.000' wsfev1.CrearFactura(concepto, tipo_doc, nro_doc, tipo_cbte, punto_vta, cbt_desde, cbt_hasta , imp_total, imp_tot_conc, imp_neto, imp_iva, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, fecha_serv_desde, fecha_serv_hasta, #-- moneda_id, moneda_ctz) # otros tributos: tributo_id = 99 desc = 'Impuesto Municipal Matanza' base_imp = None alic = None importe = 1 wsfev1.AgregarTributo(tributo_id, desc, base_imp, alic, importe) # subtotales por alicuota de IVA: iva_id = 3 # 0% base_imp = 100 # neto al 0% importe = 0 wsfev1.AgregarIva(iva_id, base_imp, importe) # subtotales por alicuota de IVA: iva_id = 5 # 21% base_imp = 100 # neto al 21% importe = 21 # iva liquidado al 21% wsfev1.AgregarIva(iva_id, base_imp, importe) wsfev1.CAESolicitar() print "Nro. Cbte. desde-hasta", wsfev1.CbtDesde, wsfev1.CbtHasta print "Resultado", wsfev1.Resultado print "Reproceso", wsfev1.Reproceso print "CAE", wsfev1.CAE print "Vencimiento", wsfev1.Vencimiento print "Observaciones", wsfev1.Obs session.cae = wsfev1.CAE response.view = "generic.html" return {"Nro. Cbte. desde-hasta": wsfev1.CbtDesde, "Resultado": wsfev1.Resultado, "Reproceso": wsfev1.Reproceso, "CAE": wsfev1.CAE, "Vencimiento": wsfev1.Vencimiento, "Observaciones": wsfev1.Obs, }
def obtener_cae(): from pyafipws.wsaa import WSAA from pyafipws.wsfev1 import WSFEv1 # web service de factura electronica: wsfev1 = WSFEv1() wsfev1.LanzarExcepciones = True # obteniendo el TA para pruebas ta = WSAA().Autenticar("wsfe", "/home/web2py/pyafipws/reingart.crt", "/home/web2py/pyafipws/reingart.key", debug=True) wsfev1.SetTicketAcceso(ta) wsfev1.Cuit = "20267565393" ok = wsfev1.Conectar() # obtengo el id de comprobante pasado por la URL desde la funcion facturar factura_id = int(request.args[0]) # obtengo el registro general del comprobante (encabezado y totales) reg = db(db.comprobante_afip.id==factura_id).select().first() tipo_cbte = reg.tipo_cbte punto_vta = reg.punto_vta cbte_nro = long(wsfev1.CompUltimoAutorizado(tipo_cbte, punto_vta) or 0) + 1 #fecha = reg.fecha_cbte.strftime("%Y%m%d") # formato AAAAMMDD fecha = datetime.datetime.now().strftime("%Y%m%d") concepto = reg.concepto tipo_doc = reg.tipo_doc # 80: CUIT, 96: DNI nro_doc = reg.nro_doc.replace("-", "") # del cliente, sin rayita cbt_desde = cbte_nro; cbt_hasta = cbte_nro imp_total = reg.imp_total imp_tot_conc = reg.imp_tot_conc imp_neto = reg.imp_neto imp_iva = reg.impto_liq imp_trib = "0.00" imp_op_ex = reg.imp_op_ex fecha_cbte = fecha # Fechas del per�odo del servicio facturado y vencimiento de pago: if concepto > 1: fecha_venc_pago = reg.fecha_venc_pago fecha_serv_desde = reg.fecha_serv_desde fecha_serv_hasta = reg.fecha_serv_desde else: fecha_venc_pago = fecha_serv_desde = fecha_serv_hasta = None moneda_id = "PES" moneda_ctz = "1.000" wsfev1.CrearFactura(concepto, tipo_doc, nro_doc, tipo_cbte, punto_vta, cbt_desde, cbt_hasta , imp_total, imp_tot_conc, imp_neto, imp_iva, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, fecha_serv_desde, fecha_serv_hasta, #-- moneda_id, moneda_ctz) # subtotales por alicuota de IVA: iva_id = 5 # 21% base_imp = reg.imp_neto # neto al 21% importe = reg.impto_liq # iva liquidado al 21% wsfev1.AgregarIva(iva_id, base_imp, importe) try: wsfev1.CAESolicitar() except: print "uy le mandamos fruta!" #print "Nro. Cbte. desde-hasta", wsfev1.CbtDesde, wsfev1.CbtHasta #print "Resultado", wsfev1.Resultado #print "Reproceso", wsfev1.Reproceso #print "CAE", wsfev1.CAE #print "Vencimiento", wsfev1.Vencimiento #print "Observaciones", wsfev1.Obs # actualizamos la factura con la respuesta de AFIP db(db.comprobante_afip.id == factura_id).update( cae=wsfev1.CAE, fecha_cbte=fecha, cbte_nro=cbte_nro, fecha_vto=wsfev1.Vencimiento, ) if wsfev1.CAE: redirect(URL(f="generar_pdf", args=[factura_id])) response.view = "generic.html" return {"Nro. Cbte. desde-hasta": wsfev1.CbtDesde, "Resultado": wsfev1.Resultado, "Reproceso": wsfev1.Reproceso, "CAE": wsfev1.CAE, "Vencimiento": wsfev1.Vencimiento, "Observaciones": wsfev1.Obs, "XmlRequest": wsfev1.XmlRequest, "XmlResponse": wsfev1.XmlResponse, "ErrMsg": wsfev1.ErrMsg, }
def do_pyafipws_request_cae(self, cr, uid, ids, context=None, *args): "Request to AFIP the invoices' Authorization Electronic Code (CAE)" for invoice in self.browse(cr, uid, ids): # if already authorized (electronic invoice with CAE), ignore if invoice.pyafipws_cae: continue # get the electronic invoice type, point of sale and service: journal = invoice.journal_id company = journal.company_id tipo_cbte = journal.pyafipws_invoice_type punto_vta = journal.pyafipws_point_of_sale service = journal.pyafipws_electronic_invoice_service # check if it is an electronic invoice sale point: if not tipo_cbte or not punto_vta or not service: continue # authenticate against AFIP: auth_data = company.pyafipws_authenticate(service=service) # create the proxy and get the configuration system parameters: cfg = self.pool.get('ir.config_parameter') cache = cfg.get_param(cr, uid, 'pyafipws.cache', context=context) proxy = cfg.get_param(cr, uid, 'pyafipws.proxy', context=context) wsdl = cfg.get_param(cr, uid, 'pyafipws.%s.url' % service, context=context) # import the AFIP webservice helper for electronic invoice if service == 'wsfe': from pyafipws.wsfev1 import WSFEv1 # local market ws = WSFEv1() elif service == 'wsmtxca': from pyafipws.wsmtx import WSMTXCA # local + detail wsdl = cfg.get_param(cr, uid, 'pyafipws.wsmtxca.url', context=context) ws = WSMTXCA() elif service == 'wsfex': from pyafipws.wsfexv1 import WSFEXv1 wsdl = cfg.get_param(cr, uid, 'pyafipws.wsfex.url', context=context) ws = WSFEXv1() else: raise osv.except_osv('Error !', "%s no soportado" % service) from pyafipws.utils import SoapFault # connect to the webservice and call to the test method ws.Conectar(cache or "", wsdl or "", proxy or "") # set AFIP webservice credentials: ws.Cuit = company.pyafipws_cuit ws.Token = auth_data['token'] ws.Sign = auth_data['sign'] # get the last 8 digit of the invoice number cbte_nro = int(invoice.number[-8:]) # get the last invoice number registered in AFIP if service == "wsfe" or service == "wsmtxca": cbte_nro_afip = ws.CompUltimoAutorizado(tipo_cbte, punto_vta) elif service == 'wsfex': cbte_nro_afip = ws.GetLastCMP(tipo_cbte, punto_vta) cbte_nro_next = int(cbte_nro_afip or 0) + 1 # verify that the invoice is the next one to be registered in AFIP if cbte_nro != cbte_nro_next: raise osv.except_osv( u'Error !', u'Referencia: %s \n' u'El número del comprobante debería ser %s y no %s' % (str(invoice.number), str(cbte_nro_next), str(cbte_nro))) # invoice number range (from - to) and date: cbte_nro = cbt_desde = cbt_hasta = cbte_nro_next fecha_cbte = invoice.date_invoice if service != 'wsmtxca': fecha_cbte = fecha_cbte.replace("-", "") # due and billing dates only for concept "services" concepto = tipo_expo = int(invoice.pyafipws_concept or 0) if int(concepto) != 1: fecha_venc_pago = invoice.date_invoice if service != 'wsmtxca': fecha_venc_pago = fecha_venc_pago.replace("-", "") if invoice.pyafipws_billing_start_date: fecha_serv_desde = invoice.pyafipws_billing_start_date if service != 'wsmtxca': fecha_serv_desde = fecha_serv_desde.replace("-", "") else: fecha_serv_desde = None if invoice.pyafipws_billing_end_date: fecha_serv_hasta = invoice.pyafipws_billing_end_date if service != 'wsmtxca': fecha_serv_desde = fecha_serv_desde.replace("-", "") else: fecha_serv_hasta = None else: fecha_venc_pago = fecha_serv_desde = fecha_serv_hasta = None # customer tax number: if invoice.partner_id.vat: nro_doc = invoice.partner_id.vat.replace("-", "") else: nro_doc = "0" # only "consumidor final" tipo_doc = None if nro_doc.startswith("AR"): nro_doc = nro_doc[2:] if int(nro_doc) == 0: tipo_doc = 99 # consumidor final elif len(nro_doc) < 11: tipo_doc = 96 # DNI else: tipo_doc = 80 # CUIT # invoice amount totals: imp_total = str("%.2f" % abs(invoice.amount_total)) imp_tot_conc = "0.00" imp_neto = str("%.2f" % abs(invoice.amount_untaxed)) imp_iva = str("%.2f" % abs(invoice.amount_tax)) imp_subtotal = imp_neto # TODO: not allways the case! imp_trib = "0.00" imp_op_ex = "0.00" if invoice.currency_id.name == 'ARS': moneda_id = "PES" moneda_ctz = 1 else: moneda_id = {'USD': 'DOL'}[invoice.currency_id.name] moneda_ctz = str(invoice.currency_id.rate) # foreign trade data: export permit, country code, etc.: if False: ##invoice.pyafipws_incoterms: incoterms = invoice.pyafipws_incoterms.code incoterms_ds = invoice.pyafipws_incoterms.name else: incoterms = incoterms_ds = None if int(tipo_cbte) == 19 and tipo_expo == 1: permiso_existente = "N" or "S" # not used now else: permiso_existente = "" obs_generales = invoice.comment if invoice.payment_term: forma_pago = invoice.payment_term.name obs_comerciales = invoice.payment_term.name else: forma_pago = obs_comerciales = None idioma_cbte = 1 # invoice language: spanish / español # customer data (foreign trade): nombre_cliente = invoice.partner_id.name if invoice.partner_id.vat: if invoice.partner_id.vat.startswith("AR"): # use the Argentina AFIP's global CUIT for the country: cuit_pais_cliente = invoice.partner_id.vat[2:] id_impositivo = None else: # use the VAT number directly id_impositivo = invoice.partner_id.vat[2:] # TODO: the prefix could be used to map the customer country cuit_pais_cliente = None else: cuit_pais_cliente = id_impositivo = None # OpenERP 7 no tiene address_invoice_id if invoice.partner_id: domicilio_cliente = " - ".join([ invoice.partner_id.name or '', invoice.partner_id.street or '', invoice.partner_id.street2 or '', invoice.partner_id.zip or '', invoice.partner_id.city or '', ]) else: domicilio_cliente = "" if invoice.partner_id.country_id: # map ISO country code to AFIP destination country code: iso_code = invoice.partner_id.country_id.code.lower() pais_dst_cmp = AFIP_COUNTRY_CODE_MAP[iso_code] # create the invoice internally in the helper if service == 'wsfe': ws.CrearFactura(concepto, tipo_doc, nro_doc, tipo_cbte, punto_vta, cbt_desde, cbt_hasta, imp_total, imp_tot_conc, imp_neto, imp_iva, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, fecha_serv_desde, fecha_serv_hasta, moneda_id, moneda_ctz) elif service == 'wsmtxca': ws.CrearFactura(concepto, tipo_doc, nro_doc, tipo_cbte, punto_vta, cbt_desde, cbt_hasta, imp_total, imp_tot_conc, imp_neto, imp_subtotal, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, fecha_serv_desde, fecha_serv_hasta, moneda_id, moneda_ctz, obs_generales) elif service == 'wsfex': ws.CrearFactura(tipo_cbte, punto_vta, cbte_nro, fecha_cbte, imp_total, tipo_expo, permiso_existente, pais_dst_cmp, nombre_cliente, cuit_pais_cliente, domicilio_cliente, id_impositivo, moneda_id, moneda_ctz, obs_comerciales, obs_generales, forma_pago, incoterms, idioma_cbte, incoterms_ds) # analyze VAT (IVA) and other taxes (tributo): if service in ('wsfe', 'wsmtxca'): for tax_line in invoice.tax_line: if "IVA" in tax_line.name: if '0%' in tax_line.name: iva_id = 3 elif '10,5%' in tax_line.name: iva_id = 4 elif '21%' in tax_line.name: iva_id = 5 elif '27%' in tax_line.name: iva_id = 6 else: iva_id = 0 base_imp = ("%.2f" % abs(tax_line.base)) importe = ("%.2f" % abs(tax_line.amount)) # add the vat detail in the helper ws.AgregarIva(iva_id, base_imp, importe) else: if 'impuesto' in tax_line.name.lower(): tributo_id = 1 # nacional elif 'iibbb' in tax_line.name.lower(): tributo_id = 3 # provincial elif 'tasa' in tax_line.name.lower(): tributo_id = 4 # municipal else: tributo_id = 99 desc = tax_line.name base_imp = ("%.2f" % abs(tax_line.base)) importe = ("%.2f" % abs(tax_line.amount)) alic = "%.2f" % tax_line.base # add the other tax detail in the helper ws.AgregarTributo(id, desc, base_imp, alic, importe) # analize line items - invoice detail if service in ('wsfex', 'wsmtxca'): for line in invoice.invoice_line: codigo = line.product_id.code u_mtx = 1 # TODO: get it from uom? cod_mtx = line.product_id.ean13 ds = line.name qty = line.quantity umed = 7 # TODO: line.uos_id...? precio = line.price_unit importe = line.price_subtotal bonif = line.discount or None if line.invoice_line_tax_id: iva_id = 5 # TODO: line.tax_code_id? imp_iva = importe * line.invoice_line_tax_id[0].amount else: iva_id = 1 imp_iva = 0 if service == 'wsmtxca': ws.AgregarItem(u_mtx, cod_mtx, codigo, ds, qty, umed, precio, bonif, iva_id, imp_iva, importe + imp_iva) elif service == 'wsfex': ws.AgregarItem(codigo, ds, qty, umed, precio, importe, bonif) # Request the authorization! (call the AFIP webservice method) vto = None try: if service == 'wsfe': ws.CAESolicitar() vto = ws.Vencimiento elif service == 'wsmtxca': ws.AutorizarComprobante() vto = ws.Vencimiento elif service == 'wsfex': ws.Authorize(invoice.id) vto = ws.FchVencCAE except SoapFault as fault: msg = 'Falla SOAP %s: %s' % (fault.faultcode, fault.faultstring) except Exception, e: if ws.Excepcion: # get the exception already parsed by the helper msg = ws.Excepcion else: # avoid encoding problem when reporting exceptions to the user: msg = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0] else: msg = u"\n".join([ws.Obs or "", ws.ErrMsg or ""]) # calculate the barcode: if ws.CAE: cae_due = ''.join([c for c in str(vto or '') if c.isdigit()]) bars = ''.join([ str(ws.Cuit), "%02d" % int(tipo_cbte), "%04d" % int(punto_vta), str(ws.CAE), cae_due ]) bars = bars + self.pyafipws_verification_digit_modulo10(bars) else: bars = "" # store the results self.write( cr, uid, invoice.id, { 'pyafipws_cae': ws.CAE, 'pyafipws_cae_due_date': vto or None, 'pyafipws_result': ws.Resultado, 'pyafipws_message': msg, 'pyafipws_xml_request': ws.XmlRequest, 'pyafipws_xml_response': ws.XmlResponse, 'pyafipws_barcode': bars, })
def facturar(registros): """Rutina para emitir facturas electrónicas en PDF c/CAE AFIP Argentina""" # inicialización AFIP: wsaa = WSAA() wsfev1 = WSFEv1() # obtener ticket de acceso (token y sign): ta = wsaa.Autenticar( "wsfe", CERT, PRIVATEKEY, wsdl=URL_WSAA, cache=CACHE, debug=True ) wsfev1.Cuit = CUIT wsfev1.SetTicketAcceso(ta) wsfev1.Conectar(CACHE, URL_WSFEv1) # inicialización PDF fepdf = FEPDF() fepdf.CargarFormato("factura.csv") fepdf.FmtCantidad = "0.2" fepdf.FmtPrecio = "0.2" fepdf.CUIT = CUIT for k, v in CONF_PDF.items(): fepdf.AgregarDato(k, v) if "h**o" in URL_WSAA: fepdf.AgregarCampo( "DEMO", "T", 120, 260, 0, 0, text="DEMOSTRACION", size=70, rotate=45, foreground=0x808080, priority=-1, ) fepdf.AgregarDato("motivos_obs", "Ejemplo Sin validez fiscal") # recorrer los registros a facturar, solicitar CAE y generar el PDF: for reg in registros: hoy = datetime.date.today().strftime("%Y%m%d") cbte = Comprobante( tipo_cbte=6, punto_vta=4000, fecha_cbte=hoy, cbte_nro=reg.get("nro"), tipo_doc=96, nro_doc=reg["dni"], nombre_cliente=reg["nombre"], # "Juan Perez" domicilio_cliente=reg["domicilio"], # "Balcarce 50" fecha_serv_desde=reg.get("periodo_desde"), fecha_serv_hasta=reg.get("periodo_hasta"), fecha_venc_pago=reg.get("venc_pago", hoy), ) cbte.agregar_item( ds=reg["descripcion"], qty=reg.get("cantidad", 1), precio=reg.get("precio", 0), tasa_iva=reg.get("tasa_iva", 21.0), ) ok = cbte.autorizar(wsfev1) nro = cbte.encabezado["cbte_nro"] print("Factura autorizada", nro, cbte.encabezado["cae"]) if "h**o" in URL_WSFEv1: cbte.encabezado["motivos_obs"] = "Ejemplo Sin validez fiscal" ok = cbte.generar_pdf(fepdf, "/tmp/factura_{}.pdf".format(nro)) print("PDF generado", ok)
def cae(): from pyafipws.wsfev1 import WSFEv1 wsfev1 = WSFEv1() wsfev1.Conectar() wsfev1.Cuit = 20267565393 wsfev1.Token, wsfev1.Sign = _autenticar() id = request.args[0] f = db(db.pagos.id == id).select().first() if f.resultado == "A": raise HTTP(500, "La factura ya tiene CAE: %s" % f.cae) tipo_cbte = f.tipo_cbte punto_vta = f.pto_vta cbte_nro = long(wsfev1.CompUltimoAutorizado(tipo_cbte, punto_vta) or 0) fecha = datetime.datetime.now().strftime("%Y%m%d") concepto = 2 tipo_doc = f.tipo_doc nro_doc = f.nro_doc cbt_desde = cbte_nro + 1 cbt_hasta = cbte_nro + 1 imp_total = f.imp_total imp_tot_conc = "0.00" imp_neto = "0.00" imp_iva = "0.00" imp_trib = "0.00" imp_op_ex = f.imp_total fecha_cbte = fecha fecha_venc_pago = fecha # Fechas del período del servicio facturado (solo si concepto = 1?) fecha_serv_desde = fecha fecha_serv_hasta = fecha moneda_id = 'PES' moneda_ctz = '1.000' wsfev1.CrearFactura( concepto, tipo_doc, nro_doc, tipo_cbte, punto_vta, cbt_desde, cbt_hasta, imp_total, imp_tot_conc, imp_neto, imp_iva, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, fecha_serv_desde, fecha_serv_hasta, #-- moneda_id, moneda_ctz) if False: tipo = 19 pto_vta = 2 nro = 1234 wsfev1.AgregarCmpAsoc(tipo, pto_vta, nro) #id = 99 #desc = 'Impuesto Municipal Matanza' #base_imp = 100 #alic = 1 #importe = 1 #wsfev1.AgregarTributo(id, desc, base_imp, alic, importe) #id = 5 # 21% #base_imp = 100 #importe = 21 #wsfev1.AgregarIva(id, base_imp, importe) wsfev1.CAESolicitar() db(db.pagos.id == int(request.args[0])).update( cae=wsfev1.CAE, cbte_nro=cbt_desde, fecha_vto=wsfev1.Vencimiento, fecha=request.now.date(), motivo=wsfev1.Obs, resultado=wsfev1.Resultado) response.view = "generic.html" return { 'CAE': wsfev1.CAE, "Resultado": wsfev1.Resultado, "Reproceso": wsfev1.Reproceso, "Vencimiento": wsfev1.Vencimiento, "ErrMsg": wsfev1.ErrMsg, "Obs": wsfev1.Obs, "Token": wsfev1.Token, "Sign": wsfev1.Sign, }
def __init__(self): WSFEv1.__init__(self) if LeerIni( clave='h**o' ) != 'S': #si no es homologacion traigo la url de produccion self.WSDL = LeerIni(clave='url_prod', key='WSFEv1')
def generate_invoices(records): """Generate the invoices in PDF using AFIP API resources.""" # AFIP init wsaa = WSAA() wsfev1 = WSFEv1() # get access ticket (token y sign) certificate = settings.AFIP['auth_cert_path'] private_key = settings.AFIP['auth_key_path'] if not os.path.exists(certificate): raise ValueError( "Auth certificate can not be found (got {!r})".format(certificate)) if not os.path.exists(private_key): raise ValueError( "Auth key can not be found (got {!r})".format(private_key)) ta = wsaa.Autenticar("wsfe", certificate, private_key, wsdl=settings.AFIP['url_wsaa'], cache=CACHE, debug=True) wsfev1.Cuit = settings.AFIP['cuit'] wsfev1.SetTicketAcceso(ta) wsfev1.Conectar(CACHE, settings.AFIP['url_wsfev1']) # init PDF builder fepdf = FEPDF() fepdf.CargarFormato("factura.csv") fepdf.FmtCantidad = "0.2" fepdf.FmtPrecio = "0.2" fepdf.CUIT = settings.AFIP['cuit'] for k, v in CONFIG_PDF.items(): fepdf.AgregarDato(k, v) # safeguard when using test webservice endpoints if "h**o" in settings.AFIP['url_wsaa']: fepdf.AgregarCampo("DEMO", 'T', 120, 260, 0, 0, text="DEMOSTRACION", size=70, rotate=45, foreground=0x808080, priority=-1) fepdf.AgregarDato("motivos_obs", "Ejemplo Sin Validez Fiscal") # get CAE for each record and generate corresponding PDF results = {} for record in records: invoice = MemberInvoice(document_number=record['dni'], fullname=record['fullname'], address=record['address'], city=record['city'], zip_code=record['zip_code'], province=record['province'], invoice_date=record['invoice_date'], invoice_number=record['invoice'], service_date_from=record['service_date_from'], service_date_to=record['service_date_to']) invoice.add_item(description=record['description'], quantity=record['quantity'], amount=record['amount'], comment=record['payment_comment']) authorized_ok = invoice.autorizar(wsfev1) invoice_number = invoice.header["cbte_nro"] print(" invoice generated: number={} CAE={} authorized={}".format( invoice_number, invoice.header["cae"], authorized_ok)) results[invoice_number] = {'invoice_ok': authorized_ok} if not authorized_ok: print("WARNING not auth") return # another safeguard if "h**o" in settings.AFIP['url_wsfev1']: invoice.header["motivos_obs"] = "Ejemplo Sin validez fiscal" # generate the PDF pdf_name = "FacturaPyArAC-{:04d}-{:08d}.pdf".format( settings.AFIP['selling_point'], invoice_number) pdf_path = os.path.join(PDF_PATH, pdf_name) invoice.generate_pdf(fepdf, pdf_path) print(" PDF generated {!r}".format(pdf_path)) results[invoice_number]['pdf_path'] = pdf_path return results
def do_pyafipws_request_cae(self): logger = logging.getLogger('pyafipws') "Request to AFIP the invoices' Authorization Electronic Code (CAE)" # if already authorized (electronic invoice with CAE), ignore if self.pyafipws_cae: logger.info(u'Se trata de obtener CAE de la factura que ya tiene. '\ u'Factura: %s, CAE: %s', self.number, self.pyafipws_cae) return # get the electronic invoice type, point of sale and service: pool = Pool() Company = pool.get('company.company') company_id = Transaction().context.get('company') if not company_id: logger.info(u'No hay companía') return company = Company(company_id) tipo_cbte = self.invoice_type.invoice_type punto_vta = self.pos.number service = self.pos.pyafipws_electronic_invoice_service # check if it is an electronic invoice sale point: ##TODO #if not tipo_cbte: # self.raise_user_error('invalid_sequence', pos.invoice_type.invoice_type) # authenticate against AFIP: auth_data = company.pyafipws_authenticate(service=service) # import the AFIP webservice helper for electronic invoice if service == 'wsfe': from pyafipws.wsfev1 import WSFEv1 # local market ws = WSFEv1() if company.pyafipws_mode_cert == 'homologacion': WSDL = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL" elif company.pyafipws_mode_cert == 'produccion': WSDL = "https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL" #elif service == 'wsmtxca': # from pyafipws.wsmtx import WSMTXCA, SoapFault # local + detail # ws = WSMTXCA() elif service == 'wsfex': from pyafipws.wsfexv1 import WSFEXv1 # foreign trade ws = WSFEXv1() if company.pyafipws_mode_cert == 'homologacion': WSDL = "https://wswhomo.afip.gov.ar/wsfexv1/service.asmx?WSDL" elif company.pyafipws_mode_cert == 'produccion': WSDL = "https://servicios1.afip.gov.ar/wsfexv1/service.asmx?WSDL" else: logger.critical(u'WS no soportado: %s', service) return # connect to the webservice and call to the test method ws.LanzarExcepciones = True ws.Conectar(wsdl=WSDL) # set AFIP webservice credentials: ws.Cuit = company.party.vat_number ws.Token = auth_data['token'] ws.Sign = auth_data['sign'] # get the last 8 digit of the invoice number if self.move: cbte_nro = int(self.move.number[-8:]) else: Sequence = pool.get('ir.sequence') cbte_nro = int( Sequence( self.invoice_type.invoice_sequence.id).get_number_next('')) # get the last invoice number registered in AFIP if service == "wsfe" or service == "wsmtxca": cbte_nro_afip = ws.CompUltimoAutorizado(tipo_cbte, punto_vta) elif service == 'wsfex': cbte_nro_afip = ws.GetLastCMP(tipo_cbte, punto_vta) cbte_nro_next = int(cbte_nro_afip or 0) + 1 # verify that the invoice is the next one to be registered in AFIP if cbte_nro != cbte_nro_next: self.raise_user_error('invalid_invoice_number', (cbte_nro, cbte_nro_next)) # invoice number range (from - to) and date: cbte_nro = cbt_desde = cbt_hasta = cbte_nro_next if self.invoice_date: fecha_cbte = self.invoice_date.strftime("%Y-%m-%d") else: Date = pool.get('ir.date') fecha_cbte = Date.today().strftime("%Y-%m-%d") if service != 'wsmtxca': fecha_cbte = fecha_cbte.replace("-", "") # due and billing dates only for concept "services" concepto = tipo_expo = int(self.pyafipws_concept or 0) if int(concepto) != 1: payments = self.payment_term.compute(self.total_amount, self.currency) last_payment = max(payments, key=lambda x: x[0])[0] fecha_venc_pago = last_payment.strftime("%Y-%m-%d") if service != 'wsmtxca': fecha_venc_pago = fecha_venc_pago.replace("-", "") if self.pyafipws_billing_start_date: fecha_serv_desde = self.pyafipws_billing_start_date.strftime( "%Y-%m-%d") if service != 'wsmtxca': fecha_serv_desde = fecha_serv_desde.replace("-", "") else: fecha_serv_desde = None if self.pyafipws_billing_end_date: fecha_serv_hasta = self.pyafipws_billing_end_date.strftime( "%Y-%m-%d") if service != 'wsmtxca': fecha_serv_hasta = fecha_serv_hasta.replace("-", "") else: fecha_serv_hasta = None else: fecha_venc_pago = fecha_serv_desde = fecha_serv_hasta = None # customer tax number: if self.party.vat_number: nro_doc = self.party.vat_number if len(nro_doc) < 11: tipo_doc = 96 # DNI else: tipo_doc = 80 # CUIT else: nro_doc = "0" # only "consumidor final" tipo_doc = 99 # consumidor final # invoice amount totals: imp_total = str("%.2f" % abs(self.total_amount)) imp_tot_conc = "0.00" imp_neto = str("%.2f" % abs(self.untaxed_amount)) imp_iva = str("%.2f" % abs(self.tax_amount)) imp_subtotal = imp_neto # TODO: not allways the case! imp_trib = "0.00" imp_op_ex = "0.00" if self.currency.code == 'ARS': moneda_id = "PES" moneda_ctz = 1 else: moneda_id = {'USD': 'DOL'}[self.currency.code] ctz = 1 / self.currency.rate moneda_ctz = str("%.2f" % ctz) # foreign trade data: export permit, country code, etc.: if self.pyafipws_incoterms: incoterms = self.pyafipws_incoterms incoterms_ds = dict(self._fields['pyafipws_incoterms'].selection)[ self.pyafipws_incoterms] else: incoterms = incoterms_ds = None if incoterms == None and incoterms_ds == None and service == 'wsfex': self.raise_user_error('missing_pyafipws_incoterms') if int(tipo_cbte) == 19 and tipo_expo == 1: permiso_existente = "N" or "S" # not used now else: permiso_existente = "" obs_generales = self.comment if self.payment_term: forma_pago = self.payment_term.name obs_comerciales = self.payment_term.name else: forma_pago = obs_comerciales = None idioma_cbte = 1 # invoice language: spanish / español # customer data (foreign trade): nombre_cliente = self.party.name if self.party.vat_number: if self.party.vat_country == "AR": # use the Argentina AFIP's global CUIT for the country: cuit_pais_cliente = self.party.vat_number id_impositivo = None else: # use the VAT number directly id_impositivo = self.party.vat_number # TODO: the prefix could be used to map the customer country cuit_pais_cliente = None else: cuit_pais_cliente = id_impositivo = None if self.invoice_address: address = self.invoice_address domicilio_cliente = " - ".join([ address.name or '', address.street or '', address.streetbis or '', address.zip or '', address.city or '', ]) else: domicilio_cliente = "" if self.invoice_address.country: # map ISO country code to AFIP destination country code: pais_dst_cmp = { 'ar': 200, 'bo': 202, 'br': 203, 'ca': 204, 'co': 205, 'cu': 207, 'cl': 208, 'ec': 210, 'us': 212, 'mx': 218, 'py': 221, 'pe': 222, 'uy': 225, 've': 226, 'cn': 310, 'tw': 313, 'in': 315, 'il': 319, 'jp': 320, 'at': 405, 'be': 406, 'dk': 409, 'es': 410, 'fr': 412, 'gr': 413, 'it': 417, 'nl': 423, 'pt': 620, 'uk': 426, 'sz': 430, 'de': 438, 'ru': 444, 'eu': 497, 'cr': '206' }[self.invoice_address.country.code.lower()] # create the invoice internally in the helper if service == 'wsfe': ws.CrearFactura(concepto, tipo_doc, nro_doc, tipo_cbte, punto_vta, cbt_desde, cbt_hasta, imp_total, imp_tot_conc, imp_neto, imp_iva, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, fecha_serv_desde, fecha_serv_hasta, moneda_id, moneda_ctz) elif service == 'wsmtxca': ws.CrearFactura(concepto, tipo_doc, nro_doc, tipo_cbte, punto_vta, cbt_desde, cbt_hasta, imp_total, imp_tot_conc, imp_neto, imp_subtotal, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, fecha_serv_desde, fecha_serv_hasta, moneda_id, moneda_ctz, obs_generales) elif service == 'wsfex': ws.CrearFactura(tipo_cbte, punto_vta, cbte_nro, fecha_cbte, imp_total, tipo_expo, permiso_existente, pais_dst_cmp, nombre_cliente, cuit_pais_cliente, domicilio_cliente, id_impositivo, moneda_id, moneda_ctz, obs_comerciales, obs_generales, forma_pago, incoterms, idioma_cbte, incoterms_ds) # analyze VAT (IVA) and other taxes (tributo): if service in ('wsfe', 'wsmtxca'): for tax_line in self.taxes: tax = tax_line.tax if tax.group.name == "IVA": iva_id = IVA_AFIP_CODE[tax.rate] base_imp = ("%.2f" % abs(tax_line.base)) importe = ("%.2f" % abs(tax_line.amount)) # add the vat detail in the helper ws.AgregarIva(iva_id, base_imp, importe) else: if 'impuesto' in tax_line.tax.name.lower(): tributo_id = 1 # nacional elif 'iibbb' in tax_line.tax.name.lower(): tributo_id = 3 # provincial elif 'tasa' in tax_line.tax.name.lower(): tributo_id = 4 # municipal else: tributo_id = 99 desc = tax_line.name base_imp = ("%.2f" % abs(tax_line.base)) importe = ("%.2f" % abs(tax_line.amount)) alic = "%.2f" % tax_line.base # add the other tax detail in the helper ws.AgregarTributo(tributo_id, desc, base_imp, alic, importe) ## Agrego un item: #codigo = "PRO1" #ds = "Producto Tipo 1 Exportacion MERCOSUR ISO 9001" #qty = 2 #precio = "150.00" #umed = 1 # Ver tabla de parámetros (unidades de medida) #bonif = "50.00" #imp_total = "250.00" # importe total final del artículo # analize line items - invoice detail # umeds # Parametros. Unidades de Medida, etc. # https://code.google.com/p/pyafipws/wiki/WSFEX#WSFEX/RECEX_Parameter_Tables if service in ('wsfex', 'wsmtxca'): for line in self.lines: if line.product: codigo = line.product.code else: codigo = 0 ds = line.description qty = line.quantity umed = 7 # FIXME: (7 - unit) precio = str(line.unit_price) importe_total = str(line.amount) bonif = None # line.discount #for tax in line.taxes: # if tax.group.name == "IVA": # iva_id = IVA_AFIP_CODE[tax.rate] # imp_iva = importe * tax.rate #if service == 'wsmtxca': # ws.AgregarItem(u_mtx, cod_mtx, codigo, ds, qty, umed, # precio, bonif, iva_id, imp_iva, importe+imp_iva) if service == 'wsfex': ws.AgregarItem(codigo, ds, qty, umed, precio, importe_total, bonif) # Request the authorization! (call the AFIP webservice method) try: if service == 'wsfe': ws.CAESolicitar() vto = ws.Vencimiento elif service == 'wsmtxca': ws.AutorizarComprobante() vto = ws.Vencimiento elif service == 'wsfex': ws.Authorize(self.id) vto = ws.FchVencCAE #except SoapFault as fault: # msg = 'Falla SOAP %s: %s' % (fault.faultcode, fault.faultstring) except Exception, e: if ws.Excepcion: # get the exception already parsed by the helper #import ipdb; ipdb.set_trace() # XXX BREAKPOINT msg = ws.Excepcion + ' ' + str(e) else: # avoid encoding problem when reporting exceptions to the user: import traceback import sys msg = traceback.format_exception_only(sys.exc_type, sys.exc_value)[0]
from builtins import str "Pruebas para WSFEv1 de AFIP (Factura Electrónica Mercado Interno sin detalle)" __author__ = "Mariano Reingart <*****@*****.**>" __copyright__ = "Copyright (C) 2010-2019 Mariano Reingart" __license__ = "GPL 3.0" import datetime import sys import pytest import os import future __WSDL__ = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL" __obj__ = WSFEv1() __service__ = "wsfe" CUIT = 20267565393 CERT = "reingart.crt" PKEY = "reingart.key" CACERT = "conf/afip_ca_info.crt" CACHE = "" pytestmark = [pytest.mark.vcr, pytest.mark.freeze_time('2021-07-01')] def test_dummy(auth): wsfev1 = auth wsfev1.Dummy() print("AppServerStatus", wsfev1.AppServerStatus)
def get(self, cr, uid, ids, context={}): #invoice = self.pool.get('account.invoice') for wiz in self.browse(cr, uid, ids): company = wiz.journal.company_id tipo_cbte = wiz.journal.pyafipws_invoice_type punto_vta = wiz.journal.pyafipws_point_of_sale service = wiz.journal.pyafipws_electronic_invoice_service # check if it is an electronic invoice sale point: if not tipo_cbte or not punto_vta or not service: raise osv.except_osv('Error !', "Solo factura electrónica") # authenticate against AFIP: auth_data = company.pyafipws_authenticate(service=service) # create the proxy and get the configuration system parameters: cfg = self.pool.get('ir.config_parameter') cache = cfg.get_param(cr, uid, 'pyafipws.cache', context=context) proxy = cfg.get_param(cr, uid, 'pyafipws.proxy', context=context) wsdl = cfg.get_param(cr, uid, 'pyafipws.%s.url' % service, context=context) # import the AFIP webservice helper for electronic invoice if service == 'wsfe': from pyafipws.wsfev1 import WSFEv1, SoapFault # local market ws = WSFEv1() elif service == 'wsmtxca': from pyafipws.wsmtx import WSMTXCA, SoapFault # local + detail wsdl = cfg.get_param(cr, uid, 'pyafipws.wsmtxca.url', context=context) ws = WSMTXCA() elif service == 'wsfex': from pyafipws.wsfexv1 import WSFEXv1, SoapFault # foreign trade wsdl = cfg.get_param(cr, uid, 'pyafipws.wsfex.url', context=context) ws = WSFEXv1() else: raise osv.except_osv('Error !', "%s no soportado" % service) # connect to the webservice and call to the test method ws.Conectar(cache or "", wsdl or "", proxy or "") # set AFIP webservice credentials: ws.Cuit = company.pyafipws_cuit ws.Token = auth_data['token'] ws.Sign = auth_data['sign'] if service in ('wsfe', 'wsmtxca'): if not wiz.cbte_nro: wiz.cbte_nro = ws.CompUltimoAutorizado( tipo_cbte, punto_vta) ws.CompConsultar(tipo_cbte, punto_vta, wiz.cbte_nro) vat = ws.ImptoLiq else: if not wiz.cbte_nro: wiz.cbte_nro = ws.GetLastCMP(tipo_cbte, punto_vta) ws.GetCMP(tipo_cbte, punto_vta, wiz.cbte_nro) vat = 0 # update the form fields with the values returned from AFIP: self.write(cr, uid, ids, { 'cae': ws.CAE, 'cae_due': ws.Vencimiento, 'total': ws.ImpTotal or 0, 'vat': vat, 'cbte_nro': ws.CbteNro, }, context=context) return { 'type': 'ir.actions.act_window', 'res_model': 'pyafipws.invoice.wizard', 'view_mode': 'form', 'view_type': 'form', 'res_id': wiz.id, 'views': [(False, 'form')], 'target': 'new', }