Private
Public Access
hecha funcionalidad de reportes y exportacion de reportes
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
61baaf14f8
commit
298f3c699c
7 files changed
+338
-7
No files matched your search
@@ -0,0 +1,50 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package reporte
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// ExportadorCSV exporta el reporte en formato CSV.
|
||||
type ExportadorCSV struct{}
|
||||
|
||||
func (e *ExportadorCSV) Exportar(w http.ResponseWriter, movimientos []models.MovimientoStock, resumen []dto.ResumenMovimientoResponse, nombreArchivo string) error {
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", nombreArchivo))
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Write([]byte{0xEF, 0xBB, 0xBF})
|
||||
|
||||
writer := csv.NewWriter(w)
|
||||
if err := writer.Write([]string{
|
||||
"ID", "Fecha", "Tipo", "Repuesto", "RepuestoID", "AlmacenID",
|
||||
"Cantidad", "SaldoAnterior", "SaldoPosterior", "ReferenciaTipo",
|
||||
"ReferenciaID", "UsuarioID", "Observacion",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range movimientos {
|
||||
nombreRepuesto := ""
|
||||
if m.Repuesto.Nombre != "" {
|
||||
nombreRepuesto = m.Repuesto.Nombre
|
||||
}
|
||||
if err := writer.Write([]string{
|
||||
fmt.Sprintf("%d", m.ID),
|
||||
m.Fecha.Format("2006-01-02 15:04:05"),
|
||||
string(m.Tipo),
|
||||
nombreRepuesto,
|
||||
fmt.Sprintf("%d", m.RepuestoID),
|
||||
fmt.Sprintf("%d", m.AlmacenID),
|
||||
fmt.Sprintf("%g", m.Cantidad),
|
||||
fmt.Sprintf("%g", m.SaldoAnterior),
|
||||
fmt.Sprintf("%g", m.SaldoPosterior),
|
||||
m.ReferenciaTipo,
|
||||
fmt.Sprintf("%d", m.ReferenciaID),
|
||||
fmt.Sprintf("%d", m.UsuarioID),
|
||||
m.Observacion,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
return writer.Error()
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package reporte
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// ExportadorXLSX exporta el reporte en formato XLSX.
|
||||
type ExportadorXLSX struct{}
|
||||
|
||||
func (e *ExportadorXLSX) Exportar(w http.ResponseWriter, movimientos []models.MovimientoStock, resumen []dto.ResumenMovimientoResponse, nombreArchivo string) error {
|
||||
archivo := excelize.NewFile()
|
||||
hoja := "Movimientos"
|
||||
archivo.SetSheetName("Sheet1", hoja)
|
||||
|
||||
encabezados := []string{
|
||||
"ID", "Fecha", "Tipo", "Repuesto", "RepuestoID", "AlmacenID",
|
||||
"Cantidad", "SaldoAnterior", "SaldoPosterior", "ReferenciaTipo",
|
||||
"ReferenciaID", "UsuarioID", "Observacion",
|
||||
}
|
||||
for i, h := range encabezados {
|
||||
celda, _ := excelize.CoordinatesToCellName(i+1, 1)
|
||||
archivo.SetCellValue(hoja, celda, h)
|
||||
}
|
||||
|
||||
for idx, m := range movimientos {
|
||||
fila := idx + 2
|
||||
valores := []interface{}{
|
||||
m.ID,
|
||||
m.Fecha.Format("2006-01-02 15:04:05"),
|
||||
string(m.Tipo),
|
||||
m.Repuesto.Nombre,
|
||||
m.RepuestoID,
|
||||
m.AlmacenID,
|
||||
m.Cantidad,
|
||||
m.SaldoAnterior,
|
||||
m.SaldoPosterior,
|
||||
m.ReferenciaTipo,
|
||||
m.ReferenciaID,
|
||||
m.UsuarioID,
|
||||
m.Observacion,
|
||||
}
|
||||
for i, v := range valores {
|
||||
celda, _ := excelize.CoordinatesToCellName(i+1, fila)
|
||||
archivo.SetCellValue(hoja, celda, v)
|
||||
}
|
||||
}
|
||||
|
||||
hojaResumen := "Resumen"
|
||||
archivo.NewSheet(hojaResumen)
|
||||
archivo.SetCellValue(hojaResumen, "A1", "Tipo")
|
||||
archivo.SetCellValue(hojaResumen, "B1", "Cantidad")
|
||||
for idx, r := range resumen {
|
||||
fila := idx + 2
|
||||
archivo.SetCellValue(hojaResumen, fmt.Sprintf("A%d", fila), string(r.Tipo))
|
||||
archivo.SetCellValue(hojaResumen, fmt.Sprintf("B%d", fila), r.Cantidad)
|
||||
}
|
||||
|
||||
buffer, err := archivo.WriteToBuffer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", nombreArchivo))
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = w.Write(buffer.Bytes())
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package reporte
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// ExportadorReporte define la estrategia de exportación de un reporte.
|
||||
type ExportadorReporte interface {
|
||||
Exportar(w http.ResponseWriter, movimientos []models.MovimientoStock, resumen []dto.ResumenMovimientoResponse, nombreArchivo string) error
|
||||
}
|
||||
|
||||
// NuevoExportador devuelve la estrategia correspondiente al formato indicado.
|
||||
func NuevoExportador(formato string) (ExportadorReporte, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(formato)) {
|
||||
case "csv":
|
||||
return &ExportadorCSV{}, nil
|
||||
case "xlsx":
|
||||
return &ExportadorXLSX{}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("formato inválido: use csv o xlsx")
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
#+begin_src plantuml :file ../imagenes/d_pat_decorator_stock_reporte.svg
|
||||
|
||||
@startuml DecoratorMovimientoQuery
|
||||
skinparam classAttributeIconSize 0
|
||||
skinparam backgroundColor #FFFFFF
|
||||
@@ -115,3 +114,6 @@ end note
|
||||
|
||||
@enduml
|
||||
#+end_src
|
||||
|
||||
#+RESULTS:
|
||||
[[file:../imagenes/d_pat_decorator_stock_reporte.svg]]
|
||||
@@ -0,0 +1,62 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function exportarReporteStock(
|
||||
formato: 'csv' | 'xlsx',
|
||||
filtros?: {
|
||||
repuestoId?: number;
|
||||
almacenId?: number;
|
||||
tipo?: string;
|
||||
desde?: string;
|
||||
hasta?: string;
|
||||
pagina?: number;
|
||||
porPagina?: number;
|
||||
}
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.set('formato', formato);
|
||||
if (filtros?.repuestoId) params.set('repuestoId', String(filtros.repuestoId));
|
||||
if (filtros?.almacenId) params.set('almacenId', String(filtros.almacenId));
|
||||
if (filtros?.tipo) params.set('tipo', filtros.tipo);
|
||||
if (filtros?.desde) params.set('desde', filtros.desde);
|
||||
if (filtros?.hasta) params.set('hasta', filtros.hasta);
|
||||
if (filtros?.pagina) params.set('pagina', String(filtros.pagina));
|
||||
if (filtros?.porPagina) params.set('porPagina', String(filtros.porPagina));
|
||||
|
||||
const res = await fetch(`${API_URL}/stock/reportes/export?${params.toString()}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${getToken()}`
|
||||
}
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
let mensaje = 'No se pudo exportar el reporte';
|
||||
try {
|
||||
const data = await res.json();
|
||||
if (data?.error) mensaje = data.error;
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return mensaje;
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
const disposition = res.headers.get('Content-Disposition') || '';
|
||||
const match = disposition.match(/filename="?([^"]+)"?/);
|
||||
const filename = match?.[1] ?? `reporte-stock.${formato}`;
|
||||
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
return null;
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,14 @@
|
||||
SelectItem
|
||||
} from 'carbon-components-svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { exportarReporteStock } from '$lib/hooks/stock/exportarReporteStock';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
let error = $state('');
|
||||
let exportError = $state('');
|
||||
let exportando = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (data.error) error = data.error;
|
||||
});
|
||||
@@ -24,6 +28,7 @@
|
||||
let resumen = $derived(Array.isArray(reporte.resumen) ? reporte.resumen : []);
|
||||
|
||||
let filtros = $state({
|
||||
repuestoId: 0,
|
||||
almacenId: 0,
|
||||
tipo: '',
|
||||
desde: '',
|
||||
@@ -31,6 +36,7 @@
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
filtros.repuestoId = data.filtros?.repuestoId ?? 0;
|
||||
filtros.almacenId = data.filtros?.almacenId ?? 0;
|
||||
filtros.tipo = data.filtros?.tipo ?? '';
|
||||
filtros.desde = data.filtros?.desde ?? '';
|
||||
@@ -42,22 +48,25 @@
|
||||
{ key: 'tipo', value: 'Tipo' },
|
||||
{ key: 'repuesto', value: 'Repuesto' },
|
||||
{ key: 'almacen', value: 'Almacén' },
|
||||
{ key: 'cantidad', value: 'Cantidad' }
|
||||
{ key: 'cantidad', value: 'Cantidad' },
|
||||
{ key: 'saldo', value: 'Saldo posterior' }
|
||||
];
|
||||
|
||||
const rows = $derived(
|
||||
movimientos.map((m: any, i: number) => ({
|
||||
id: m.id ?? i,
|
||||
fecha: m.fecha,
|
||||
fecha: m.fecha ? new Date(m.fecha).toLocaleString() : '',
|
||||
tipo: m.tipo,
|
||||
repuesto: m.repuesto?.nombre ?? m.repuestoId,
|
||||
almacen: m.almacenId,
|
||||
cantidad: m.cantidad
|
||||
cantidad: m.cantidad,
|
||||
saldo: m.saldoPosterior
|
||||
}))
|
||||
);
|
||||
|
||||
function aplicarFiltros() {
|
||||
const params = new URLSearchParams();
|
||||
if (filtros.repuestoId) params.set('repuestoId', String(filtros.repuestoId));
|
||||
if (filtros.almacenId) params.set('almacenId', String(filtros.almacenId));
|
||||
if (filtros.tipo) params.set('tipo', filtros.tipo);
|
||||
if (filtros.desde) params.set('desde', filtros.desde);
|
||||
@@ -66,9 +75,24 @@
|
||||
}
|
||||
|
||||
function limpiarFiltros() {
|
||||
filtros = { almacenId: 0, tipo: '', desde: '', hasta: '' };
|
||||
filtros = { repuestoId: 0, almacenId: 0, tipo: '', desde: '', hasta: '' };
|
||||
void goto('/stock/reportes', { replaceState: true });
|
||||
}
|
||||
|
||||
async function exportar(formato: 'csv' | 'xlsx') {
|
||||
exportError = '';
|
||||
exportando = true;
|
||||
const filtrosExport = {
|
||||
repuestoId: filtros.repuestoId || undefined,
|
||||
almacenId: filtros.almacenId || undefined,
|
||||
tipo: filtros.tipo || undefined,
|
||||
desde: filtros.desde || undefined,
|
||||
hasta: filtros.hasta || undefined
|
||||
};
|
||||
const resultado = await exportarReporteStock(formato, filtrosExport);
|
||||
exportando = false;
|
||||
if (resultado) exportError = resultado;
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
@@ -86,6 +110,13 @@
|
||||
}}
|
||||
>
|
||||
<div class="flex flex-wrap gap-4 items-end mb-4!">
|
||||
<Select labelText="Repuesto" bind:selected={filtros.repuestoId}>
|
||||
<SelectItem value={0} text="Todos" />
|
||||
{#each data.repuestos as r (r.ID)}
|
||||
<SelectItem value={r.ID} text={r.nombre ?? r.ID} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<Select labelText="Almacén" bind:selected={filtros.almacenId}>
|
||||
<SelectItem value={0} text="Todos" />
|
||||
{#each data.almacenes as a (a.id)}
|
||||
@@ -123,7 +154,37 @@
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton class="mb-4" />
|
||||
{/if}
|
||||
|
||||
{#if exportError}
|
||||
<InlineNotification kind="error" title="Exportación" subtitle={exportError} hideCloseButton class="mb-4" />
|
||||
{/if}
|
||||
|
||||
<div class="flex gap-2 mb-4!">
|
||||
<Button kind="secondary" disabled={exportando} onclick={() => exportar('csv')}>
|
||||
{exportando ? 'Exportando...' : 'Exportar CSV'}
|
||||
</Button>
|
||||
<Button kind="secondary" disabled={exportando} onclick={() => exportar('xlsx')}>
|
||||
{exportando ? 'Exportando...' : 'Exportar Excel'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable {headers} {rows} />
|
||||
</div>
|
||||
{#if movimientos.length === 0}
|
||||
<InlineNotification kind="info" title="Sin datos" subtitle="No hay movimientos para los filtros seleccionados." hideCloseButton class="mb-4" />
|
||||
{:else}
|
||||
<DataTable {headers} {rows} />
|
||||
{/if}
|
||||
|
||||
{#if resumen.length > 0}
|
||||
<h2 class="mt-6 mb-2">Totales por tipo</h2>
|
||||
<DataTable
|
||||
headers={[
|
||||
{ key: 'tipo', value: 'Tipo' },
|
||||
{ key: 'cantidad', value: 'Cantidad' }
|
||||
]}
|
||||
rows={resumen.map((r: any, i: number) => ({
|
||||
id: i,
|
||||
tipo: r.tipo,
|
||||
cantidad: r.cantidad
|
||||
}))}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
Reference in new issue
Block a user