Files
Repuestera/back/controllers/stock/ExportarReporte.go
T

51 lines
1.3 KiB
Go

package stock
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"repuestera_back/strategy/reporte"
"repuestera_back/utils"
)
func ExportarReporte(c *gin.Context) {
formato := strings.ToLower(strings.TrimSpace(c.DefaultQuery("formato", "csv")))
if formato == "" {
formato = "csv"
}
if _, autenticado := utils.PermisosDelContexto(c); autenticado &&
!utils.UsuarioTienePermiso(c, 14) {
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para generar reportes de stock"})
return
}
datos, err := obtenerDatosReporte(c)
if err != nil {
if strings.HasPrefix(err.Error(), "validación:") {
c.JSON(http.StatusBadRequest, gin.H{"error": strings.TrimPrefix(err.Error(), "validación: ")})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
exportador, err := reporte.NuevoExportador(formato)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
timestamp := time.Now().Format("20060102-1504")
nombreArchivo := fmt.Sprintf("reporte-stock-%s.%s", timestamp, formato)
if err := exportador.Exportar(c.Writer, datos.movimientos, datos.resumen, nombreArchivo); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se pudo generar el archivo"})
return
}
}