implementato il modale di carico e scarico del magazzino
This commit is contained in:
parent
2ad2d05ceb
commit
88d6de0453
7 changed files with 869 additions and 6 deletions
|
|
@ -1,3 +1,177 @@
|
|||
export default function Movimenti(){
|
||||
return <h1>Movimenti</h1>
|
||||
}
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import type { Movimento } from "@/src/types/movimento";
|
||||
|
||||
export default function MovimentiPage() {
|
||||
const [movimenti, setMovimenti] = useState<Movimento[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchMovimenti = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/movimenti?limit=200");
|
||||
if (!res.ok) throw new Error("Errore nel caricamento");
|
||||
|
||||
const data = await res.json();
|
||||
setMovimenti(data.movimenti);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Errore sconosciuto");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchMovimenti();
|
||||
}, [fetchMovimenti]);
|
||||
|
||||
const formatDate = (dateStr: string) => {
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleString("it-IT", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-black">
|
||||
<div className="max-w-6xl mx-auto px-4 py-6">
|
||||
{/* Header */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-bold text-white">Movimenti</h1>
|
||||
<p className="text-sm text-zinc-500">Storico carichi e scarichi</p>
|
||||
</div>
|
||||
|
||||
{/* Statistiche rapide */}
|
||||
<div className="grid grid-cols-3 gap-4 mb-6">
|
||||
<div className="p-4 rounded-xl bg-zinc-900 border border-zinc-800">
|
||||
<p className="text-sm text-zinc-500">Totale movimenti</p>
|
||||
<p className="text-2xl font-bold text-white">{movimenti.length}</p>
|
||||
</div>
|
||||
<div className="p-4 rounded-xl bg-zinc-900 border border-green-500/30">
|
||||
<p className="text-sm text-zinc-500">Carichi</p>
|
||||
<p className="text-2xl font-bold text-green-400">
|
||||
{movimenti.filter((m) => m.tipo_movimento === 1).length}
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-4 rounded-xl bg-zinc-900 border border-red-500/30">
|
||||
<p className="text-sm text-zinc-500">Scarichi</p>
|
||||
<p className="text-2xl font-bold text-red-400">
|
||||
{movimenti.filter((m) => m.tipo_movimento === 2).length}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Lista movimenti */}
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-20 text-zinc-500">
|
||||
<svg className="w-6 h-6 animate-spin mr-3" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
Caricamento movimenti...
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-6 rounded-xl bg-red-500/10 border border-red-500/30 text-center">
|
||||
<p className="text-red-400">{error}</p>
|
||||
<button onClick={fetchMovimenti} className="mt-4 px-4 py-2 rounded-lg bg-red-600 text-white hover:bg-red-500">
|
||||
Riprova
|
||||
</button>
|
||||
</div>
|
||||
) : movimenti.length === 0 ? (
|
||||
<div className="p-12 rounded-xl bg-zinc-900 border border-zinc-800 text-center">
|
||||
<svg className="w-16 h-16 mx-auto text-zinc-700 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
|
||||
</svg>
|
||||
<h3 className="text-lg font-medium text-white mb-2">Nessun movimento</h3>
|
||||
<p className="text-zinc-500">I movimenti appariranno qui quando effettuerai carichi o scarichi</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{movimenti.map((movimento) => (
|
||||
<div
|
||||
key={movimento.id}
|
||||
className={`
|
||||
flex items-center gap-4 p-4 rounded-lg border bg-zinc-900
|
||||
${movimento.tipo_movimento === 1 ? "border-green-500/30" : "border-red-500/30"}
|
||||
`}
|
||||
>
|
||||
{/* Icona tipo */}
|
||||
<div className={`
|
||||
p-2 rounded-lg flex-shrink-0
|
||||
${movimento.tipo_movimento === 1 ? "bg-green-500/10 text-green-400" : "bg-red-500/10 text-red-400"}
|
||||
`}>
|
||||
{movimento.tipo_movimento === 1 ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Info articolo */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-white truncate">
|
||||
{movimento.articolo_descrizione}
|
||||
</p>
|
||||
<p className="text-xs text-zinc-500 font-mono">
|
||||
{movimento.articolo_codice}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Quantità */}
|
||||
<div className={`
|
||||
text-lg font-bold flex-shrink-0
|
||||
${movimento.tipo_movimento === 1 ? "text-green-400" : "text-red-400"}
|
||||
`}>
|
||||
{movimento.tipo_movimento === 1 ? "+" : "-"}{movimento.quantita}
|
||||
</div>
|
||||
|
||||
{/* Magazzino */}
|
||||
<div className="text-right flex-shrink-0 min-w-[120px]">
|
||||
<p className="text-xs text-zinc-500">
|
||||
{movimento.tipo_movimento === 1 ? "Destinazione" : "Origine"}
|
||||
</p>
|
||||
<p className="text-sm text-white">
|
||||
{movimento.tipo_movimento === 1
|
||||
? movimento.magazzino_destinazione
|
||||
: movimento.magazzino_origine}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Data e utente */}
|
||||
<div className="text-right flex-shrink-0 min-w-[140px]">
|
||||
<p className="text-xs text-white">
|
||||
{formatDate(movimento.data_movimento)}
|
||||
</p>
|
||||
<p className="text-xs text-zinc-500">
|
||||
{movimento.utente}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Causale */}
|
||||
{movimento.causale && (
|
||||
<div className="flex-shrink-0 max-w-[150px]">
|
||||
<p className="text-xs text-zinc-400 truncate" title={movimento.causale}>
|
||||
{movimento.causale}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
112
src/app/api/movimenti/route.ts
Normal file
112
src/app/api/movimenti/route.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import { NextResponse } from "next/server";
|
||||
|
||||
import { auth } from "@/src/auth";
|
||||
import { listMovimenti, createMovimento } from "@/src/lib/movimenti";
|
||||
import { getArticleById } from "@/src/lib/articles";
|
||||
import type { TipoMovimento } from "@/src/types/movimento";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Non autorizzato" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const articoloId = searchParams.get("articoloId");
|
||||
const magazzinoId = searchParams.get("magazzinoId");
|
||||
const limit = searchParams.get("limit");
|
||||
|
||||
const movimenti = await listMovimenti({
|
||||
articoloId: articoloId ? parseInt(articoloId, 10) : undefined,
|
||||
magazzinoId: magazzinoId ? parseInt(magazzinoId, 10) : undefined,
|
||||
limit: limit ? parseInt(limit, 10) : 100,
|
||||
});
|
||||
|
||||
return NextResponse.json({ movimenti });
|
||||
} catch (error) {
|
||||
console.error("[API movimenti] Errore GET:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Errore nel recupero dei movimenti" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Non autorizzato" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { id_articolo, quantita, tipo, id_magazzino, causale } = body as {
|
||||
id_articolo: number;
|
||||
quantita: number;
|
||||
tipo: TipoMovimento;
|
||||
id_magazzino: number;
|
||||
causale?: string;
|
||||
};
|
||||
|
||||
if (!id_articolo || !quantita || !tipo || !id_magazzino) {
|
||||
return NextResponse.json(
|
||||
{ error: "Campi obbligatori mancanti: id_articolo, quantita, tipo, id_magazzino" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (quantita <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "La quantità deve essere maggiore di zero" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!["carico", "scarico"].includes(tipo)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Tipo movimento non valido. Usare 'carico' o 'scarico'" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const articolo = await getArticleById(id_articolo);
|
||||
if (!articolo) {
|
||||
return NextResponse.json(
|
||||
{ error: "Articolo non trovato" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const tipoMovimentoDB = tipo === "carico" ? 1 : 2;
|
||||
const utente = session.user.name || session.user.email || "Sistema";
|
||||
|
||||
const movimentoId = await createMovimento({
|
||||
id_articolo,
|
||||
articolo_codice: articolo.codice,
|
||||
articolo_descrizione: articolo.descrizione,
|
||||
quantita,
|
||||
tipo_movimento: tipoMovimentoDB,
|
||||
causale: causale || null,
|
||||
utente,
|
||||
id_magazzino_origine: tipo === "scarico" ? id_magazzino : null,
|
||||
id_magazzino_destinazione: tipo === "carico" ? id_magazzino : null,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
message: `${tipo === "carico" ? "Carico" : "Scarico"} registrato con successo`,
|
||||
id: movimentoId
|
||||
},
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[API movimenti] Errore POST:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Errore nella registrazione del movimento" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
import { useState } from "react";
|
||||
import type { Article } from "@/src/types/article";
|
||||
import type { TipoMovimento } from "@/src/types/movimento";
|
||||
|
||||
interface ArticleCardProps {
|
||||
article: Article;
|
||||
|
|
@ -9,6 +10,7 @@ interface ArticleCardProps {
|
|||
magazzinoNome?: string;
|
||||
onEdit: (article: Article) => void;
|
||||
onDelete: (article: Article) => void;
|
||||
onMovimento?: (article: Article, tipo: TipoMovimento) => void;
|
||||
}
|
||||
|
||||
export default function ArticleCard({
|
||||
|
|
@ -16,7 +18,8 @@ export default function ArticleCard({
|
|||
giacenzaMagazzino,
|
||||
magazzinoNome,
|
||||
onEdit,
|
||||
onDelete
|
||||
onDelete,
|
||||
onMovimento,
|
||||
}: ArticleCardProps) {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
|
|
@ -107,7 +110,31 @@ export default function ArticleCard({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Azioni */}
|
||||
{/* Azioni movimenti */}
|
||||
{onMovimento && (
|
||||
<div className="flex items-center gap-1 flex-shrink-0 border-l border-zinc-800 pl-3">
|
||||
<button
|
||||
onClick={() => onMovimento(article, "carico")}
|
||||
className="p-1.5 rounded text-zinc-500 hover:text-green-400 hover:bg-green-500/10 transition-colors"
|
||||
title="Carico"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onMovimento(article, "scarico")}
|
||||
className="p-1.5 rounded text-zinc-500 hover:text-red-400 hover:bg-red-500/10 transition-colors"
|
||||
title="Scarico"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Azioni CRUD */}
|
||||
<div className="flex items-center gap-1 flex-shrink-0 border-l border-zinc-800 pl-3">
|
||||
<button
|
||||
onClick={() => onEdit(article)}
|
||||
|
|
|
|||
|
|
@ -4,8 +4,10 @@ import { useState, useEffect, useCallback } from "react";
|
|||
import type { Article, ArticleFamily } from "@/src/types/article";
|
||||
import type { Stabilimento, Magazzino } from "@/src/types/stabilimento";
|
||||
import type { GiacenzePerArticolo } from "@/src/types/giacenza";
|
||||
import type { TipoMovimento } from "@/src/types/movimento";
|
||||
import ArticleCard from "./ArticleCard";
|
||||
import ArticleModal from "./ArticleModal";
|
||||
import MovimentoModal from "./MovimentoModal";
|
||||
import StabilimentoMagazzinoSelector from "./StabilimentoMagazzinoSelector";
|
||||
|
||||
export default function ArticlesList() {
|
||||
|
|
@ -19,6 +21,10 @@ export default function ArticlesList() {
|
|||
const [showModal, setShowModal] = useState(false);
|
||||
const [editingArticle, setEditingArticle] = useState<Article | null>(null);
|
||||
|
||||
const [showMovimentoModal, setShowMovimentoModal] = useState(false);
|
||||
const [movimentoArticle, setMovimentoArticle] = useState<Article | null>(null);
|
||||
const [movimentoTipo, setMovimentoTipo] = useState<TipoMovimento>("carico");
|
||||
|
||||
const [selectedStabilimento, setSelectedStabilimento] = useState<Stabilimento | null>(null);
|
||||
const [selectedMagazzino, setSelectedMagazzino] = useState<Magazzino | null>(null);
|
||||
|
||||
|
|
@ -101,6 +107,19 @@ export default function ArticlesList() {
|
|||
fetchGiacenze();
|
||||
};
|
||||
|
||||
const handleMovimento = (article: Article, tipo: TipoMovimento) => {
|
||||
setMovimentoArticle(article);
|
||||
setMovimentoTipo(tipo);
|
||||
setShowMovimentoModal(true);
|
||||
};
|
||||
|
||||
const handleMovimentoSuccess = () => {
|
||||
setShowMovimentoModal(false);
|
||||
setMovimentoArticle(null);
|
||||
fetchArticles();
|
||||
fetchGiacenze();
|
||||
};
|
||||
|
||||
const filteredArticles = articles.filter((article) => {
|
||||
if (!search) return true;
|
||||
const searchLower = search.toLowerCase();
|
||||
|
|
@ -184,12 +203,13 @@ export default function ArticlesList() {
|
|||
magazzinoNome={magazzinoNome}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onMovimento={handleMovimento}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal */}
|
||||
{/* Modal Articolo */}
|
||||
{showModal && (
|
||||
<ArticleModal
|
||||
article={editingArticle}
|
||||
|
|
@ -198,6 +218,16 @@ export default function ArticlesList() {
|
|||
onSave={handleSave}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Modal Movimento */}
|
||||
{showMovimentoModal && movimentoArticle && (
|
||||
<MovimentoModal
|
||||
article={movimentoArticle}
|
||||
tipo={movimentoTipo}
|
||||
onClose={() => { setShowMovimentoModal(false); setMovimentoArticle(null); }}
|
||||
onSuccess={handleMovimentoSuccess}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
281
src/components/MovimentoModal.tsx
Normal file
281
src/components/MovimentoModal.tsx
Normal file
|
|
@ -0,0 +1,281 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import type { Article } from "@/src/types/article";
|
||||
import type { Stabilimento, Magazzino } from "@/src/types/stabilimento";
|
||||
import type { TipoMovimento } from "@/src/types/movimento";
|
||||
|
||||
interface MovimentoModalProps {
|
||||
article: Article;
|
||||
tipo: TipoMovimento;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function MovimentoModal({
|
||||
article,
|
||||
tipo,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}: MovimentoModalProps) {
|
||||
const modalRef = useRef<HTMLDivElement>(null);
|
||||
const isCarico = tipo === "carico";
|
||||
|
||||
const [stabilimenti, setStabilimenti] = useState<Stabilimento[]>([]);
|
||||
const [magazzini, setMagazzini] = useState<Magazzino[]>([]);
|
||||
const [selectedStabilimento, setSelectedStabilimento] = useState<number | null>(null);
|
||||
const [selectedMagazzino, setSelectedMagazzino] = useState<number | null>(null);
|
||||
const [quantita, setQuantita] = useState<number>(1);
|
||||
const [causale, setCausale] = useState<string>("");
|
||||
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchData() {
|
||||
try {
|
||||
const [stabRes, magRes] = await Promise.all([
|
||||
fetch("/api/stabilimenti"),
|
||||
fetch("/api/magazzini"),
|
||||
]);
|
||||
|
||||
if (stabRes.ok && magRes.ok) {
|
||||
const stabData = await stabRes.json();
|
||||
const magData = await magRes.json();
|
||||
setStabilimenti(stabData.stabilimenti);
|
||||
setMagazzini(magData.magazzini);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Errore caricamento dati:", error);
|
||||
}
|
||||
}
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
document.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
const filteredMagazzini = selectedStabilimento
|
||||
? magazzini.filter((m) => m.id_stabilimento === selectedStabilimento)
|
||||
: [];
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!selectedMagazzino) {
|
||||
setError("Seleziona un magazzino");
|
||||
return;
|
||||
}
|
||||
|
||||
if (quantita <= 0) {
|
||||
setError("La quantità deve essere maggiore di zero");
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/movimenti", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
id_articolo: article.id,
|
||||
quantita,
|
||||
tipo,
|
||||
id_magazzino: selectedMagazzino,
|
||||
causale: causale || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || "Errore durante la registrazione");
|
||||
}
|
||||
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Errore sconosciuto");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm">
|
||||
<div
|
||||
ref={modalRef}
|
||||
className="w-full max-w-md bg-zinc-900 rounded-2xl shadow-2xl border border-zinc-800 overflow-hidden"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className={`flex items-center justify-between px-6 py-4 border-b ${
|
||||
isCarico ? "border-green-500/30 bg-green-500/5" : "border-red-500/30 bg-red-500/5"
|
||||
}`}>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-2 rounded-lg ${isCarico ? "bg-green-500/20 text-green-400" : "bg-red-500/20 text-red-400"}`}>
|
||||
{isCarico ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<h2 className={`text-lg font-semibold ${isCarico ? "text-green-400" : "text-red-400"}`}>
|
||||
{isCarico ? "Carico" : "Scarico"}
|
||||
</h2>
|
||||
<p className="text-xs text-zinc-500">Registra movimento</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800 transition-colors"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Articolo info */}
|
||||
<div className="px-6 py-3 bg-zinc-800/50 border-b border-zinc-800">
|
||||
<p className="text-sm text-zinc-400">Articolo</p>
|
||||
<p className="font-medium text-white">{article.descrizione}</p>
|
||||
<p className="text-xs text-zinc-500 font-mono">{article.codice}</p>
|
||||
<p className="text-xs text-zinc-500 mt-1">
|
||||
Giacenza attuale: <span className="text-white">{article.quantita}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-4">
|
||||
{error && (
|
||||
<div className="p-3 rounded-lg bg-red-500/10 border border-red-500/50 text-red-400 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stabilimento */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Stabilimento
|
||||
</label>
|
||||
<select
|
||||
value={selectedStabilimento ?? ""}
|
||||
onChange={(e) => {
|
||||
setSelectedStabilimento(e.target.value ? parseInt(e.target.value, 10) : null);
|
||||
setSelectedMagazzino(null);
|
||||
}}
|
||||
className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white focus:outline-none focus:border-blue-500 transition-colors"
|
||||
>
|
||||
<option value="">Seleziona stabilimento...</option>
|
||||
{stabilimenti.map((stab) => (
|
||||
<option key={stab.id} value={stab.id}>
|
||||
{stab.descrizione}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Magazzino */}
|
||||
{selectedStabilimento && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Magazzino {isCarico ? "(destinazione)" : "(origine)"}
|
||||
</label>
|
||||
<select
|
||||
value={selectedMagazzino ?? ""}
|
||||
onChange={(e) => setSelectedMagazzino(e.target.value ? parseInt(e.target.value, 10) : null)}
|
||||
className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white focus:outline-none focus:border-blue-500 transition-colors"
|
||||
>
|
||||
<option value="">Seleziona magazzino...</option>
|
||||
{filteredMagazzini.map((mag) => (
|
||||
<option key={mag.id} value={mag.id}>
|
||||
{mag.descrizione}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quantità */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Quantità
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
value={quantita}
|
||||
onChange={(e) => setQuantita(parseFloat(e.target.value) || 0)}
|
||||
min="1"
|
||||
className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white focus:outline-none focus:border-blue-500 transition-colors text-lg font-semibold"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Causale */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Causale (opzionale)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={causale}
|
||||
onChange={(e) => setCausale(e.target.value)}
|
||||
placeholder={isCarico ? "Es: Acquisto fornitore" : "Es: Utilizzo manutenzione"}
|
||||
className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-zinc-800">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800 transition-colors"
|
||||
>
|
||||
Annulla
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving || !selectedMagazzino}
|
||||
className={`px-6 py-2 rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 ${
|
||||
isCarico
|
||||
? "bg-green-600 text-white hover:bg-green-500"
|
||||
: "bg-red-600 text-white hover:bg-red-500"
|
||||
}`}
|
||||
>
|
||||
{saving && (
|
||||
<svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
)}
|
||||
{isCarico ? "Registra Carico" : "Registra Scarico"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
199
src/lib/movimenti/index.ts
Normal file
199
src/lib/movimenti/index.ts
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
import type { ResultSetHeader, RowDataPacket } from "mysql2";
|
||||
|
||||
import { db, getDbConnection } from "@/src/lib/db";
|
||||
import type { Movimento, CreateMovimentoPayload } from "@/src/types/movimento";
|
||||
|
||||
type MovimentoRow = Movimento & RowDataPacket;
|
||||
|
||||
export async function listMovimenti(options: {
|
||||
articoloId?: number;
|
||||
magazzinoId?: number;
|
||||
limit?: number;
|
||||
} = {}): Promise<Movimento[]> {
|
||||
const { articoloId, magazzinoId, limit = 100 } = options;
|
||||
|
||||
const conditions: string[] = [];
|
||||
const params: Record<string, number> = {};
|
||||
|
||||
if (articoloId) {
|
||||
conditions.push("m.id_articolo = :articoloId");
|
||||
params.articoloId = articoloId;
|
||||
}
|
||||
|
||||
if (magazzinoId) {
|
||||
conditions.push("(m.id_magazzino_origine = :magazzinoId OR m.id_magazzino_destinazione = :magazzinoId)");
|
||||
params.magazzinoId = magazzinoId;
|
||||
}
|
||||
|
||||
let query = `
|
||||
SELECT
|
||||
m.id,
|
||||
m.id_articolo,
|
||||
m.articolo_codice,
|
||||
m.articolo_descrizione,
|
||||
m.id_macchina_parte,
|
||||
m.nome_macchina_parte,
|
||||
m.quantita,
|
||||
m.data_movimento,
|
||||
m.tipo_movimento,
|
||||
m.causale,
|
||||
m.utente,
|
||||
m.id_intervento,
|
||||
m.id_magazzino_origine,
|
||||
m.id_magazzino_destinazione,
|
||||
mo.descrizione AS magazzino_origine,
|
||||
md.descrizione AS magazzino_destinazione
|
||||
FROM movimenti m
|
||||
LEFT JOIN magazzini mo ON mo.id = m.id_magazzino_origine
|
||||
LEFT JOIN magazzini md ON md.id = m.id_magazzino_destinazione
|
||||
`;
|
||||
|
||||
if (conditions.length > 0) {
|
||||
query += " WHERE " + conditions.join(" AND ");
|
||||
}
|
||||
|
||||
query += ` ORDER BY m.data_movimento DESC LIMIT ${limit}`;
|
||||
|
||||
const [rows] = await db.execute<MovimentoRow[]>(query, params);
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
id_articolo: row.id_articolo,
|
||||
articolo_codice: row.articolo_codice,
|
||||
articolo_descrizione: row.articolo_descrizione,
|
||||
id_macchina_parte: row.id_macchina_parte,
|
||||
nome_macchina_parte: row.nome_macchina_parte,
|
||||
quantita: Number(row.quantita) || 0,
|
||||
data_movimento: row.data_movimento,
|
||||
tipo_movimento: row.tipo_movimento,
|
||||
causale: row.causale,
|
||||
utente: row.utente,
|
||||
id_intervento: row.id_intervento,
|
||||
id_magazzino_origine: row.id_magazzino_origine,
|
||||
id_magazzino_destinazione: row.id_magazzino_destinazione,
|
||||
magazzino_origine: row.magazzino_origine,
|
||||
magazzino_destinazione: row.magazzino_destinazione,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function createMovimento(
|
||||
payload: CreateMovimentoPayload
|
||||
): Promise<number> {
|
||||
const connection = await getDbConnection();
|
||||
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`INSERT INTO movimenti
|
||||
(id_articolo, articolo_codice, articolo_descrizione, quantita, tipo_movimento, causale, utente, id_magazzino_origine, id_magazzino_destinazione)
|
||||
VALUES (:id_articolo, :articolo_codice, :articolo_descrizione, :quantita, :tipo_movimento, :causale, :utente, :id_magazzino_origine, :id_magazzino_destinazione)`,
|
||||
{
|
||||
id_articolo: payload.id_articolo,
|
||||
articolo_codice: payload.articolo_codice,
|
||||
articolo_descrizione: payload.articolo_descrizione,
|
||||
quantita: payload.quantita,
|
||||
tipo_movimento: payload.tipo_movimento,
|
||||
causale: payload.causale,
|
||||
utente: payload.utente,
|
||||
id_magazzino_origine: payload.id_magazzino_origine,
|
||||
id_magazzino_destinazione: payload.id_magazzino_destinazione,
|
||||
}
|
||||
);
|
||||
|
||||
const movimentoId = result.insertId;
|
||||
|
||||
const idMagazzino = payload.tipo_movimento === 1
|
||||
? payload.id_magazzino_destinazione
|
||||
: payload.id_magazzino_origine;
|
||||
|
||||
if (!idMagazzino) {
|
||||
throw new Error("Magazzino non specificato");
|
||||
}
|
||||
|
||||
const [existingRows] = await connection.execute<RowDataPacket[]>(
|
||||
"SELECT id, quantita FROM giacenze WHERE articolo_id = :articoloId AND id_magazzino = :magazzinoId",
|
||||
{ articoloId: payload.id_articolo, magazzinoId: idMagazzino }
|
||||
);
|
||||
|
||||
const existing = existingRows[0];
|
||||
|
||||
if (payload.tipo_movimento === 1) {
|
||||
if (existing) {
|
||||
await connection.execute<ResultSetHeader>(
|
||||
"UPDATE giacenze SET quantita = quantita + :quantita WHERE id = :id",
|
||||
{ quantita: payload.quantita, id: existing.id }
|
||||
);
|
||||
} else {
|
||||
await connection.execute<ResultSetHeader>(
|
||||
"INSERT INTO giacenze (articolo_id, id_magazzino, quantita) VALUES (:articoloId, :magazzinoId, :quantita)",
|
||||
{ articoloId: payload.id_articolo, magazzinoId: idMagazzino, quantita: payload.quantita }
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (!existing || Number(existing.quantita) < payload.quantita) {
|
||||
throw new Error(
|
||||
`Quantità insufficiente. Disponibile: ${existing?.quantita || 0}, richiesta: ${payload.quantita}`
|
||||
);
|
||||
}
|
||||
|
||||
const nuovaQuantita = Number(existing.quantita) - payload.quantita;
|
||||
|
||||
if (nuovaQuantita === 0) {
|
||||
await connection.execute<ResultSetHeader>(
|
||||
"DELETE FROM giacenze WHERE id = :id",
|
||||
{ id: existing.id }
|
||||
);
|
||||
} else {
|
||||
await connection.execute<ResultSetHeader>(
|
||||
"UPDATE giacenze SET quantita = :quantita WHERE id = :id",
|
||||
{ quantita: nuovaQuantita, id: existing.id }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await connection.commit();
|
||||
return movimentoId;
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMovimentoById(id: number): Promise<Movimento | null> {
|
||||
const [rows] = await db.execute<MovimentoRow[]>(
|
||||
`SELECT
|
||||
m.*,
|
||||
mo.descrizione AS magazzino_origine,
|
||||
md.descrizione AS magazzino_destinazione
|
||||
FROM movimenti m
|
||||
LEFT JOIN magazzini mo ON mo.id = m.id_magazzino_origine
|
||||
LEFT JOIN magazzini md ON md.id = m.id_magazzino_destinazione
|
||||
WHERE m.id = :id`,
|
||||
{ id }
|
||||
);
|
||||
|
||||
const row = rows[0];
|
||||
if (!row) return null;
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
id_articolo: row.id_articolo,
|
||||
articolo_codice: row.articolo_codice,
|
||||
articolo_descrizione: row.articolo_descrizione,
|
||||
id_macchina_parte: row.id_macchina_parte,
|
||||
nome_macchina_parte: row.nome_macchina_parte,
|
||||
quantita: Number(row.quantita) || 0,
|
||||
data_movimento: row.data_movimento,
|
||||
tipo_movimento: row.tipo_movimento,
|
||||
causale: row.causale,
|
||||
utente: row.utente,
|
||||
id_intervento: row.id_intervento,
|
||||
id_magazzino_origine: row.id_magazzino_origine,
|
||||
id_magazzino_destinazione: row.id_magazzino_destinazione,
|
||||
magazzino_origine: row.magazzino_origine,
|
||||
magazzino_destinazione: row.magazzino_destinazione,
|
||||
};
|
||||
}
|
||||
40
src/types/movimento.ts
Normal file
40
src/types/movimento.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
export type TipoMovimento = "carico" | "scarico";
|
||||
|
||||
export interface Movimento {
|
||||
id: number;
|
||||
id_articolo: number;
|
||||
articolo_codice: string | null;
|
||||
articolo_descrizione: string | null;
|
||||
id_macchina_parte: number | null;
|
||||
nome_macchina_parte: string | null;
|
||||
quantita: number;
|
||||
data_movimento: string;
|
||||
tipo_movimento: number; // 1 = carico, 2 = scarico
|
||||
causale: string | null;
|
||||
utente: string | null;
|
||||
id_intervento: number | null;
|
||||
id_magazzino_origine: number | null;
|
||||
id_magazzino_destinazione: number | null;
|
||||
magazzino_origine?: string;
|
||||
magazzino_destinazione?: string;
|
||||
}
|
||||
|
||||
export interface MovimentoInput {
|
||||
id_articolo: number;
|
||||
quantita: number;
|
||||
tipo: TipoMovimento;
|
||||
id_magazzino: number;
|
||||
causale?: string;
|
||||
}
|
||||
|
||||
export interface CreateMovimentoPayload {
|
||||
id_articolo: number;
|
||||
articolo_codice: string;
|
||||
articolo_descrizione: string;
|
||||
quantita: number;
|
||||
tipo_movimento: number;
|
||||
causale: string | null;
|
||||
utente: string;
|
||||
id_magazzino_origine: number | null;
|
||||
id_magazzino_destinazione: number | null;
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue