Я сделал новый модуль, который помещает ошибки в соответствующий счет, но вот моя проблема.
Я хочу запустить оповещение с «UserError», которое сообщает мне, что счет не был сертифицирован, но когда я использую «raise UserError», все транзакции транзакции, вызвавшей оповещение, отменяются, поэтому ошибки не отображаются в представлении счета.
С другой стороны, если я не использую «поднять UserError», размещаются ошибки, но счет-фактура в Odoo продолжает работать и публикуется, что не подходит для моей бизнес-логики.
Это представление ошибок

Но счет уже опубликован, а это неверно

Я хотел бы остановить поток Odoo и предотвратить публикацию счета и установку ошибок в счете.
def certificar_documento(self, url, headers, tree):
certificar_xml = ET.tostring(tree.getroot(), encoding="UTF-8", method="xml")
respuesta = requests.post(url, headers=headers, data=certificar_xml)
respuesta_json = respuesta.json()
return certificar_xml, respuesta_json
def establecer_error(self, json):
errores = self.env["errores.fel"]
for error in json["descripcion_errores"]:
errores.create(
{
"mensaje_error": error.get("mensaje_error"),
"fecha_hora_error": datetime.now(),
"account_move_factuas_ids": self.id,
}
)
def facturacion_electronica(self):
url = "https://certificador.feel.com.gt/fel/pr ... ion/v2/xml"
headers = {
"UsuarioFirma": f"{self.company_id.usuario}",
"LlaveFirma": f"{self.company_id.llave_firma}",
"UsuarioApi": f"{self.company_id.usuario}",
"LlaveApi": f"{self.company_id.llave_api}",
"Content-Type": "application/xml",
}
for factura in self:
if (
factura.tipo_factura == "none"
and factura.move_type != "out_refund"
and factura.move_type != "in_invoice"
and not factura.debit_origin_id
):
raise UserError("Debe ingresar el tipo de documento que va a emitir")
elif factura.debit_origin_id:
tree = NDEB.generar_nota_debito(self, factura)
elif factura.move_type == "out_refund":
tree = NCRE.generar_nota_credito(self, factura)
elif factura.tipo_factura == "fact" or factura.tipo_factura == "fact_cambiaria":
tree = FACT.generar_factura(self, factura)
elif factura.factura_especial:
tree = FESP.generar_especial(self, factura)
else:
continue
certificar_xml, respuesta_json = self.certificar_documento(url, headers, tree)
if respuesta_json["resultado"] == False:
# mensajes_error = "\n".join(error["mensaje_error"] for error in respuesta_json["descripcion_errores"])
# raise ValidationError(f"La factura no se certificó\n{mensajes_error}")
self.establecer_error(respuesta_json)
return
else:
factura.numero_autorizacion = respuesta_json["uuid"]
factura.serie = respuesta_json["serie"]
factura.numero_dte = respuesta_json["numero"]
factura.xml_generado = certificar_xml
factura.fecha_emision = datetime.now()
fecha_hora_certificado = respuesta_json["fecha"].split("T")
hora_certificado = fecha_hora_certificado[1].split("-")
fecha_hora_str = f"{fecha_hora_certificado[0]} {hora_certificado[0]}"
fecha_hora_time = datetime.strptime(fecha_hora_str, "%Y-%m-%d %H:%M:%S")
fecha_hora_modificada = fecha_hora_time + timedelta(hours=6)
factura.fecha_certificacion = fecha_hora_modificada
factura.xml_certificado = respuesta_json["xml_certificado"]
factura.certificada = True
var_numero_autorizacion = respuesta_json["uuid"]
var_serie = respuesta_json["serie"]
var_numero_dte = respuesta_json["numero"]
var_fecha = date.today()
link_factura = (
f"https://report.feel.com.gt/ingfacerepor ... torizacion}"
)
mensaje = f"""
Datos FEL de la factura
- Número de autorización: {var_numero_autorizacion}
- Serie: {var_serie}
- Número DTE: {var_numero_dte}
- Fecha: {var_fecha}
"""
factura.message_post(
body=mensaje,
body_is_html=True,
author_id=self.env.ref("base.partner_root").id,
subject="Factura certificada correctamente",
message_type="comment",
subtype_xmlid="mail.mt_comment",
)
Подробнее здесь: https://stackoverflow.com/questions/787 ... -odoo-flow