Private
Public Access
commit parcial con la parte de email y comprobante correjido
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
fcf16df5d3
commit
320cc9c241
13 files changed
+813
-36
No files matched your search
@@ -0,0 +1,75 @@
|
||||
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"})
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto_facturas "repuestera_back/dto/Facturas"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// ObtenerComprobante devuelve el detalle de una factura junto con sus pagos,
|
||||
// listo para renderizar el comprobante de venta.
|
||||
func ObtenerComprobante(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
|
||||
}
|
||||
|
||||
factura, err := r.ObtenerRepositorios(c).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
|
||||
}
|
||||
|
||||
pagos, err := r.ObtenerRepositorios(c).Pago.ListarPorFactura(factura.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
respuesta, err := dto_directors.NewFacturaDirector().DesdeFactura(factura)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
pagosResumen := make([]dto_facturas.PagoResumen, 0, len(pagos))
|
||||
for _, p := range pagos {
|
||||
forma := ""
|
||||
if p.FormaDePago.ID != 0 {
|
||||
forma = p.FormaDePago.Descripcion
|
||||
}
|
||||
pagosResumen = append(pagosResumen, dto_facturas.PagoResumen{
|
||||
ID: p.ID,
|
||||
FacturaID: p.FacturaID,
|
||||
FormaDePagoID: p.FormaDePagoID,
|
||||
FormaDePago: forma,
|
||||
Importe: p.Importe,
|
||||
Fecha: p.Fecha,
|
||||
Observacion: p.Observacion,
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto_facturas.ComprobanteResponse{
|
||||
FacturaResponse: respuesta,
|
||||
Pagos: pagosResumen,
|
||||
})
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
type ComprobanteVentaEmailBuilder struct {
|
||||
factura *models.Factura
|
||||
nombres map[uint64]string
|
||||
pagos []models.Pago
|
||||
destinatario string
|
||||
err error
|
||||
}
|
||||
@@ -40,6 +41,11 @@ func (b *ComprobanteVentaEmailBuilder) ConNombresRepuestos(nombres map[uint64]st
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ComprobanteVentaEmailBuilder) ConPagos(pagos []models.Pago) *ComprobanteVentaEmailBuilder {
|
||||
b.pagos = pagos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ComprobanteVentaEmailBuilder) ConDestinatario(destinatario string) *ComprobanteVentaEmailBuilder {
|
||||
b.destinatario = strings.TrimSpace(destinatario)
|
||||
if b.destinatario == "" {
|
||||
@@ -58,7 +64,7 @@ func (b *ComprobanteVentaEmailBuilder) Build() (*dto_email.MensajeEmail, error)
|
||||
|
||||
return NewMensajeEmailBuilder().
|
||||
ConTitulo("Comprobante de venta " + b.factura.Numero).
|
||||
ConDescripcion(htmlComprobanteVenta(b.factura, b.nombres)).
|
||||
ConDescripcion(htmlComprobanteVenta(b.factura, b.nombres, b.pagos)).
|
||||
ConItems([]string{}).
|
||||
ConDestinatarios([]string{b.destinatario}).
|
||||
Build()
|
||||
@@ -75,7 +81,7 @@ const (
|
||||
// htmlComprobanteVenta genera el cuerpo HTML del comprobante. Usa tablas y
|
||||
// estilos inline porque los clientes de correo suelen ignorar las hojas de
|
||||
// estilo.
|
||||
func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) string {
|
||||
func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string, pagos []models.Pago) string {
|
||||
var b strings.Builder
|
||||
|
||||
b.WriteString(`<div style="max-width:640px;margin:0 auto;font-family:Arial,Helvetica,sans-serif;color:` + comprobanteColorText + `;">`)
|
||||
@@ -112,13 +118,16 @@ func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) st
|
||||
b.WriteString(`<tr><td colspan="4" style="padding:12px 8px;color:` + comprobanteColorMuted + `;">Sin detalles</td></tr>`)
|
||||
}
|
||||
for _, detalle := range factura.Detalles {
|
||||
nombre := fmt.Sprintf("Repuesto %d", detalle.RepuestoID)
|
||||
nombre := detalle.RepuestoID // placeholder, se reemplaza abajo
|
||||
_ = nombre
|
||||
nombreRepuesto := fmt.Sprintf("Repuesto %d", detalle.RepuestoID)
|
||||
if n := strings.TrimSpace(nombres[detalle.RepuestoID]); n != "" {
|
||||
nombre = n
|
||||
nombreRepuesto = n
|
||||
}
|
||||
fmt.Fprintf(&b,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%.3f</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;font-weight:600;">%s</td></tr>`,
|
||||
comprobanteColorBorder, htmlutil.EscapeString(nombre), detalle.Cantidad,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;font-weight:600;">%s</td></tr>`,
|
||||
comprobanteColorBorder, htmlutil.EscapeString(nombreRepuesto),
|
||||
formatoCantidad(detalle.Cantidad),
|
||||
montoComprobante(detalle.PrecioUnitario), montoComprobante(detalle.Subtotal),
|
||||
)
|
||||
}
|
||||
@@ -143,6 +152,34 @@ func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) st
|
||||
}
|
||||
b.WriteString(`</table>`)
|
||||
|
||||
// Sección de pagos realizados
|
||||
if len(pagos) > 0 {
|
||||
b.WriteString(`<h2 style="margin:24px 0 10px;font-size:14px;letter-spacing:1px;text-transform:uppercase;color:` + comprobanteColorMuted + `;">Pagos realizados</h2>`)
|
||||
b.WriteString(`<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;font-size:13px;">`)
|
||||
b.WriteString(`<thead><tr style="background:` + comprobanteColorSoft + `;color:` + comprobanteColorMuted + `;text-align:left;">`)
|
||||
b.WriteString(`<th style="padding:10px 8px;">Fecha</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Forma de pago</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Importe</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Observación</th>`)
|
||||
b.WriteString(`</tr></thead><tbody>`)
|
||||
for _, pago := range pagos {
|
||||
forma := "-"
|
||||
if pago.FormaDePago.ID != 0 {
|
||||
forma = pago.FormaDePago.Descripcion
|
||||
}
|
||||
fechaStr := pago.Fecha.Format("02/01/2006 15:04")
|
||||
obs := pago.Observacion
|
||||
if obs == "" {
|
||||
obs = "-"
|
||||
}
|
||||
fmt.Fprintf(&b,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;font-weight:600;">%s</td><td style="padding:10px 8px;color:%s;">%s</td></tr>`,
|
||||
comprobanteColorBorder, fechaStr, htmlutil.EscapeString(forma), montoComprobante(pago.Importe), comprobanteColorMuted, htmlutil.EscapeString(obs),
|
||||
)
|
||||
}
|
||||
b.WriteString(`</tbody></table>`)
|
||||
}
|
||||
|
||||
if observacion := strings.TrimSpace(factura.Observacion); observacion != "" {
|
||||
fmt.Fprintf(&b, `<p style="margin:20px 0 0;font-size:12px;color:%s;"><strong>Observación:</strong> %s</p>`, comprobanteColorMuted, htmlutil.EscapeString(observacion))
|
||||
}
|
||||
@@ -153,6 +190,22 @@ func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) st
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// formatoCantidad devuelve la cantidad como número entero si no tiene decimales,
|
||||
// o con coma decimal si los tiene (formato AR).
|
||||
func formatoCantidad(cantidad float64) string {
|
||||
if cantidad == float64(int64(cantidad)) {
|
||||
return strconv.FormatInt(int64(cantidad), 10)
|
||||
}
|
||||
// Tiene decimales: mostrar con coma
|
||||
centavos := int64(math.Round(cantidad * 100))
|
||||
entero := centavos / 100
|
||||
dec := centavos % 100
|
||||
if dec == 0 {
|
||||
return strconv.FormatInt(entero, 10)
|
||||
}
|
||||
return fmt.Sprintf("%d,%02d", entero, dec)
|
||||
}
|
||||
|
||||
// montoComprobante formatea importes con separador de miles y coma decimal.
|
||||
func montoComprobante(valor float64) string {
|
||||
negativo := valor < 0
|
||||
|
||||
@@ -20,11 +20,13 @@ func NewEmailDirector() *EmailDirector {
|
||||
func (d *EmailDirector) ComprobanteVenta(
|
||||
factura *models.Factura,
|
||||
nombresRepuestos map[uint64]string,
|
||||
pagos []models.Pago,
|
||||
destinatario string,
|
||||
) (*dto_email.MensajeEmail, error) {
|
||||
return builders.NewComprobanteVentaEmailBuilder().
|
||||
ConFactura(factura).
|
||||
ConNombresRepuestos(nombresRepuestos).
|
||||
ConPagos(pagos).
|
||||
ConDestinatario(destinatario).
|
||||
Build()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package dto
|
||||
|
||||
// ComprobanteResponse es la representación pública de una factura para
|
||||
// visualizar el comprobante. Incluye todos los datos de FacturaResponse
|
||||
// más la lista de pagos realizados.
|
||||
type ComprobanteResponse struct {
|
||||
*FacturaResponse
|
||||
Pagos []PagoResumen `json:"pagos"`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// PagoResumen es la representación ligera de un pago de factura,
|
||||
// usada para mostrar el historial de pagos en el comprobante.
|
||||
type PagoResumen struct {
|
||||
ID uint `json:"id"`
|
||||
FacturaID uint `json:"facturaId,omitempty"`
|
||||
FormaDePagoID uint `json:"formaDePagoId,omitempty"`
|
||||
FormaDePago string `json:"formaDePago,omitempty"`
|
||||
Importe float64 `json:"importe"`
|
||||
Fecha time.Time `json:"fecha"`
|
||||
Observacion string `json:"observacion,omitempty"`
|
||||
}
|
||||
@@ -38,9 +38,11 @@ func (r *repositorioPago) Registrar(tx *gorm.DB, pago *models.Pago) error {
|
||||
return tx.Create(pago).Error
|
||||
}
|
||||
|
||||
// ListarPorFactura devuelve los pagos de una factura, con la forma de pago
|
||||
// precargada para poder mostrar su descripción.
|
||||
func (r *repositorioPago) ListarPorFactura(facturaID uint) ([]models.Pago, error) {
|
||||
var pagos []models.Pago
|
||||
if err := r.db.Where("factura_id = ?", facturaID).Find(&pagos).Error; err != nil {
|
||||
if err := r.db.Where("facturaId = ?", facturaID).Preload("FormaDePago").Find(&pagos).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pagos, nil
|
||||
@@ -48,7 +50,7 @@ func (r *repositorioPago) ListarPorFactura(facturaID uint) ([]models.Pago, error
|
||||
|
||||
func (r *repositorioPago) SumarPorFactura(facturaID uint) (float64, error) {
|
||||
var total float64
|
||||
if err := r.db.Model(&models.Pago{}).Where("factura_id = ?", facturaID).Select("COALESCE(SUM(importe),0)").Scan(&total).Error; err != nil {
|
||||
if err := r.db.Model(&models.Pago{}).Where("facturaId = ?", facturaID).Select("COALESCE(SUM(importe),0)").Scan(&total).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return total, nil
|
||||
|
||||
@@ -15,6 +15,7 @@ func FacturaRoute(r *gin.Engine) {
|
||||
{
|
||||
grupo.GET("/", factura.ObtenerFacturas)
|
||||
grupo.GET("/:id", factura.ObtenerFactura)
|
||||
grupo.GET("/:id/comprobante", factura.ObtenerComprobante)
|
||||
}
|
||||
|
||||
// Escritura: solo gestión de ventas. Se agregan en CU-02, CU-05, CU-06,
|
||||
@@ -23,5 +24,6 @@ func FacturaRoute(r *gin.Engine) {
|
||||
escritura.Use(middleware.AuthMiddleware(15))
|
||||
{
|
||||
escritura.POST("/", factura.CrearFactura)
|
||||
escritura.POST("/:id/enviar-email", factura.EnviarEmailComprobante)
|
||||
}
|
||||
}
|
||||
@@ -270,7 +270,7 @@ func CrearFactura(
|
||||
// Email post-commit: un fallo no revierte la factura.
|
||||
facturaCreada.Cliente = *cliente
|
||||
if entrada.EnviarEmail && cliente.Email != "" {
|
||||
mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta(facturaCreada, nombresRepuestos, cliente.Email)
|
||||
mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta(facturaCreada, nombresRepuestos, nil, cliente.Email)
|
||||
if err != nil {
|
||||
applog.Printf("facturas: no se pudo construir el email de la factura %s: %v", facturaCreada.Numero, err)
|
||||
} else if EnviarEmail(*mensaje, usuarioID) {
|
||||
|
||||
Reference in new issue
Block a user