package factura import ( "errors" "fmt" "net/http" "strconv" "github.com/gin-gonic/gin" "gorm.io/gorm" dto_directors "repuestera_back/dto/Builders/Directors" r "repuestera_back/repositorios" "repuestera_back/services" ) // EnviarEmailComprobante envía por email el comprobante de venta al cliente // de la factura indicada. Requiere que el cliente tenga email registrado. func EnviarEmailComprobante(c *gin.Context) { id, err := strconv.ParseUint(c.Param("id"), 10, 64) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"}) return } repo := r.ObtenerRepositorios(c) factura, err := repo.Factura.ObtenerConRelaciones(uint(id)) if errors.Is(err, gorm.ErrRecordNotFound) { c.JSON(http.StatusNotFound, gin.H{"error": "factura no encontrada"}) return } if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } if factura.Cliente.Email == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "el cliente no tiene email registrado"}) return } // Nombres reales de repuestos desde la base de datos. nombres := make(map[uint64]string, len(factura.Detalles)) for _, d := range factura.Detalles { repuesto, err := repo.Repuesto.ObtenerPorID(uint(d.RepuestoID)) if err == nil && repuesto != nil && *repuesto != nil { nombres[d.RepuestoID] = (*repuesto).Nombre } else { nombres[d.RepuestoID] = fmt.Sprintf("Repuesto %d", d.RepuestoID) } } // Pagos realizados de esta factura. pagos, err := repo.Pago.ListarPorFactura(factura.ID) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta( factura, nombres, pagos, factura.Cliente.Email, ) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } userID := c.GetUint("userID") if !services.EnviarEmail(*mensaje, userID) { c.JSON(http.StatusInternalServerError, gin.H{"error": "no se pudo enviar el email"}) return } c.JSON(http.StatusOK, gin.H{"mensaje": "email enviado correctamente"}) }