def on_change_vat(self): xmlPath = os.path.dirname(os.path.abspath(__file__))+'/xml' for record in self: if (record.vat) : ruc = record.vat tipo_documento = record.sunat_tipo_documento if(ruc!=""): SunatService = Service() SunatService.setXMLPath(xmlPath) response = {} response = SunatService.consultRUC_Pydevs(tipo_documento,ruc) #raise Warning(len(response['data'])) if len(response['data'])==0: raise Warning("El RUC no fue encontrado en registros de SUNAT") else: self.update_document(response)
def on_change_vat(self): xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' for record in self: if (record.vat): ruc = record.vat if (ruc != ""): SunatService = Service() SunatService.setXMLPath(xmlPath) response = {} response = SunatService.consultRUC(ruc) if not response: raise Warning( "El RUC no fue encontrado en registros de SUNAT") else: self.street = response['address'] self.name = response["name"] self.city = response["city"]
def invoice_validate(self): tipo_documento_consultar = self.journal_id.code if (tipo_documento_consultar == "NCR"): invoice_items = [] total_venta_gravada = 0.0 total_venta = 0.0 sumatoria_ivg = 0.0 for invoice in self: items = invoice.invoice_line_ids for item in items: index = 0 for taxes in invoice.tax_line_ids: if (index == 0): impuesto = taxes.tax_id.amount / 100 valor_venta = (item.price_unit * item.quantity) monto_afectacion_IGV = valor_venta * impuesto precio_unitario = (item.price_unit * impuesto) + item.price_unit invoice_item = { 'cantidad': str(item.quantity), 'descripcion': item.name, 'valorVenta': valor_venta, 'valorUnitario': item.price_unit, 'precioVentaUnitario': precio_unitario, 'tipoPrecioVentaUnitario': '01', 'montoAfectacionIgv': monto_afectacion_IGV, 'tipoAfectacionIgv': '10', 'unidadMedidaCantidad': 'ZZ' } invoice_items.append(invoice_item) total_venta_gravada += valor_venta total_venta += precio_unitario sumatoria_ivg += monto_afectacion_IGV index = index + 1 serieParts = str(invoice.number).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] currentDateTime = datetime.now() currentTime = currentDateTime.strftime("%H:%M:%S") data = { 'serie': str(serieConsecutivoString), "numero": str(serieConsecutivo), "emisor": { "tipo": 6, "nro": invoice.company_id.sol_ruc, "nombre": invoice.company_id.name, "direccion": invoice.company_id.street, "ciudad": invoice.company_id.city, "departamento": invoice.company_id.state_id.name, "codigoPostal": invoice.company_id.zip, "codigoPais": invoice.company_id.country_id.code }, "receptor": { "tipo": 6, "nro": invoice.partner_id.vat, "nombre": invoice.partner_id.name, "direccion": invoice.partner_id.street, }, "tipoDocumento": "01", "notaDescripcion": self.name, "notaDiscrepanciaCode": self.discrepance_code, "documentoOrigen": self.origin, "fechaEmision": str(invoice.date_invoice).replace("/", "-", 3), "fechaVencimiento": str(invoice.date_due).replace("/", "-", 3), "horaEmision": currentTime, 'totalVentaGravada': total_venta_gravada, 'sumatoriaIgv': str(round(float(sumatoria_ivg), 2)), 'totalVenta': total_venta, 'tipoMoneda': invoice.currency_id.name, 'items': invoice_items, 'sol': { 'usuario': invoice.company_id.sol_username, 'clave': invoice.company_id.sol_password } } # xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) SunatService.fileName = str( invoice.company_id.sol_ruc) + "-07-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(invoice.company_id.api_mode, "sendBill") sunatResponse = SunatService.processCreditNote(data) #with open('/home/rockscripts/Documents/data1.json', 'w') as outfile: # json.dump(data, outfile) if (sunatResponse["status"] == "OK"): self.api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"] ["referencia"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]["description"]) return super(account_invoice, self).invoice_validate() else: errorMessage = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]) + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]) raise Warning(errorMessage) elif (tipo_documento_consultar == "NDB"): invoice_items = [] total_venta_gravada = 0.0 total_venta = 0.0 sumatoria_ivg = 0.0 for invoice in self: items = invoice.invoice_line_ids for item in items: index = 0 for taxes in invoice.tax_line_ids: if (index == 0): impuesto = taxes.tax_id.amount / 100 valor_venta = (item.price_unit * item.quantity) monto_afectacion_IGV = valor_venta * impuesto precio_unitario = (item.price_unit * impuesto) + item.price_unit invoice_item = { 'cantidad': str(item.quantity), 'descripcion': item.name, 'valorVenta': valor_venta, 'valorUnitario': item.price_unit, 'precioVentaUnitario': precio_unitario, 'tipoPrecioVentaUnitario': '01', 'montoAfectacionIgv': monto_afectacion_IGV, 'tipoAfectacionIgv': '10', 'unidadMedidaCantidad': "ZZ", } invoice_items.append(invoice_item) total_venta_gravada += valor_venta total_venta += precio_unitario sumatoria_ivg += monto_afectacion_IGV index = index + 1 serieParts = str(invoice.number).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] currentDateTime = datetime.now() currentTime = currentDateTime.strftime("%H:%M:%S") data = { 'serie': str(serieConsecutivoString), "numero": str(serieConsecutivo), "emisor": { "tipo": 6, "nro": invoice.company_id.sol_ruc, "nombre": invoice.company_id.name, "direccion": invoice.company_id.street, "ciudad": invoice.company_id.city, "departamento": invoice.company_id.state_id.name, "codigoPostal": invoice.company_id.zip, "codigoPais": invoice.company_id.country_id.code }, "receptor": { "tipo": 6, "nro": invoice.partner_id.vat, "nombre": invoice.partner_id.name, "direccion": invoice.partner_id.street, }, "tipoDocumento": "01", "notaDescripcion": self.name, "notaDiscrepanciaCode": self.discrepance_code, "documentoOrigen": self.origin, "fechaEmision": str(invoice.date_invoice).replace("/", "-", 3), "fechaVencimiento": str(invoice.date_due).replace("/", "-", 3), "horaEmision": currentTime, 'totalVentaGravada': total_venta_gravada, 'sumatoriaIgv': str(round(float(sumatoria_ivg), 2)), 'totalVenta': total_venta, 'tipoMoneda': invoice.currency_id.name, 'items': invoice_items, 'sol': { 'usuario': invoice.company_id.sol_username, 'clave': invoice.company_id.sol_password } } # xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) SunatService.fileName = str( invoice.company_id.sol_ruc) + "-08-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(invoice.company_id.api_mode, "sendBill") sunatResponse = SunatService.processDebitNote(data) #with open('/home/rockscripts/Documents/data1.json', 'w') as outfile: # json.dump(sunatResponse, outfile) if (sunatResponse["status"] == "OK"): self.api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"] ["referencia"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]["description"]) return super(account_invoice, self).invoice_validate() else: errorMessage = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]) + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]) raise Warning(errorMessage) elif (tipo_documento_consultar == "BOL"): invoice_items = [] total_venta_gravada = 0.0 total_venta = 0.0 sumatoria_ivg = 0.0 for invoice in self: items = invoice.invoice_line_ids for item in items: index = 0 for taxes in invoice.tax_line_ids: if (index == 0): impuesto = taxes.tax_id.amount / 100 valor_venta = (item.price_unit * item.quantity) monto_afectacion_IGV = valor_venta * impuesto precio_unitario = (item.price_unit * impuesto) + item.price_unit invoice_item = { 'cantidad': str(item.quantity), 'descripcion': item.name, 'valorVenta': valor_venta, 'valorUnitario': item.price_unit, 'precioVentaUnitario': precio_unitario, 'tipoPrecioVentaUnitario': '01', 'montoAfectacionIgv': monto_afectacion_IGV, 'tipoAfectacionIgv': '10', 'unidadMedidaCantidad': "ZZ", } invoice_items.append(invoice_item) total_venta_gravada += valor_venta total_venta += precio_unitario sumatoria_ivg += monto_afectacion_IGV index = index + 1 #old - serieParts = str(invoice.number).split("/") #old - serieConsecutivo = serieParts[2] #old - serieConsecutivo = serieConsecutivo[1:] serieParts = str(invoice.number).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] currentDateTime = datetime.now() currentTime = currentDateTime.strftime("%H:%M:%S") data = { 'serie': str(serieConsecutivoString), "numero": str(serieConsecutivo), "emisor": { "tipo": 6, "nro": invoice.company_id.sol_ruc, "nombre": invoice.company_id.name, "direccion": invoice.company_id.street, "ciudad": invoice.company_id.city, "departamento": invoice.company_id.state_id.name, "codigoPostal": invoice.company_id.zip, "codigoPais": invoice.company_id.country_id.code }, "receptor": { "tipo": 6, "nro": invoice.partner_id.vat, "nombre": invoice.partner_id.name, "direccion": invoice.partner_id.street, }, "fechaEmision": str(invoice.date_invoice).replace("/", "-", 3), "fechaVencimiento": str(invoice.date_due).replace("/", "-", 3), "horaEmision": currentTime, 'totalVentaGravada': total_venta_gravada, 'sumatoriaIgv': str(round(float(sumatoria_ivg), 2)), 'totalVenta': total_venta, 'tipoMoneda': invoice.currency_id.name, 'items': invoice_items, 'sol': { 'usuario': invoice.company_id.sol_username, 'clave': invoice.company_id.sol_password } } # xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) SunatService.setXMLPath(xmlPath) SunatService.fileName = str( invoice.company_id.sol_ruc) + "-03-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(invoice.company_id.api_mode, "sendBill") sunatResponse = SunatService.processTicket(data) #with open('/home/rockscripts/Documents/data1.json', 'w') as outfile: # json.dump(sunatResponse, outfile) if (sunatResponse["status"] == "OK"): self.api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"] ["referencia"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]["description"]) return super(account_invoice, self).invoice_validate() else: errorMessage = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]) + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]) raise Warning(errorMessage) else: #FOR INVOICES invoice_items = [] total_venta_gravada = 0.0 total_venta = 0.0 sumatoria_ivg = 0.0 for invoice in self: items = invoice.invoice_line_ids for item in items: index = 0 for taxes in invoice.tax_line_ids: if (index == 0): impuesto = taxes.tax_id.amount / 100 valor_venta = (item.price_unit * item.quantity) monto_afectacion_IGV = valor_venta * impuesto precio_unitario = (item.price_unit * impuesto) + item.price_unit invoice_item = { 'cantidad': str(item.quantity), 'descripcion': item.name, 'valorVenta': valor_venta, 'valorUnitario': item.price_unit, 'precioVentaUnitario': precio_unitario, 'tipoPrecioVentaUnitario': '01', 'montoAfectacionIgv': monto_afectacion_IGV, 'tipoAfectacionIgv': '10', 'unidadMedidaCantidad': "ZZ", } invoice_items.append(invoice_item) total_venta_gravada += valor_venta total_venta += precio_unitario sumatoria_ivg += monto_afectacion_IGV index = index + 1 serieParts = str(invoice.number).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] currentDateTime = datetime.now() currentTime = currentDateTime.strftime("%H:%M:%S") data = { 'serie': str(serieConsecutivoString), "numero": str(serieConsecutivo), "emisor": { "tipo": 6, "nro": invoice.company_id.sol_ruc, "nombre": invoice.company_id.name, "direccion": invoice.company_id.street, "ciudad": invoice.company_id.city, "departamento": invoice.company_id.state_id.name, "codigoPostal": invoice.company_id.zip, "codigoPais": invoice.company_id.country_id.code }, "receptor": { "tipo": 6, "nro": invoice.partner_id.vat, "nombre": invoice.partner_id.name, "direccion": invoice.partner_id.street, }, "fechaEmision": str(invoice.date_invoice).replace("/", "-", 3), "fechaVencimiento": str(invoice.date_due).replace("/", "-", 3), "horaEmision": currentTime, 'totalVentaGravada': total_venta_gravada, 'sumatoriaIgv': str(round(float(sumatoria_ivg), 2)), 'totalVenta': total_venta, 'tipoMoneda': invoice.currency_id.name, 'items': invoice_items, 'sol': { 'usuario': invoice.company_id.sol_username, 'clave': invoice.company_id.sol_password } } #with open('/opt/odoo/custom-addons/sfact_addon/data.json', 'w') as outfile: # json.dump(data, outfile) xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) SunatService.setXMLPath(xmlPath) SunatService.fileName = str( invoice.company_id.sol_ruc) + "-01-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(invoice.company_id.api_mode, "sendBill") sunatResponse = SunatService.processInvoice(data) #with open('/home/rockscripts/Documents/data1.json', 'w') as outfile: # json.dump(sunatResponse, outfile) if (sunatResponse["status"] == "OK"): self.api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"] ["referencia"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]["description"]) return super(account_invoice, self).invoice_validate() else: errorMessage = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]) + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]) raise Warning(errorMessage)
def edocs_submit_invoices(self, **kw): query = "select nextcall from ir_cron where cron_name = '" + str( "sunat_edocs") + "'" request.cr.execute(query) cron_job_edocs = request.cr.dictfetchone() nextcall_datetime = str(cron_job_edocs["nextcall"]).split(" ") invoice_date_limit = nextcall_datetime[0] query = "select id, number, company_id, unsigned_document, signed_document, response_document from account_invoice where date_invoice <= '" + str( invoice_date_limit) + "' and (sunat_request_status = '" + str( "FAIL") + "' or sunat_request_status = '" + str( "No Emitido") + "' or sunat_request_status = '" + str( "not_requested") + "')" request.cr.execute(query) invoices_unsubmited = request.cr.dictfetchall() for invoice_unsubmited in invoices_unsubmited: query = "select res_partner.vat, res_company.api_mode, res_company.sol_ruc, res_company.sol_username, res_company.sol_password, res_company.certs from res_company left join res_partner on res_partner.company_id = res_company.id where res_company.id = " + str( invoice_unsubmited['company_id'] ) + " and res_partner.is_company = TRUE and res_company.partner_id = res_partner.id" request.cr.execute(query) company_fields = request.cr.dictfetchone() if (invoice_unsubmited["number"]): serieParts = str(invoice_unsubmited["number"]).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] sunat_data = { "secuencia_consecutivo": serieConsecutivo, "numero": serieConsecutivo, # cdr "serie": serieConsecutivoString, "sunat_sol": { "ruc": company_fields["sol_ruc"], 'usuario': company_fields["sol_username"], 'clave': company_fields["sol_password"] }, "xml": { #"signed":base64.b64decode((invoice_fields["signed_document"])) }, "licencia": "081OHTGAVHJZ4GOZJGJV" } # with open('/odoo_sunatperu/custom/addons/sunat_fact/models/log.json', 'w+') as outfile: # json.dump(sunat_data, outfile) xmlPath = str(os.path.dirname( os.path.abspath(__file__))).replace( "controllers", "models") + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) if ("F0" in serieConsecutivoString): SunatService.fileName = str( company_fields["vat"]) + "-01-" + str( serieConsecutivoString) + "-" + str( serieConsecutivo) SunatService.documentType = str("01") if ("BF" in serieConsecutivoString): SunatService.fileName = str( company_fields["vat"]) + "-03-" + str( serieConsecutivoString) + "-" + str( serieConsecutivo) SunatService.documentType = str("03") if ("FD" in serieConsecutivoString): SunatService.fileName = str( company_fields["vat"]) + "-08-" + str( serieConsecutivoString) + "-" + str( serieConsecutivo) SunatService.documentType = str("08") if ("FC" in serieConsecutivoString): SunatService.fileName = str( company_fields["vat"]) + "-07-" + str( serieConsecutivoString) + "-" + str( serieConsecutivo) SunatService.documentType = str("07") SunatService.initSunatAPI(company_fields["api_mode"], "sendBill") sunatResponse = SunatService.processInvoiceFromSignedXML( sunat_data) #with open('/home/rockscripts/Documents/data.json', 'w') as outfile: # json.dump(SunatService.fileName, outfile) if (sunatResponse["status"] == "OK"): # save xml documents steps for reference in edocs response_document_filename = str("R_") + "-01-" + str( serieConsecutivoString) + "-" + str( serieConsecutivo) + str(".XML") api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"]["referencia"]).replace( "'", '"') + "\n" + " " + str( sunatResponse["body"] ["description"]).replace("'", '"') query = "update account_invoice set sunat_request_status = 'OK', api_message = '" + str( api_message ) + "', response_document_filename = '" + str( response_document_filename ) + "', sunat_request_type = 'Automatizada' where id = " + str( invoice_unsubmited["id"]) request.cr.execute(query) #if(serieConsecutivo=="00000008"): # with open('/home/rockscripts/Documents/data.json', 'w') as outfile: # json.dump(query, outfile) else: api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + " " + str( sunatResponse["body"]).replace( "'", '"') + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]).replace("'", '"') query = "update account_invoice set sunat_request_status = 'FAIL', api_message = '" + str( api_message ) + "', sunat_request_type = 'Automatizada' where id = " + str( invoice_unsubmited["id"]) request.cr.execute(query)
def invoice_validate(self): urlPath = http.request.httprequest.full_path if 'payment/process' in urlPath: return super(account_invoice, self).invoice_validate() #FOR INVOICES invoice_items = [] total_venta_gravada = 0.0 total_venta = 0.0 sumatoria_igv = 0.0 sumatoria_igv_impuesto = 0.0 total_venta_igv = 0.0 sumatoria_isc = 0.0 sumatoria_isc_impuesto = 0.0 total_venta_ics = 0.0 sumatoria_inafecto = 0.0 sumatoria_inafecto_impuesto = 0.0 total_venta_inafecto = 0.0 sumatoria_gratuita = 0.0 sumatoria_gratuita_impuesto = 0.0 total_venta_gratuita = 0.0 sumatoria_exonerada = 0.0 sumatoria_exonerada_impuesto = 0.0 total_venta_exonerada = 0.0 sumatoria_exportacion = 0.0 sumatoria_exportacion_impuesto = 0.0 total_venta_exportacion = 0.0 sumatoria_other = 0.0 sumatoria_other_impuesto = 0.0 total_venta_other = 0.0 tipoAfectacionTributo = 0 tipoAfectacionISC = 0 #if '/web/dataset/call_kw/pos.order/create_from_ui?' in urlPath: # return super(account_invoice, self).invoice_validate() for invoice in self: if invoice.partner_id.vat == "" or invoice.partner_id.vat == False: raise Warning(_("Por favor digitar el RUC del receptor")) tipo_documento_consultar = self.journal_id.code if (tipo_documento_consultar == "NCR"): index = 0 total_venta = 0 for invoice in self: items = invoice.invoice_line_ids for item in items: tax_line = False for tax in item.invoice_line_tax_ids: tax_line = tax impuesto = tax_line.amount / 100 valor_venta = (item.price_unit * item.quantity) monto_afectacion_tributo = valor_venta * impuesto precio_unitario = (item.price_unit * impuesto) + item.price_unit if (str(int(tax_line.sunat_tributo)) == "1000"): sumatoria_igv += monto_afectacion_tributo sumatoria_igv_impuesto += impuesto total_venta_igv += valor_venta total_venta += total_venta_igv tipoAfectacionTributo = "10" if (str(int(tax_line.sunat_tributo)) == "2000"): sumatoria_isc += monto_afectacion_tributo sumatoria_isc_impuesto += impuesto total_venta_ics += valor_venta total_venta += total_venta_ics tipoAfectacionTributo = "01" # catalogo 8 if (str(int(tax_line.sunat_tributo)) == "9998"): sumatoria_inafecto += monto_afectacion_tributo sumatoria_inafecto_impuesto += impuesto total_venta_inafecto += valor_venta total_venta += total_venta_inafecto tipoAfectacionTributo = "30" if (str(int(tax_line.sunat_tributo)) == "9996"): sumatoria_gratuita += monto_afectacion_tributo sumatoria_gratuita_impuesto += impuesto total_venta_gratuita += valor_venta total_venta += total_venta_gratuita tipoAfectacionTributo = "21" if (str(int(tax_line.sunat_tributo)) == "9997"): sumatoria_exonerada += monto_afectacion_tributo sumatoria_exonerada_impuesto += impuesto total_venta_exonerada += valor_venta total_venta += total_venta_exonerada tipoAfectacionTributo = "20" if (str(int(tax_line.sunat_tributo)) == "9995"): sumatoria_exportacion += monto_afectacion_tributo sumatoria_exportacion_impuesto += impuesto total_venta_exportacion += valor_venta total_venta += total_venta_exportacion tipoAfectacionTributo = "40" if (str(int(tax_line.sunat_tributo)) == "9999"): sumatoria_other += monto_afectacion_tributo sumatoria_other_impuesto += impuesto total_venta_other += valor_venta total_venta += total_venta_other tipoAfectacionTributo = "10" invoice_item = { 'id': str(item.id), 'cantidad': str(item.quantity), 'descripcion': item.name, 'valorVenta': valor_venta, 'valorUnitario': item.price_unit, 'precioVentaUnitario': precio_unitario, 'tipoPrecioVentaUnitario': '01', #instalar en ficha de producto catalogo 16 "tributo": { "codigo": str(int(tax_line.sunat_tributo)), "porcentaje": tax_line.amount, #taxes.tax_id.amount, 'montoAfectacionTributo': monto_afectacion_tributo, 'tipoAfectacionTributo': tipoAfectacionTributo, # pendiente si es igv - catalogo 7. #pendiente si es isc - catalogo 8 para codigo = 2000 ISC }, 'unidadMedidaCantidad': "ZZ", } invoice_items.append(invoice_item) serieParts = str(invoice.number).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] currentDateTime = datetime.now() currentTime = currentDateTime.strftime("%H:%M:%S") #end for data = { 'serie': str(serieConsecutivoString), "numero": str(serieConsecutivo), "emisor": { "tipo": 6, "nro": invoice.company_id.sol_ruc, "nombre": invoice.company_id.name, "direccion": invoice.company_id.street, "ciudad": invoice.company_id.city, "departamento": invoice.company_id.state_id.name, "codigoPostal": invoice.company_id.zip, "codigoPais": invoice.company_id.country_id.code, "ubigeo": invoice.company_id.ubigeo }, "receptor": { "tipo": 6, "nro": invoice.partner_id.vat, "nombre": invoice.partner_id.name, "direccion": invoice.partner_id.street, }, "tributo": { 'IGV': { "total_venta": str(round(float(total_venta_igv), 2)), "impuesto": str(round(float(sumatoria_igv_impuesto), 2)), "sumatoria": str(round(float(sumatoria_igv), 2)) }, 'ISC': { "total_venta": str(round(float(total_venta_ics), 2)), "impuesto": str(round(float(sumatoria_isc_impuesto), 2)), "sumatoria": str(round(float(sumatoria_isc), 2)) }, 'inafecto': { "total_venta": str(round(float(total_venta_inafecto), 2)), "impuesto": str(round(float(sumatoria_inafecto_impuesto), 2)), "sumatoria": str(round(float(sumatoria_inafecto), 2)) }, 'exonerado': { "total_venta": str(round(float(total_venta_exonerada), 2)), "impuesto": str(round(float(sumatoria_exonerada_impuesto), 2)), "sumatoria": str(round(float(sumatoria_exonerada), 2)) }, 'exportacion': { "total_venta": str(round(float(total_venta_exportacion), 2)), "impuesto": str(round(float(sumatoria_exportacion_impuesto), 2)), "sumatoria": str(round(float(sumatoria_exportacion), 2)) }, 'other': { "total_venta": str(round(float(total_venta_other), 2)), "impuesto": str(round(float(sumatoria_other_impuesto), 2)), "sumatoria": str(round(float(sumatoria_other), 2)) }, }, "notaDescripcion": self.name, "notaDiscrepanciaCode": self.discrepance_code, "documentoOrigen": self.origin, "documentoOrigenTipo": str("01"), #01 factura, 03 boleta, 12 tiket de venta "fechaEmision": str(invoice.date_invoice).replace("/", "-", 3), "fechaVencimiento": str(invoice.date_due).replace("/", "-", 3), "horaEmision": currentTime, 'totalVenta': total_venta, 'tipoMoneda': invoice.currency_id.name, 'items': invoice_items, 'sol': { 'usuario': invoice.company_id.sol_username, 'clave': invoice.company_id.sol_password }, 'licencia': "081OHTGAVHJZ4GOZJGJV" } # xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) SunatService.fileName = str( invoice.company_id.sol_ruc) + "-07-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(invoice.company_id.api_mode, "sendBill") sunatResponse = SunatService.processCreditNote(data) #with open('/home/rockscripts/Documents/data1.json', 'w') as outfile: # json.dump(data, outfile) if (sunatResponse["status"] == "OK"): # generate qr for invoices and tickets in pos base_url = request.env['ir.config_parameter'].get_param( 'web.base.url') base_url += '/web#id=%d&view_type=form&model=%s' % (self.id, self._name) qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=20, border=4, ) qr.add_data(base_url) qr.make(fit=True) img = qr.make_image() temp = BytesIO() img.save(temp, format="PNG") self.qr_image = base64.b64encode(temp.getvalue()) self.qr_in_report = True self.api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"] ["referencia"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]["description"]) return super(account_invoice, self).invoice_validate() else: errorMessage = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]) + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]) raise Warning(errorMessage) elif (tipo_documento_consultar == "NDB"): index = 0 total_venta = 0 for invoice in self: items = invoice.invoice_line_ids for item in items: tax_line = False for tax in item.invoice_line_tax_ids: tax_line = tax impuesto = tax_line.amount / 100 valor_venta = (item.price_unit * item.quantity) monto_afectacion_tributo = valor_venta * impuesto precio_unitario = (item.price_unit * impuesto) + item.price_unit if (str(int(tax_line.sunat_tributo)) == "1000"): sumatoria_igv += monto_afectacion_tributo sumatoria_igv_impuesto += impuesto total_venta_igv += valor_venta total_venta += total_venta_igv tipoAfectacionTributo = "10" if (str(int(tax_line.sunat_tributo)) == "2000"): sumatoria_isc += monto_afectacion_tributo sumatoria_isc_impuesto += impuesto total_venta_ics += valor_venta total_venta += total_venta_ics tipoAfectacionTributo = "01" # catalogo 8 if (str(int(tax_line.sunat_tributo)) == "9998"): sumatoria_inafecto += monto_afectacion_tributo sumatoria_inafecto_impuesto += impuesto total_venta_inafecto += valor_venta total_venta += total_venta_inafecto tipoAfectacionTributo = "30" if (str(int(tax_line.sunat_tributo)) == "9996"): sumatoria_gratuita += monto_afectacion_tributo sumatoria_gratuita_impuesto += impuesto total_venta_gratuita += valor_venta total_venta += total_venta_gratuita tipoAfectacionTributo = "21" if (str(int(tax_line.sunat_tributo)) == "9997"): sumatoria_exonerada += monto_afectacion_tributo sumatoria_exonerada_impuesto += impuesto total_venta_exonerada += valor_venta total_venta += total_venta_exonerada tipoAfectacionTributo = "20" if (str(int(tax_line.sunat_tributo)) == "9995"): sumatoria_exportacion += monto_afectacion_tributo sumatoria_exportacion_impuesto += impuesto total_venta += sumatoria_exportacion_impuesto tipoAfectacionTributo = "40" if (str(int(tax_line.sunat_tributo)) == "9999"): sumatoria_other += monto_afectacion_tributo sumatoria_other_impuesto += impuesto total_venta_other += valor_venta total_venta += total_venta_other tipoAfectacionTributo = "10" invoice_item = { 'id': str(item.id), 'cantidad': str(item.quantity), 'descripcion': item.name, 'valorVenta': valor_venta, 'valorUnitario': item.price_unit, 'precioVentaUnitario': precio_unitario, 'tipoPrecioVentaUnitario': '01', #instalar en ficha de producto catalogo 16 "tributo": { "codigo": str(int(tax_line.sunat_tributo)), "porcentaje": tax_line.amount, #taxes.tax_id.amount, 'montoAfectacionTributo': monto_afectacion_tributo, 'tipoAfectacionTributo': tipoAfectacionTributo, # pendiente si es igv - catalogo 7. #pendiente si es isc - catalogo 8 para codigo = 2000 ISC }, 'unidadMedidaCantidad': "ZZ", } invoice_items.append(invoice_item) serieParts = str(invoice.number).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] currentDateTime = datetime.now() currentTime = currentDateTime.strftime("%H:%M:%S") #end for data = { 'serie': str(serieConsecutivoString), "numero": str(serieConsecutivo), "emisor": { "tipo": 6, "nro": invoice.company_id.sol_ruc, "nombre": invoice.company_id.name, "direccion": invoice.company_id.street, "ciudad": invoice.company_id.city, "departamento": invoice.company_id.state_id.name, "codigoPostal": invoice.company_id.zip, "codigoPais": invoice.company_id.country_id.code, "ubigeo": invoice.company_id.ubigeo }, "receptor": { "tipo": 6, "nro": invoice.partner_id.vat, "nombre": invoice.partner_id.name, "direccion": invoice.partner_id.street, }, "tributo": { 'IGV': { "total_venta": str(round(float(total_venta_igv), 2)), "impuesto": str(round(float(sumatoria_igv_impuesto), 2)), "sumatoria": str(round(float(sumatoria_igv), 2)) }, 'ISC': { "total_venta": str(round(float(total_venta_ics), 2)), "impuesto": str(round(float(sumatoria_isc_impuesto), 2)), "sumatoria": str(round(float(sumatoria_isc), 2)) }, 'inafecto': { "total_venta": str(round(float(total_venta_inafecto), 2)), "impuesto": str(round(float(sumatoria_inafecto_impuesto), 2)), "sumatoria": str(round(float(sumatoria_inafecto), 2)) }, 'exonerado': { "total_venta": str(round(float(total_venta_exonerada), 2)), "impuesto": str(round(float(sumatoria_exonerada_impuesto), 2)), "sumatoria": str(round(float(sumatoria_exonerada), 2)) }, 'exportacion': { "total_venta": str(round(float(total_venta_exportacion), 2)), "impuesto": str(round(float(sumatoria_exportacion_impuesto), 2)), "sumatoria": str(round(float(sumatoria_exportacion), 2)) }, 'other': { "total_venta": str(round(float(total_venta_other), 2)), "impuesto": str(round(float(sumatoria_other_impuesto), 2)), "sumatoria": str(round(float(sumatoria_other), 2)) }, }, "notaDescripcion": self.name, "notaDiscrepanciaCode": self.discrepance_code, "documentoOrigen": self.origin, "documentoOrigenTipo": str("01"), #01 factura, 03 boleta, 12 tiket de venta "fechaEmision": str(invoice.date_invoice).replace("/", "-", 3), "fechaVencimiento": str(invoice.date_due).replace("/", "-", 3), "horaEmision": currentTime, 'totalVenta': total_venta, 'tipoMoneda': invoice.currency_id.name, 'items': invoice_items, 'sol': { 'usuario': invoice.company_id.sol_username, 'clave': invoice.company_id.sol_password }, 'licencia': "081OHTGAVHJZ4GOZJGJV" } xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) SunatService.fileName = str( invoice.company_id.sol_ruc) + "-08-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(invoice.company_id.api_mode, "sendBill") sunatResponse = SunatService.processDebitNote(data) #with open('/home/rockscripts/Documents/data1.json', 'w') as outfile: # json.dump(sunatResponse, outfile) if (sunatResponse["status"] == "OK"): # generate qr for invoices and tickets in pos base_url = request.env['ir.config_parameter'].get_param( 'web.base.url') base_url += '/web#id=%d&view_type=form&model=%s' % (self.id, self._name) qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=20, border=4, ) qr.add_data(base_url) qr.make(fit=True) img = qr.make_image() temp = BytesIO() img.save(temp, format="PNG") self.qr_image = base64.b64encode(temp.getvalue()) self.qr_in_report = True self.api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"] ["referencia"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]["description"]) return super(account_invoice, self).invoice_validate() else: errorMessage = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]) + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]) raise Warning(errorMessage) elif (tipo_documento_consultar == "BOL"): index = 0 total_venta = 0 for invoice in self: items = invoice.invoice_line_ids for item in items: tax_line = False for tax in item.invoice_line_tax_ids: tax_line = tax impuesto = tax_line.amount / 100 valor_venta = (item.price_unit * item.quantity) monto_afectacion_tributo = valor_venta * impuesto precio_unitario = (item.price_unit * impuesto) + item.price_unit if (str(int(tax_line.sunat_tributo)) == "1000"): sumatoria_igv += monto_afectacion_tributo sumatoria_igv_impuesto += impuesto total_venta_igv += valor_venta total_venta += total_venta_igv tipoAfectacionTributo = "10" if (str(int(tax_line.sunat_tributo)) == "2000"): sumatoria_isc += monto_afectacion_tributo sumatoria_isc_impuesto += impuesto total_venta_ics += valor_venta total_venta += total_venta_ics tipoAfectacionTributo = "01" # catalogo 8 if (str(int(tax_line.sunat_tributo)) == "9998"): sumatoria_inafecto += monto_afectacion_tributo sumatoria_inafecto_impuesto += impuesto total_venta_inafecto += valor_venta total_venta += total_venta_inafecto tipoAfectacionTributo = "30" if (str(int(tax_line.sunat_tributo)) == "9996"): sumatoria_gratuita += monto_afectacion_tributo sumatoria_gratuita_impuesto += impuesto total_venta_gratuita += valor_venta total_venta += total_venta_gratuita tipoAfectacionTributo = "21" if (str(int(tax_line.sunat_tributo)) == "9997"): sumatoria_exonerada += monto_afectacion_tributo sumatoria_exonerada_impuesto += impuesto total_venta_exonerada += valor_venta total_venta += total_venta_exonerada tipoAfectacionTributo = "20" if (str(int(tax_line.sunat_tributo)) == "9995"): sumatoria_exportacion += monto_afectacion_tributo sumatoria_exportacion_impuesto += impuesto total_venta_exportacion += valor_venta total_venta += total_venta_exportacion tipoAfectacionTributo = "40" if (str(int(tax_line.sunat_tributo)) == "9999"): sumatoria_other += monto_afectacion_tributo sumatoria_other_impuesto += impuesto total_venta_other += valor_venta total_venta += total_venta_other tipoAfectacionTributo = "10" invoice_item = { 'id': str(item.id), 'cantidad': str(item.quantity), 'descripcion': item.name, 'valorVenta': valor_venta, 'valorUnitario': item.price_unit, 'precioVentaUnitario': precio_unitario, 'tipoPrecioVentaUnitario': '01', #instalar en ficha de producto catalogo 16 "tributo": { "codigo": str(int(tax_line.sunat_tributo)), "porcentaje": tax_line.amount, #taxes.tax_id.amount, 'montoAfectacionTributo': monto_afectacion_tributo, 'tipoAfectacionTributo': tipoAfectacionTributo, # pendiente si es igv - catalogo 7. #pendiente si es isc - catalogo 8 para codigo = 2000 ISC }, 'unidadMedidaCantidad': "ZZ", } invoice_items.append(invoice_item) serieParts = str(invoice.number).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] currentDateTime = datetime.now() currentTime = currentDateTime.strftime("%H:%M:%S") #end for data = { 'serie': str(serieConsecutivoString), "numero": str(serieConsecutivo), "emisor": { "tipo": 6, "nro": invoice.company_id.sol_ruc, "nombre": invoice.company_id.name, "direccion": invoice.company_id.street, "ciudad": invoice.company_id.city, "departamento": invoice.company_id.state_id.name, "codigoPostal": invoice.company_id.zip, "codigoPais": invoice.company_id.country_id.code, "ubigeo": invoice.company_id.ubigeo }, "receptor": { "tipo": 6, "nro": invoice.partner_id.vat, "nombre": invoice.partner_id.name, "direccion": invoice.partner_id.street, }, "tributo": { 'IGV': { "total_venta": str(round(float(total_venta_igv), 2)), "impuesto": str(round(float(sumatoria_igv_impuesto), 2)), "sumatoria": str(round(float(sumatoria_igv), 2)) }, 'ISC': { "total_venta": str(round(float(total_venta_ics), 2)), "impuesto": str(round(float(sumatoria_isc_impuesto), 2)), "sumatoria": str(round(float(sumatoria_isc), 2)) }, 'inafecto': { "total_venta": str(round(float(total_venta_inafecto), 2)), "impuesto": str(round(float(sumatoria_inafecto_impuesto), 2)), "sumatoria": str(round(float(sumatoria_inafecto), 2)) }, 'exonerado': { "total_venta": str(round(float(total_venta_exonerada), 2)), "impuesto": str(round(float(sumatoria_exonerada_impuesto), 2)), "sumatoria": str(round(float(sumatoria_exonerada), 2)) }, 'exportacion': { "total_venta": str(round(float(total_venta_exportacion), 2)), "impuesto": str(round(float(sumatoria_exportacion_impuesto), 2)), "sumatoria": str(round(float(sumatoria_exportacion), 2)) }, 'other': { "total_venta": str(round(float(total_venta_other), 2)), "impuesto": str(round(float(sumatoria_other_impuesto), 2)), "sumatoria": str(round(float(sumatoria_other), 2)) }, }, "fechaEmision": str(invoice.date_invoice).replace("/", "-", 3), "fechaVencimiento": str(invoice.date_due).replace("/", "-", 3), "horaEmision": currentTime, 'totalVenta': total_venta, 'tipoMoneda': invoice.currency_id.name, 'items': invoice_items, 'sol': { 'usuario': invoice.company_id.sol_username, 'clave': invoice.company_id.sol_password }, 'licencia': "081OHTGAVHJZ4GOZJGJV" } # with open('/home/rockscripts/Documents/data.json', 'w') as outfile: json.dump(data, outfile) xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) SunatService.setXMLPath(xmlPath) SunatService.fileName = str( invoice.company_id.sol_ruc) + "-03-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(invoice.company_id.api_mode, "sendBill") sunatResponse = SunatService.processTicket(data) if (sunatResponse["status"] == "OK"): # generate qr for invoices and tickets in pos base_url = request.env['ir.config_parameter'].get_param( 'web.base.url') base_url += '/web#id=%d&view_type=form&model=%s' % (self.id, self._name) qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=20, border=4, ) qr.add_data(base_url) qr.make(fit=True) img = qr.make_image() temp = BytesIO() img.save(temp, format="PNG") self.qr_image = base64.b64encode(temp.getvalue()) self.qr_in_report = True self.api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"] ["referencia"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]["description"]) return super(account_invoice, self).invoice_validate() else: errorMessage = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]) + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]) raise Warning(errorMessage) elif (tipo_documento_consultar == "FAC" or tipo_documento_consultar == "INV"): index = 0 total_venta = 0 for invoice in self: items = invoice.invoice_line_ids for item in items: tax_line = False for tax in item.invoice_line_tax_ids: tax_line = tax impuesto = tax_line.amount / 100 valor_venta = (item.price_unit * item.quantity) monto_afectacion_tributo = valor_venta * impuesto precio_unitario = (item.price_unit * impuesto) + item.price_unit if (str(int(tax_line.sunat_tributo)) == "1000"): sumatoria_igv += monto_afectacion_tributo sumatoria_igv_impuesto += impuesto total_venta_igv += valor_venta total_venta += total_venta_igv tipoAfectacionTributo = "10" if (str(int(tax_line.sunat_tributo)) == "2000"): sumatoria_isc += monto_afectacion_tributo sumatoria_isc_impuesto += impuesto total_venta_ics += valor_venta total_venta += total_venta_ics tipoAfectacionTributo = "01" # catalogo 8 if (str(int(tax_line.sunat_tributo)) == "9998"): sumatoria_inafecto += monto_afectacion_tributo sumatoria_inafecto_impuesto += impuesto total_venta_inafecto += valor_venta total_venta += total_venta_inafecto tipoAfectacionTributo = "30" if (str(int(tax_line.sunat_tributo)) == "9996"): sumatoria_gratuita += monto_afectacion_tributo sumatoria_gratuita_impuesto += impuesto total_venta_gratuita += valor_venta total_venta += total_venta_gratuita tipoAfectacionTributo = "21" if (str(int(tax_line.sunat_tributo)) == "9997"): sumatoria_exonerada += monto_afectacion_tributo sumatoria_exonerada_impuesto += impuesto total_venta_exonerada += valor_venta total_venta += total_venta_exonerada tipoAfectacionTributo = "20" if (str(int(tax_line.sunat_tributo)) == "9995"): sumatoria_exportacion += monto_afectacion_tributo sumatoria_exportacion_impuesto += impuesto total_venta_exportacion += valor_venta total_venta += total_venta_exportacion tipoAfectacionTributo = "40" if (str(int(tax_line.sunat_tributo)) == "9999"): sumatoria_other += monto_afectacion_tributo sumatoria_other_impuesto += impuesto total_venta_other += valor_venta total_venta += total_venta_other tipoAfectacionTributo = "10" invoice_item = { 'id': str(item.id), 'cantidad': str(item.quantity), 'descripcion': item.name, 'valorVenta': valor_venta, 'valorUnitario': item.price_unit, 'precioVentaUnitario': precio_unitario, 'tipoPrecioVentaUnitario': '01', #instalar en ficha de producto catalogo 16 "tributo": { "codigo": str(int(tax_line.sunat_tributo)), "porcentaje": tax_line.amount, #taxes.tax_id.amount, 'montoAfectacionTributo': monto_afectacion_tributo, 'tipoAfectacionTributo': tipoAfectacionTributo, # pendiente si es igv - catalogo 7. #pendiente si es isc - catalogo 8 para codigo = 2000 ISC }, 'unidadMedidaCantidad': "ZZ", } invoice_items.append(invoice_item) serieParts = str(invoice.number).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] currentDateTime = datetime.now() currentTime = currentDateTime.strftime("%H:%M:%S") #end for data = { 'serie': str(serieConsecutivoString), "numero": str(serieConsecutivo), "emisor": { "tipo": 6, "nro": invoice.company_id.sol_ruc, "nombre": invoice.company_id.name, "direccion": invoice.company_id.street, "ciudad": invoice.company_id.city, "departamento": invoice.company_id.state_id.name, "codigoPostal": invoice.company_id.zip, "codigoPais": invoice.company_id.country_id.code, "ubigeo": invoice.company_id.ubigeo }, "receptor": { "tipo": 6, "nro": invoice.partner_id.vat, "nombre": invoice.partner_id.name, "direccion": invoice.partner_id.street, }, "tributo": { 'IGV': { "total_venta": str(round(float(total_venta_igv), 2)), "impuesto": str(round(float(sumatoria_igv_impuesto), 2)), "sumatoria": str(round(float(sumatoria_igv), 2)) }, 'ISC': { "total_venta": str(round(float(total_venta_ics), 2)), "impuesto": str(round(float(sumatoria_isc_impuesto), 2)), "sumatoria": str(round(float(sumatoria_isc), 2)) }, 'inafecto': { "total_venta": str(round(float(total_venta_inafecto), 2)), "impuesto": str(round(float(sumatoria_inafecto_impuesto), 2)), "sumatoria": str(round(float(sumatoria_inafecto), 2)) }, 'exonerado': { "total_venta": str(round(float(total_venta_exonerada), 2)), "impuesto": str(round(float(sumatoria_exonerada_impuesto), 2)), "sumatoria": str(round(float(sumatoria_exonerada), 2)) }, 'exportacion': { "total_venta": str(round(float(total_venta_exportacion), 2)), "impuesto": str(round(float(sumatoria_exportacion_impuesto), 2)), "sumatoria": str(round(float(sumatoria_exportacion), 2)) }, 'other': { "total_venta": str(round(float(total_venta_other), 2)), "impuesto": str(round(float(sumatoria_other_impuesto), 2)), "sumatoria": str(round(float(sumatoria_other), 2)) }, }, "fechaEmision": str(invoice.date_invoice).replace("/", "-", 3), "fechaVencimiento": str(invoice.date_due).replace("/", "-", 3), "horaEmision": currentTime, 'totalVenta': total_venta, 'tipoMoneda': invoice.currency_id.name, 'items': invoice_items, 'sol': { 'usuario': invoice.company_id.sol_username, 'clave': invoice.company_id.sol_password }, 'licencia': "081OHTGAVHJZ4GOZJGJV" } with open('/home/rockscripts/Documents/data.json', 'w') as outfile: json.dump(data, outfile) #raise Warning("STOP") xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) SunatService.setXMLPath(xmlPath) SunatService.fileName = str( invoice.company_id.sol_ruc) + "-01-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(invoice.company_id.api_mode, "sendBill") sunatResponse = SunatService.processInvoice(data) #with open('/home/rockscripts/Documents/data1.json', 'w') as outfile: # json.dump(sunatResponse, outfile) if (sunatResponse["status"] == "OK"): # generate qr for invoices and tickets in pos base_url = request.env['ir.config_parameter'].get_param( 'web.base.url') base_url += '/web#id=%d&view_type=form&model=%s' % (self.id, self._name) qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=20, border=4, ) qr.add_data(base_url) qr.make(fit=True) img = qr.make_image() temp = BytesIO() img.save(temp, format="PNG") self.qr_image = base64.b64encode(temp.getvalue()) self.qr_in_report = True self.api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"] ["referencia"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]["description"]) return super(account_invoice, self).invoice_validate() else: errorMessage = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "DESCRIPCIÓN: " + str( sunatResponse["body"]) + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]) raise Warning(errorMessage) else: return super(account_invoice, self).invoice_validate()
def edocs_submit_invoice(self, **kw): #self.update_inv() #return None invoice_id = kw.get('invoice_id') query = "select number, company_id, unsigned_document, signed_document, response_document from account_invoice where id = " + str( invoice_id) request.cr.execute(query) invoice_fields = request.cr.dictfetchone() query = "select res_partner.vat, res_company.api_mode, res_company.sol_ruc, res_company.sol_username, res_company.sol_password, res_company.certs from res_company left join res_partner on res_partner.company_id = res_company.id where res_company.id = " + str( invoice_fields['company_id'] ) + " and res_partner.is_company = TRUE and res_company.partner_id = res_partner.id" request.cr.execute(query) company_fields = request.cr.dictfetchone() serieParts = str(invoice_fields["number"]).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] sunat_data = { "secuencia_consecutivo": serieConsecutivo, "numero": serieConsecutivo, "serie": serieConsecutivoString, "sunat_sol": { "ruc": company_fields["sol_ruc"], 'usuario': company_fields["sol_username"], 'clave': company_fields["sol_password"] }, "xml": { #"signed":base64.b64decode((invoice_fields["signed_document"])) }, "licencia": "081OHTGAVHJZ4GOZJGJV" } xmlPath = str(os.path.dirname(os.path.abspath(__file__))).replace( "controllers", "models") + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) if ("F0" in serieConsecutivoString): SunatService.fileName = str(company_fields["vat"]) + "-01-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.documentType = str("01") if ("BF" in serieConsecutivoString): SunatService.fileName = str(company_fields["vat"]) + "-03-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.documentType = str("03") if ("FD" in serieConsecutivoString): SunatService.fileName = str(company_fields["vat"]) + "-08-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.documentType = str("08") if ("FC" in serieConsecutivoString): SunatService.fileName = str(company_fields["vat"]) + "-07-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.documentType = str("07") SunatService.initSunatAPI(company_fields["api_mode"], "sendBill") sunatResponse = SunatService.processInvoiceFromSignedXML(sunat_data) try: if ('status' in sunatResponse): if (sunatResponse["status"] == "OK"): # save xml documents steps for reference in edocs response_document_filename = str("R_") + "-01-" + str( serieConsecutivoString) + "-" + str( serieConsecutivo) + str(".XML") api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"]["referencia"]).replace( "'", '"') + "\n" + " " + str( sunatResponse["body"] ["description"]).replace("'", '"') query = "update account_invoice set sunat_request_status = 'OK', api_message = '" + str( api_message ) + "', response_document_filename = '" + str( response_document_filename ) + "', sunat_request_type = 'Manual' where id = " + str( invoice_id) request.cr.execute(query) response = { "sunat_request_status": sunatResponse["status"], "api_message": api_message } else: api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + " " + str( sunatResponse["body"]).replace( "'", '"') + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]).replace("'", '"') query = "update account_invoice set sunat_request_status = 'FAIL', api_message = '" + str( api_message ) + "', sunat_request_type = 'Manual' where id = " + str( invoice_id) request.cr.execute(query) response = { "sunat_request_status": sunatResponse["status"], "api_message": api_message } else: sunatResponse["status"] = "FAIL" api_message = "Servidor no disponible temporalmente." query = "update account_invoice set sunat_request_status = 'FAIL', api_message = '" + str( api_message ) + "', sunat_request_type = 'Manual' where id = " + str( invoice_id) request.cr.execute(query) response = { "sunat_request_status": sunatResponse["status"], "api_message": api_message } return response except Exception as e: exc_traceback = sys.exc_info()
def eguide_submit_single(self, **kw): stock_picking_id = kw.get('stock_picking_id') query = "select name, company_id, unsigned_document, signed_document, response_document from stock_picking where id = " + str( stock_picking_id) request.cr.execute(query) stock_picking = request.cr.dictfetchone() query = "select res_partner.vat, res_company.api_mode, res_company.sol_ruc, res_company.sol_username, res_company.sol_password, res_company.certs from res_company left join res_partner on res_partner.company_id = res_company.id where res_company.id = " + str( stock_picking['company_id'] ) + " and res_partner.is_company = TRUE and res_company.partner_id = res_partner.id" request.cr.execute(query) company_fields = request.cr.dictfetchone() serieParts = str(stock_picking["name"]).split("-") serieConsecutivoString = serieParts[0] serieConsecutivo = serieParts[1] sunat_data = { "secuencia_consecutivo": serieConsecutivo, "sunat_sol": { "ruc": company_fields["sol_ruc"], 'usuario': company_fields["sol_username"], 'clave': company_fields["sol_password"] }, "xml": { #"signed":base64.b64decode((stock_picking["signed_document"])) }, "licencia": "081OHTGAVHJZ4GOZJGJV" } xmlPath = str(os.path.dirname(os.path.abspath(__file__))).replace( "controllers", "models") + '/xml' SunatService = Service() SunatService.setXMLPath(xmlPath) if ("T001" in serieConsecutivoString): SunatService.fileName = str(company_fields["vat"]) + "-09-" + str( serieConsecutivoString) + "-" + str(serieConsecutivo) SunatService.initSunatAPI(company_fields["api_mode"], "sendBill") sunatResponse = SunatService.processDeliveryGuideFromSignedXML( sunat_data) if ('status' in sunatResponse): if (sunatResponse["status"] == "OK"): # save xml documents steps for reference in edocs response_document_filename = str("R_") + "-09-" + str( serieConsecutivoString) + "-" + str( serieConsecutivo) + str(".XML") api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + "REFERENCIA: " + str( sunatResponse["body"]["referencia"]).replace( "'", '"') + "\n" + " " + str( sunatResponse["body"]["description"]).replace( "'", '"') query = "update stock_picking set sunat_request_status = 'OK', api_message = '" + str( api_message) + "', response_document_filename = '" + str( response_document_filename ) + "', sunat_request_type = 'Manual' where id = " + str( stock_picking_id) request.cr.execute(query) #if(serieConsecutivo=="00000008"): # with open('/home/rockscripts/Documents/data.json', 'w') as outfile: # json.dump(query, outfile) else: api_message = "ESTADO: " + str( sunatResponse["status"]) + "\n" + " " + str( sunatResponse["body"]).replace( "'", '"') + "\n" + "CÓDIGO ERROR: " + str( sunatResponse["code"]).replace("'", '"') query = "update stock_picking set sunat_request_status = 'FAIL', api_message = '" + str( api_message ) + "', sunat_request_type = 'Manual' where id = " + str( stock_picking_id) request.cr.execute(query) #if(serieConsecutivo): # with open('/home/rockscripts/Documents/data.json', 'w') as outfile: # json.dump(serieConsecutivo, outfile) else: sunatResponse["status"] = "FAIL" api_message = "Servidor no disponible temporalmente." query = "update stock_picking set sunat_request_status = 'FAIL', api_message = '" + str( api_message ) + "', sunat_request_type = 'Manual' where id = " + str( stock_picking_id) request.cr.execute(query) response = { "sunat_request_status": sunatResponse["status"], "api_message": api_message } return response
def get_ruc(self, **kw): doc_num = kw.get('doc_num') doc_type = kw.get('doc_type') xmlPath = os.path.dirname(os.path.abspath(__file__)) + '/xml' xmlPath = xmlPath.replace("controllers", "models") response = {'status': "El documento no fue encontrado."} try: if (doc_num != ""): SunatService = Service() SunatService.setXMLPath(xmlPath) response_service = SunatService.consultRUC_Pydevs( doc_type, doc_num) if len(response_service['data']) > 0: if (int(doc_type) == 6): query = "select id, name, code from res_country_state where length(code) = 6 and country_id = " + str( 173) + " and name like'%" + str( response_service["data"]['distrito']) + "%'" request.cr.execute(query) district = request.cr.dictfetchone() ubigeo = str("") if (district): ubigeo = district["code"] nombre = str(response_service["data"] ['nombre']).capitalize().replace( '"', '').strip() nombre_comercial = str( response_service["data"] ['nombre_comercial']).capitalize().replace( '"', '').strip() nombre_comercial_tmp = nombre_comercial nombre_comercial = nombre + nombre_comercial if nombre_comercial != "-" else "" name = str(nombre) if str(nombre_comercial_tmp) == str( "-") else str(nombre) + str(" -- ") + str( nombre_comercial_tmp) response = { 'status': "OK", 'nmro': doc_num, 'address': str(response_service["data"] ['domicilio_fiscal']).capitalize(), 'name': name, 'tipo_contribuyente': response_service["data"]['tipo_contribuyente'], 'nombre_comercial': nombre_comercial, 'sistema_emision_comprobante': str(response_service["data"] ['sistema_emision_comprobante']).capitalize(), 'sistema_contabilidad': str(response_service["data"] ['sistema_contabilidad']).capitalize(), 'actividad_economica': str(response_service["data"] ['actividad_economica']).capitalize(), 'estado_contribuyente': str(response_service["data"] ['estado_contribuyente']).capitalize(), 'condicion_contribuyente': str(response_service["data"] ['condicion_contribuyente']).capitalize(), 'distrito': response_service["data"]['distrito'], 'provincia': response_service["data"]['provincia'], 'departamento': response_service["data"]['departamento'], 'ubigeo': ubigeo } if (int(doc_type) == 1): response = { 'status': "OK", 'nmro': doc_num, 'name': str( str(response_service["data"]['nombres']) + str(" ") + str(response_service["data"]['ape_paterno']) + str(" ") + str(response_service["data"]['ape_materno'])). capitalize() } except Exception as e: exc_traceback = sys.exc_info() #with open('/home/rockscripts/Documentos/log_.js', 'w') as outfile: # json.dump(getattr(e, 'message', repr(e))+" ON LINE "+format(sys.exc_info()[-1].tb_lineno), outfile) return {'status': "FAIL"} return response