modifiche a Modale di scarico, inserito Drag & Drop e modale destinazione scarico
This commit is contained in:
parent
c66ee44f36
commit
17119cda99
12 changed files with 1069 additions and 66 deletions
57
src/app/api/art-macchine-parti/[idmacchina]/[idart]/route.ts
Normal file
57
src/app/api/art-macchine-parti/[idmacchina]/[idart]/route.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { NextResponse } from "next/server";
|
||||
|
||||
import { auth } from "@/src/auth";
|
||||
import { rimuoviArticoloDaMacchina } from "@/src/lib/artMacchineParti";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{ idmacchina: string; idart: string }>;
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, { params }: RouteParams) {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Non autorizzato" }, { status: 401 });
|
||||
}
|
||||
|
||||
const { idmacchina, idart } = await params;
|
||||
const macchinaId = parseInt(idmacchina, 10);
|
||||
const articoloId = parseInt(idart, 10);
|
||||
|
||||
if (isNaN(macchinaId) || isNaN(articoloId)) {
|
||||
return NextResponse.json({ error: "ID non validi" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { quantita, opzione } = body;
|
||||
|
||||
if (!quantita || quantita <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "Quantità non valida" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!opzione || !["carico", "elimina"].includes(opzione)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Opzione non valida (carico o elimina)" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await rimuoviArticoloDaMacchina(
|
||||
articoloId,
|
||||
macchinaId,
|
||||
quantita,
|
||||
opzione,
|
||||
session.user.email || session.user.name || "unknown"
|
||||
);
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
console.error("[API art-macchine-parti/:idmacchina/:idart] Errore DELETE:", error);
|
||||
const message = error instanceof Error ? error.message : "Errore nella rimozione";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
34
src/app/api/art-macchine-parti/[idmacchina]/route.ts
Normal file
34
src/app/api/art-macchine-parti/[idmacchina]/route.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { NextResponse } from "next/server";
|
||||
|
||||
import { auth } from "@/src/auth";
|
||||
import { getArticoliByMacchina } from "@/src/lib/artMacchineParti";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{ idmacchina: string }>;
|
||||
}
|
||||
|
||||
export async function GET(request: Request, { params }: RouteParams) {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Non autorizzato" }, { status: 401 });
|
||||
}
|
||||
|
||||
const { idmacchina } = await params;
|
||||
const macchinaId = parseInt(idmacchina, 10);
|
||||
|
||||
if (isNaN(macchinaId)) {
|
||||
return NextResponse.json({ error: "ID macchina non valido" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const articoli = await getArticoliByMacchina(macchinaId);
|
||||
return NextResponse.json({ articoli });
|
||||
} catch (error) {
|
||||
console.error("[API art-macchine-parti/:idmacchina] Errore GET:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Errore nel recupero degli articoli" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
46
src/app/api/art-macchine-parti/assegna/route.ts
Normal file
46
src/app/api/art-macchine-parti/assegna/route.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { NextResponse } from "next/server";
|
||||
|
||||
import { auth } from "@/src/auth";
|
||||
import { assegnaArticoloMacchina } from "@/src/lib/artMacchineParti";
|
||||
|
||||
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 { idart, idmacchina, quantita, causale } = body;
|
||||
|
||||
if (!idart || !idmacchina || !quantita) {
|
||||
return NextResponse.json(
|
||||
{ error: "Parametri mancanti: idart, idmacchina, quantita sono obbligatori" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (quantita <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "La quantità deve essere maggiore di zero" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await assegnaArticoloMacchina({
|
||||
idart: parseInt(idart),
|
||||
idmacchina: parseInt(idmacchina),
|
||||
quantita: parseInt(quantita),
|
||||
causale: causale || "Assegnazione articolo a macchina",
|
||||
user: session.user.email || session.user.name || "unknown",
|
||||
});
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
console.error("[API art-macchine-parti/assegna] Errore POST:", error);
|
||||
const message = error instanceof Error ? error.message : "Errore nell'assegnazione";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
23
src/app/api/art-macchine-parti/route.ts
Normal file
23
src/app/api/art-macchine-parti/route.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { NextResponse } from "next/server";
|
||||
|
||||
import { auth } from "@/src/auth";
|
||||
import { getArticoliPerTutteLeMacchine } from "@/src/lib/artMacchineParti";
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Non autorizzato" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const articoliPerMacchina = await getArticoliPerTutteLeMacchine();
|
||||
return NextResponse.json({ articoliPerMacchina });
|
||||
} catch (error) {
|
||||
console.error("[API art-macchine-parti] Errore GET:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Errore nel recupero degli articoli" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useState, type DragEvent } from "react";
|
||||
import type { Article } from "@/src/types/article";
|
||||
import type { TipoMovimento } from "@/src/types/movimento";
|
||||
|
||||
|
|
@ -11,6 +11,7 @@ interface ArticleCardProps {
|
|||
onEdit: (article: Article) => void;
|
||||
onDelete: (article: Article) => void;
|
||||
onMovimento?: (article: Article, tipo: TipoMovimento) => void;
|
||||
draggable?: boolean;
|
||||
}
|
||||
|
||||
export default function ArticleCard({
|
||||
|
|
@ -20,12 +21,15 @@ export default function ArticleCard({
|
|||
onEdit,
|
||||
onDelete,
|
||||
onMovimento,
|
||||
draggable = true,
|
||||
}: ArticleCardProps) {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
|
||||
const isSottoScorta = article.quantita < article.quantita_minima;
|
||||
const disponibile = article.quantita - article.assegnata_macchine;
|
||||
const hasGiacenzaMagazzino = giacenzaMagazzino !== undefined;
|
||||
const canDrag = draggable && disponibile > 0;
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!confirm(`Eliminare "${article.descrizione}"?`)) return;
|
||||
|
|
@ -42,11 +46,37 @@ export default function ArticleCard({
|
|||
}
|
||||
};
|
||||
|
||||
const handleDragStart = (e: DragEvent<HTMLDivElement>) => {
|
||||
if (!canDrag) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
setIsDragging(true);
|
||||
e.dataTransfer.setData("application/json", JSON.stringify({
|
||||
id: article.id,
|
||||
descrizione: article.descrizione,
|
||||
codice: article.codice,
|
||||
barcode: article.barcode,
|
||||
quantita_residua: disponibile,
|
||||
famiglia: article.famiglia,
|
||||
}));
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
};
|
||||
|
||||
const handleDragEnd = () => {
|
||||
setIsDragging(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
draggable={canDrag}
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
className={`
|
||||
flex items-center gap-3 p-3 rounded-lg border bg-zinc-900 transition-colors hover:bg-zinc-800
|
||||
${isSottoScorta ? "border-red-500/50" : "border-zinc-800"}
|
||||
${canDrag ? "cursor-grab active:cursor-grabbing" : ""}
|
||||
${isDragging ? "opacity-50 ring-2 ring-blue-500" : ""}
|
||||
`}
|
||||
>
|
||||
{/* Indicatore sotto scorta */}
|
||||
|
|
|
|||
|
|
@ -77,6 +77,17 @@ export default function ArticlesList() {
|
|||
fetchGiacenze();
|
||||
}, [fetchGiacenze]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleArticoliUpdated = () => {
|
||||
fetchArticles();
|
||||
};
|
||||
|
||||
window.addEventListener("articoli-updated", handleArticoliUpdated);
|
||||
return () => {
|
||||
window.removeEventListener("articoli-updated", handleArticoliUpdated);
|
||||
};
|
||||
}, [fetchArticles]);
|
||||
|
||||
const handleEdit = (article: Article) => {
|
||||
setEditingArticle(article);
|
||||
setShowModal(true);
|
||||
|
|
|
|||
240
src/components/DestinazioneModal.tsx
Normal file
240
src/components/DestinazioneModal.tsx
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import type { MacchinaWithDetails } from "@/src/types/macchina";
|
||||
|
||||
interface DestinazioneModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (macchina: MacchinaWithDetails) => void;
|
||||
selectedId?: number | null;
|
||||
}
|
||||
|
||||
function TreeNodeSelectable({
|
||||
node,
|
||||
allNodes,
|
||||
level = 0,
|
||||
selectedId,
|
||||
onSelect,
|
||||
}: {
|
||||
node: MacchinaWithDetails;
|
||||
allNodes: MacchinaWithDetails[];
|
||||
level?: number;
|
||||
selectedId?: number | null;
|
||||
onSelect: (node: MacchinaWithDetails) => void;
|
||||
}) {
|
||||
const [isExpanded, setIsExpanded] = useState(level < 2);
|
||||
const children = allNodes.filter((n) => n.id_padre === node.id);
|
||||
const isSelected = selectedId === node.id;
|
||||
|
||||
const getNodeTypeIcon = () => {
|
||||
switch (node.tipo) {
|
||||
case "macchina": return "🔧";
|
||||
case "gruppo": return "📁";
|
||||
case "parte": return "⚙️";
|
||||
default: return "📄";
|
||||
}
|
||||
};
|
||||
|
||||
const getNodeTypeBg = () => {
|
||||
if (isSelected) return "bg-blue-600 border-blue-500";
|
||||
switch (node.tipo) {
|
||||
case "macchina": return "bg-blue-900/30 border-blue-700/50 hover:bg-blue-800/40";
|
||||
case "gruppo": return "bg-purple-900/30 border-purple-700/50 hover:bg-purple-800/40";
|
||||
case "parte": return "bg-zinc-800/50 border-zinc-700/50 hover:bg-zinc-700/50";
|
||||
default: return "bg-zinc-800 border-zinc-700 hover:bg-zinc-700";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ marginLeft: `${level * 16}px` }} className="mb-1">
|
||||
<div
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border cursor-pointer transition-all ${getNodeTypeBg()}`}
|
||||
onClick={() => onSelect(node)}
|
||||
>
|
||||
{children.length > 0 && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setIsExpanded(!isExpanded);
|
||||
}}
|
||||
className="w-5 h-5 flex items-center justify-center text-zinc-400 hover:text-white"
|
||||
>
|
||||
<svg
|
||||
className={`w-4 h-4 transition-transform ${isExpanded ? "rotate-90" : ""}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
{children.length === 0 && <div className="w-5" />}
|
||||
|
||||
<span className="text-sm">{getNodeTypeIcon()}</span>
|
||||
<span className={`flex-1 text-sm font-medium truncate ${isSelected ? "text-white" : "text-zinc-200"}`}>
|
||||
{node.nome}
|
||||
</span>
|
||||
|
||||
{isSelected && (
|
||||
<svg className="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isExpanded && children.length > 0 && (
|
||||
<div className="mt-1">
|
||||
{children.map((child) => (
|
||||
<TreeNodeSelectable
|
||||
key={child.id}
|
||||
node={child}
|
||||
allNodes={allNodes}
|
||||
level={level + 1}
|
||||
selectedId={selectedId}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DestinazioneModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSelect,
|
||||
selectedId,
|
||||
}: DestinazioneModalProps) {
|
||||
const [nodes, setNodes] = useState<MacchinaWithDetails[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [localSelectedId, setLocalSelectedId] = useState<number | null>(selectedId || null);
|
||||
const [localSelectedNode, setLocalSelectedNode] = useState<MacchinaWithDetails | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setLoading(true);
|
||||
setLocalSelectedId(selectedId || null);
|
||||
|
||||
fetch("/api/macchine")
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
setNodes(data.macchine || []);
|
||||
if (selectedId) {
|
||||
const found = data.macchine?.find((n: MacchinaWithDetails) => n.id === selectedId);
|
||||
setLocalSelectedNode(found || null);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Errore caricamento macchine:", error);
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
}
|
||||
}, [isOpen, selectedId]);
|
||||
|
||||
const handleNodeSelect = (node: MacchinaWithDetails) => {
|
||||
setLocalSelectedId(node.id);
|
||||
setLocalSelectedNode(node);
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (localSelectedNode) {
|
||||
onSelect(localSelectedNode);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const rootNodes = nodes.filter((n) => n.id_padre === null);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[60] flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-black/70 backdrop-blur-sm" onClick={onClose} />
|
||||
|
||||
<div className="relative w-full max-w-lg max-h-[80vh] bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-white">Seleziona Destinazione</h3>
|
||||
<p className="text-xs text-zinc-500">Scegli la macchina o parte a cui assegnare l'articolo</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1 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>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-8 text-zinc-500 text-sm">
|
||||
<svg className="w-5 h-5 animate-spin mr-2" 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...
|
||||
</div>
|
||||
) : rootNodes.length === 0 ? (
|
||||
<div className="text-center py-8">
|
||||
<svg className="w-12 h-12 text-zinc-700 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
|
||||
</svg>
|
||||
<p className="text-zinc-500 text-sm">Nessuna macchina disponibile</p>
|
||||
<p className="text-zinc-600 text-xs mt-1">Aggiungi prima delle macchine nel sistema</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{rootNodes.map((node) => (
|
||||
<TreeNodeSelectable
|
||||
key={node.id}
|
||||
node={node}
|
||||
allNodes={nodes}
|
||||
level={0}
|
||||
selectedId={localSelectedId}
|
||||
onSelect={handleNodeSelect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-between px-5 py-4 border-t border-zinc-800 bg-zinc-900/50">
|
||||
{localSelectedNode ? (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-zinc-500">Selezionato:</span>
|
||||
<span className="text-blue-400 font-medium">{localSelectedNode.nome}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-zinc-500">Nessuna selezione</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-zinc-300 hover:text-white rounded-lg hover:bg-zinc-800 transition-colors"
|
||||
>
|
||||
Annulla
|
||||
</button>
|
||||
<button
|
||||
onClick={handleConfirm}
|
||||
disabled={!localSelectedNode}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
Conferma
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,14 +1,30 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import type { MacchinaWithDetails, ArticoliPerMacchina } from "@/src/types/macchina";
|
||||
import type { MacchinaWithDetails } from "@/src/types/macchina";
|
||||
import type { ArticoloAssegnatoMacchina } from "@/src/types/artMacchineParti";
|
||||
import TreeNode from "./TreeNode";
|
||||
import MacchinaModal from "./MacchinaModal";
|
||||
import { useStabilimento } from "@/src/contexts/StabilimentoContext";
|
||||
|
||||
interface DroppedArticle {
|
||||
id: number;
|
||||
descrizione: string;
|
||||
codice: string;
|
||||
barcode?: string | null;
|
||||
quantita_residua: number;
|
||||
famiglia?: string;
|
||||
}
|
||||
|
||||
interface DropModalState {
|
||||
macchinaId: number;
|
||||
macchinaNome: string;
|
||||
article: DroppedArticle;
|
||||
}
|
||||
|
||||
export default function MacchineTree() {
|
||||
const [nodes, setNodes] = useState<MacchinaWithDetails[]>([]);
|
||||
const [articlesByMacchina, setArticlesByMacchina] = useState<ArticoliPerMacchina>({});
|
||||
const [articlesByMacchina, setArticlesByMacchina] = useState<Record<number, ArticoloAssegnatoMacchina[]>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
|
|
@ -26,6 +42,17 @@ export default function MacchineTree() {
|
|||
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{ id: number; nome: string } | null>(null);
|
||||
|
||||
const [dropModal, setDropModal] = useState<DropModalState | null>(null);
|
||||
const [dropQuantita, setDropQuantita] = useState(1);
|
||||
const [dropCausale, setDropCausale] = useState("");
|
||||
const [dropSaving, setDropSaving] = useState(false);
|
||||
|
||||
const [showArticlesModal, setShowArticlesModal] = useState<{
|
||||
macchinaId: number;
|
||||
macchinaNome: string;
|
||||
articoli: ArticoloAssegnatoMacchina[];
|
||||
} | null>(null);
|
||||
|
||||
const fetchNodes = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/macchine");
|
||||
|
|
@ -37,12 +64,23 @@ export default function MacchineTree() {
|
|||
}
|
||||
}, []);
|
||||
|
||||
const fetchArticoliPerMacchina = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/art-macchine-parti");
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setArticlesByMacchina(data.articoliPerMacchina || {});
|
||||
} catch (err) {
|
||||
console.error("Errore caricamento articoli per macchina:", err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadInitialData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
await fetchNodes();
|
||||
await Promise.all([fetchNodes(), fetchArticoliPerMacchina()]);
|
||||
setLoading(false);
|
||||
}, [fetchNodes]);
|
||||
}, [fetchNodes, fetchArticoliPerMacchina]);
|
||||
|
||||
useEffect(() => {
|
||||
loadInitialData();
|
||||
|
|
@ -184,11 +222,81 @@ export default function MacchineTree() {
|
|||
};
|
||||
|
||||
const handleShowArticles = (nodeId: number) => {
|
||||
console.log("Show articles for node:", nodeId);
|
||||
const macchina = nodes.find((n) => n.id === nodeId);
|
||||
if (!macchina) return;
|
||||
|
||||
const articoliNodo = articlesByMacchina[nodeId] || [];
|
||||
|
||||
const getDescendantArticles = (id: number): ArticoloAssegnatoMacchina[] => {
|
||||
const children = nodes.filter((n) => n.id_padre === id);
|
||||
let result: ArticoloAssegnatoMacchina[] = [];
|
||||
for (const child of children) {
|
||||
const childArticles = articlesByMacchina[child.id] || [];
|
||||
result = [...result, ...childArticles, ...getDescendantArticles(child.id)];
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const allArticoli = [...articoliNodo, ...getDescendantArticles(nodeId)];
|
||||
|
||||
setShowArticlesModal({
|
||||
macchinaId: nodeId,
|
||||
macchinaNome: macchina.nome,
|
||||
articoli: allArticoli,
|
||||
});
|
||||
};
|
||||
|
||||
const handleDropArticle = (macchinaId: number, article: unknown) => {
|
||||
console.log("Drop article on machine:", macchinaId, article);
|
||||
const droppedArticle = article as DroppedArticle;
|
||||
if (!droppedArticle || droppedArticle.quantita_residua <= 0) return;
|
||||
|
||||
const macchina = nodes.find((n) => n.id === macchinaId);
|
||||
if (!macchina) return;
|
||||
|
||||
setDropModal({
|
||||
macchinaId,
|
||||
macchinaNome: macchina.nome,
|
||||
article: droppedArticle,
|
||||
});
|
||||
setDropQuantita(1);
|
||||
setDropCausale("");
|
||||
};
|
||||
|
||||
const handleConfirmDrop = async () => {
|
||||
if (!dropModal) return;
|
||||
|
||||
if (dropQuantita <= 0 || dropQuantita > dropModal.article.quantita_residua) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDropSaving(true);
|
||||
try {
|
||||
const res = await fetch("/api/art-macchine-parti/assegna", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
idart: dropModal.article.id,
|
||||
idmacchina: dropModal.macchinaId,
|
||||
quantita: dropQuantita,
|
||||
causale: dropCausale || `Assegnazione a ${dropModal.macchinaNome}`,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || "Errore nell'assegnazione");
|
||||
}
|
||||
|
||||
await fetchArticoliPerMacchina();
|
||||
setDropModal(null);
|
||||
|
||||
window.dispatchEvent(new CustomEvent("articoli-updated"));
|
||||
} catch (err) {
|
||||
console.error("Errore assegnazione:", err);
|
||||
alert(err instanceof Error ? err.message : "Errore nell'assegnazione");
|
||||
} finally {
|
||||
setDropSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredNodes = useMemo(() => {
|
||||
|
|
@ -368,6 +476,155 @@ export default function MacchineTree() {
|
|||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Show Articles Modal */}
|
||||
{showArticlesModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setShowArticlesModal(null)} />
|
||||
<div className="relative w-full max-w-lg max-h-[80vh] bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl flex flex-col">
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800 bg-teal-900/20">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-white">Articoli Assegnati</h3>
|
||||
<p className="text-xs text-zinc-500">{showArticlesModal.macchinaNome}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowArticlesModal(null)}
|
||||
className="p-1 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800"
|
||||
>
|
||||
<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>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
{showArticlesModal.articoli.length === 0 ? (
|
||||
<div className="text-center py-8 text-zinc-500">
|
||||
Nessun articolo assegnato
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{showArticlesModal.articoli.map((art) => (
|
||||
<div
|
||||
key={`${art.id_articolo}-${art.id}`}
|
||||
className="flex items-center justify-between p-3 rounded-lg bg-zinc-800/50 border border-zinc-700"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-white truncate">{art.descrizione}</p>
|
||||
<p className="text-xs text-zinc-500 font-mono">{art.codice}</p>
|
||||
</div>
|
||||
<div className="text-right ml-3">
|
||||
<div className="text-lg font-bold text-teal-400">{art.quantita}</div>
|
||||
<div className="text-[10px] text-zinc-600">assegnati</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="px-5 py-3 border-t border-zinc-800 bg-zinc-900/50 flex justify-between items-center">
|
||||
<span className="text-xs text-zinc-500">
|
||||
Totale: {showArticlesModal.articoli.reduce((sum, a) => sum + a.quantita, 0)} pezzi in {showArticlesModal.articoli.length} articoli
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setShowArticlesModal(null)}
|
||||
className="px-4 py-2 text-sm font-medium text-zinc-300 hover:text-white rounded-lg hover:bg-zinc-800"
|
||||
>
|
||||
Chiudi
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Drop Article Modal */}
|
||||
{dropModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setDropModal(null)} />
|
||||
<div className="relative w-full max-w-md bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl">
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800 bg-blue-900/20">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-white">Assegna Articolo</h3>
|
||||
<p className="text-xs text-zinc-500">Trascina e rilascia completato</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setDropModal(null)}
|
||||
className="p-1 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800"
|
||||
>
|
||||
<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>
|
||||
|
||||
<div className="p-5 space-y-4">
|
||||
{/* Info articolo */}
|
||||
<div className="p-3 rounded-lg bg-zinc-800/50 border border-zinc-700">
|
||||
<p className="text-xs text-zinc-500 mb-1">Articolo</p>
|
||||
<p className="font-medium text-white">{dropModal.article.descrizione}</p>
|
||||
<p className="text-xs text-zinc-500 font-mono">{dropModal.article.codice}</p>
|
||||
<p className="text-xs text-zinc-500 mt-1">
|
||||
Disponibili: <span className="text-green-400">{dropModal.article.quantita_residua}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Info destinazione */}
|
||||
<div className="p-3 rounded-lg bg-blue-900/20 border border-blue-700/50">
|
||||
<p className="text-xs text-zinc-500 mb-1">Destinazione</p>
|
||||
<p className="font-medium text-blue-300">{dropModal.macchinaNome}</p>
|
||||
</div>
|
||||
|
||||
{/* Quantità */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">Quantità</label>
|
||||
<input
|
||||
type="number"
|
||||
value={dropQuantita}
|
||||
onChange={(e) => setDropQuantita(Math.max(1, Math.min(dropModal.article.quantita_residua, parseInt(e.target.value) || 1)))}
|
||||
min={1}
|
||||
max={dropModal.article.quantita_residua}
|
||||
className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-lg font-semibold focus:outline-none focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Causale */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">Causale (opzionale)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={dropCausale}
|
||||
onChange={(e) => setDropCausale(e.target.value)}
|
||||
placeholder="Es: Manutenzione programmata"
|
||||
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"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-zinc-800">
|
||||
<button
|
||||
onClick={() => setDropModal(null)}
|
||||
className="px-4 py-2 text-sm font-medium text-zinc-300 hover:text-white rounded-lg hover:bg-zinc-800"
|
||||
>
|
||||
Annulla
|
||||
</button>
|
||||
<button
|
||||
onClick={handleConfirmDrop}
|
||||
disabled={dropSaving || dropQuantita <= 0}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-500 disabled:opacity-50 flex items-center gap-2"
|
||||
>
|
||||
{dropSaving && (
|
||||
<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>
|
||||
)}
|
||||
Assegna
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ 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";
|
||||
import type { MacchinaWithDetails } from "@/src/types/macchina";
|
||||
import DestinazioneModal from "./DestinazioneModal";
|
||||
|
||||
interface MovimentoModalProps {
|
||||
article: Article;
|
||||
|
|
@ -28,11 +30,16 @@ export default function MovimentoModal({
|
|||
const [quantita, setQuantita] = useState<number>(1);
|
||||
const [causale, setCausale] = useState<string>("");
|
||||
|
||||
const [selectedDestinazione, setSelectedDestinazione] = useState<MacchinaWithDetails | null>(null);
|
||||
const [showDestinazioneModal, setShowDestinazioneModal] = useState(false);
|
||||
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchData() {
|
||||
if (!isCarico) return;
|
||||
|
||||
try {
|
||||
const [stabRes, magRes] = await Promise.all([
|
||||
fetch("/api/stabilimenti"),
|
||||
|
|
@ -51,7 +58,7 @@ export default function MovimentoModal({
|
|||
}
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
}, [isCarico]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
|
|
@ -81,19 +88,32 @@ export default function MovimentoModal({
|
|||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (isCarico) {
|
||||
if (!selectedMagazzino) {
|
||||
setError("Seleziona un magazzino");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (!selectedDestinazione) {
|
||||
setError("Seleziona una destinazione (macchina/parte)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (quantita <= 0) {
|
||||
setError("La quantità deve essere maggiore di zero");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isCarico && quantita > article.quantita) {
|
||||
setError(`Quantità richiesta (${quantita}) supera la giacenza disponibile (${article.quantita})`);
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
|
||||
try {
|
||||
if (isCarico) {
|
||||
const res = await fetch("/api/movimenti", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
|
|
@ -110,6 +130,23 @@ export default function MovimentoModal({
|
|||
const data = await res.json();
|
||||
throw new Error(data.error || "Errore durante la registrazione");
|
||||
}
|
||||
} else {
|
||||
const res = await fetch("/api/art-macchine-parti/assegna", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
idart: article.id,
|
||||
idmacchina: selectedDestinazione!.id,
|
||||
quantita,
|
||||
causale: causale || `Scarico verso ${selectedDestinazione!.nome}`,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || "Errore durante l'assegnazione");
|
||||
}
|
||||
}
|
||||
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
|
|
@ -176,7 +213,9 @@ export default function MovimentoModal({
|
|||
</div>
|
||||
)}
|
||||
|
||||
{/* Stabilimento */}
|
||||
{/* Sezione CARICO: Stabilimento e Magazzino */}
|
||||
{isCarico && (
|
||||
<>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Stabilimento
|
||||
|
|
@ -198,11 +237,10 @@ export default function MovimentoModal({
|
|||
</select>
|
||||
</div>
|
||||
|
||||
{/* Magazzino */}
|
||||
{selectedStabilimento && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Magazzino {isCarico ? "(destinazione)" : "(origine)"}
|
||||
Magazzino (destinazione)
|
||||
</label>
|
||||
<select
|
||||
value={selectedMagazzino ?? ""}
|
||||
|
|
@ -218,6 +256,46 @@ export default function MovimentoModal({
|
|||
</select>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Sezione SCARICO: Destinazione Macchina/Parte */}
|
||||
{!isCarico && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Destinazione (Macchina/Parte) <span className="text-red-400">*</span>
|
||||
</label>
|
||||
|
||||
{selectedDestinazione ? (
|
||||
<div className="flex items-center justify-between p-3 rounded-lg bg-blue-900/20 border border-blue-700/50">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">
|
||||
{selectedDestinazione.tipo === "macchina" ? "🔧" : selectedDestinazione.tipo === "gruppo" ? "📁" : "⚙️"}
|
||||
</span>
|
||||
<span className="text-white font-medium">{selectedDestinazione.nome}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowDestinazioneModal(true)}
|
||||
className="px-3 py-1 text-xs rounded bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors"
|
||||
>
|
||||
Cambia
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowDestinazioneModal(true)}
|
||||
className="w-full px-4 py-3 rounded-lg bg-zinc-800 border-2 border-dashed border-zinc-600 text-zinc-400 hover:border-blue-500 hover:text-blue-400 transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
<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>
|
||||
Seleziona Destinazione
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quantità */}
|
||||
<div>
|
||||
|
|
@ -229,20 +307,26 @@ export default function MovimentoModal({
|
|||
value={quantita}
|
||||
onChange={(e) => setQuantita(parseFloat(e.target.value) || 0)}
|
||||
min="1"
|
||||
max={!isCarico ? article.quantita : undefined}
|
||||
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"
|
||||
/>
|
||||
{!isCarico && quantita > article.quantita && (
|
||||
<p className="mt-1 text-xs text-red-400">
|
||||
Quantità richiesta supera la giacenza disponibile ({article.quantita})
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Causale */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Causale (opzionale)
|
||||
Causale {!isCarico && <span className="text-zinc-600">(opzionale)</span>}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={causale}
|
||||
onChange={(e) => setCausale(e.target.value)}
|
||||
placeholder={isCarico ? "Es: Acquisto fornitore" : "Es: Utilizzo manutenzione"}
|
||||
placeholder={isCarico ? "Es: Acquisto fornitore" : "Es: Manutenzione programmata"}
|
||||
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>
|
||||
|
|
@ -258,7 +342,7 @@ export default function MovimentoModal({
|
|||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving || !selectedMagazzino}
|
||||
disabled={saving || (isCarico ? !selectedMagazzino : !selectedDestinazione)}
|
||||
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"
|
||||
|
|
@ -276,6 +360,17 @@ export default function MovimentoModal({
|
|||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Modal Selezione Destinazione */}
|
||||
<DestinazioneModal
|
||||
isOpen={showDestinazioneModal}
|
||||
onClose={() => setShowDestinazioneModal(false)}
|
||||
onSelect={(macchina) => {
|
||||
setSelectedDestinazione(macchina);
|
||||
setShowDestinazioneModal(false);
|
||||
}}
|
||||
selectedId={selectedDestinazione?.id}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
"use client";
|
||||
|
||||
import { useState, type DragEvent } from "react";
|
||||
import type { MacchinaWithDetails, ArticoliPerMacchina } from "@/src/types/macchina";
|
||||
import type { MacchinaWithDetails } from "@/src/types/macchina";
|
||||
import type { ArticoloAssegnatoMacchina } from "@/src/types/artMacchineParti";
|
||||
|
||||
function toRgb(color: string | null | undefined): { r: number; g: number; b: number } | null {
|
||||
if (!color || typeof color !== "string") return null;
|
||||
|
|
@ -45,7 +46,7 @@ interface TreeNodeProps {
|
|||
node: MacchinaWithDetails;
|
||||
allNodes: MacchinaWithDetails[];
|
||||
level?: number;
|
||||
articlesByMacchina?: ArticoliPerMacchina;
|
||||
articlesByMacchina?: Record<number, ArticoloAssegnatoMacchina[]>;
|
||||
isCloning?: boolean;
|
||||
copiedNodeId?: number | null;
|
||||
onAdd: (parentId: number) => void;
|
||||
|
|
|
|||
172
src/lib/artMacchineParti/index.ts
Normal file
172
src/lib/artMacchineParti/index.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
import type { RowDataPacket, ResultSetHeader } from "mysql2";
|
||||
|
||||
import { db } from "@/src/lib/db";
|
||||
import type {
|
||||
ArtMacchinaParte,
|
||||
ArticoloAssegnatoMacchina,
|
||||
AssegnaArticoloInput,
|
||||
} from "@/src/types/artMacchineParti";
|
||||
|
||||
type ArtMacchinaParteRow = ArtMacchinaParte & RowDataPacket;
|
||||
|
||||
export async function getArticoliByMacchina(
|
||||
idmacchina: number
|
||||
): Promise<ArticoloAssegnatoMacchina[]> {
|
||||
const [rows] = await db.execute<ArtMacchinaParteRow[]>(
|
||||
`SELECT
|
||||
id, idart, descrizione, codice, barcode,
|
||||
idmacchina, qtain, qtaout, created_at, updated_at
|
||||
FROM art_macchine_parti
|
||||
WHERE idmacchina = :idmacchina`,
|
||||
{ idmacchina }
|
||||
);
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
id_articolo: row.idart,
|
||||
descrizione: row.descrizione,
|
||||
codice: row.codice,
|
||||
barcode: row.barcode,
|
||||
quantita: Math.max(0, row.qtain - row.qtaout),
|
||||
qtain: row.qtain,
|
||||
qtaout: row.qtaout,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function assegnaArticoloMacchina(
|
||||
input: AssegnaArticoloInput
|
||||
): Promise<{ success: boolean; message: string }> {
|
||||
const { idart, idmacchina, quantita, causale = "Assegnazione articolo", user = "system" } = input;
|
||||
|
||||
const [articoloRows] = await db.execute<(RowDataPacket & { descrizione: string; codice: string; barcode: string | null })[]>(
|
||||
"SELECT descrizione, codice, barcode FROM articoli WHERE id = :idart LIMIT 1",
|
||||
{ idart }
|
||||
);
|
||||
|
||||
if (articoloRows.length === 0) {
|
||||
throw new Error("Articolo non trovato");
|
||||
}
|
||||
|
||||
const articolo = articoloRows[0];
|
||||
|
||||
const [existingRows] = await db.execute<(RowDataPacket & { id: number })[]>(
|
||||
"SELECT id FROM art_macchine_parti WHERE idart = :idart AND idmacchina = :idmacchina LIMIT 1",
|
||||
{ idart, idmacchina }
|
||||
);
|
||||
|
||||
if (existingRows.length > 0) {
|
||||
await db.execute(
|
||||
`UPDATE art_macchine_parti
|
||||
SET qtain = qtain + :quantita, updated_at = NOW()
|
||||
WHERE idart = :idart AND idmacchina = :idmacchina`,
|
||||
{ quantita, idart, idmacchina }
|
||||
);
|
||||
} else {
|
||||
await db.execute(
|
||||
`INSERT INTO art_macchine_parti (idart, descrizione, codice, barcode, idmacchina, qtain, qtaout)
|
||||
VALUES (:idart, :descrizione, :codice, :barcode, :idmacchina, :quantita, 0)`,
|
||||
{
|
||||
idart,
|
||||
descrizione: articolo.descrizione,
|
||||
codice: articolo.codice,
|
||||
barcode: articolo.barcode,
|
||||
idmacchina,
|
||||
quantita,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
await db.execute(
|
||||
`INSERT INTO movimenti (id_articolo, quantita, tipo, causale, user, id_macchina_parte, data_movimento)
|
||||
VALUES (:id_articolo, :quantita, 'scarico', :causale, :user, :id_macchina_parte, NOW())`,
|
||||
{
|
||||
id_articolo: idart,
|
||||
quantita,
|
||||
causale,
|
||||
user,
|
||||
id_macchina_parte: idmacchina,
|
||||
}
|
||||
);
|
||||
|
||||
return { success: true, message: "Articolo assegnato con successo" };
|
||||
}
|
||||
|
||||
export async function rimuoviArticoloDaMacchina(
|
||||
idart: number,
|
||||
idmacchina: number,
|
||||
quantita: number,
|
||||
opzione: "carico" | "elimina",
|
||||
user: string = "system"
|
||||
): Promise<{ success: boolean; message: string }> {
|
||||
const [existingRows] = await db.execute<(RowDataPacket & { id: number; qtain: number; qtaout: number })[]>(
|
||||
"SELECT id, qtain, qtaout FROM art_macchine_parti WHERE idart = :idart AND idmacchina = :idmacchina LIMIT 1",
|
||||
{ idart, idmacchina }
|
||||
);
|
||||
|
||||
if (existingRows.length === 0) {
|
||||
throw new Error("Assegnazione non trovata");
|
||||
}
|
||||
|
||||
const existing = existingRows[0];
|
||||
const quantitaDisponibile = existing.qtain - existing.qtaout;
|
||||
|
||||
if (quantita > quantitaDisponibile) {
|
||||
throw new Error(`Quantità richiesta (${quantita}) supera quella disponibile (${quantitaDisponibile})`);
|
||||
}
|
||||
|
||||
await db.execute(
|
||||
`UPDATE art_macchine_parti
|
||||
SET qtaout = qtaout + :quantita, updated_at = NOW()
|
||||
WHERE idart = :idart AND idmacchina = :idmacchina`,
|
||||
{ quantita, idart, idmacchina }
|
||||
);
|
||||
|
||||
if (opzione === "carico") {
|
||||
await db.execute(
|
||||
`INSERT INTO movimenti (id_articolo, quantita, tipo, causale, user, data_movimento)
|
||||
VALUES (:id_articolo, :quantita, 'carico', :causale, :user, NOW())`,
|
||||
{
|
||||
id_articolo: idart,
|
||||
quantita,
|
||||
causale: "Rientro da macchina",
|
||||
user,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return { success: true, message: opzione === "carico" ? "Articolo rientrato in magazzino" : "Articolo rimosso" };
|
||||
}
|
||||
|
||||
export async function getArticoliPerTutteLeMacchine(): Promise<Record<number, ArticoloAssegnatoMacchina[]>> {
|
||||
const [rows] = await db.execute<ArtMacchinaParteRow[]>(
|
||||
`SELECT
|
||||
id, idart, descrizione, codice, barcode,
|
||||
idmacchina, qtain, qtaout, created_at, updated_at
|
||||
FROM art_macchine_parti
|
||||
WHERE (qtain - qtaout) > 0`
|
||||
);
|
||||
|
||||
const result: Record<number, ArticoloAssegnatoMacchina[]> = {};
|
||||
|
||||
for (const row of rows) {
|
||||
const quantita = Math.max(0, row.qtain - row.qtaout);
|
||||
if (quantita <= 0) continue;
|
||||
|
||||
if (!result[row.idmacchina]) {
|
||||
result[row.idmacchina] = [];
|
||||
}
|
||||
|
||||
result[row.idmacchina].push({
|
||||
id: row.id,
|
||||
id_articolo: row.idart,
|
||||
descrizione: row.descrizione,
|
||||
codice: row.codice,
|
||||
barcode: row.barcode,
|
||||
quantita,
|
||||
qtain: row.qtain,
|
||||
qtaout: row.qtaout,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
37
src/types/artMacchineParti.ts
Normal file
37
src/types/artMacchineParti.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
export interface ArtMacchinaParte {
|
||||
id: number;
|
||||
idart: number;
|
||||
descrizione: string;
|
||||
codice: string;
|
||||
barcode: string | null;
|
||||
idmacchina: number;
|
||||
qtain: number;
|
||||
qtaout: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ArticoloAssegnatoMacchina {
|
||||
id: number;
|
||||
id_articolo: number;
|
||||
descrizione: string;
|
||||
codice: string;
|
||||
barcode: string | null;
|
||||
quantita: number;
|
||||
qtain: number;
|
||||
qtaout: number;
|
||||
}
|
||||
|
||||
export interface AssegnaArticoloInput {
|
||||
idart: number;
|
||||
idmacchina: number;
|
||||
quantita: number;
|
||||
causale?: string;
|
||||
user?: string;
|
||||
}
|
||||
|
||||
export interface RimuoviArticoloInput {
|
||||
quantita: number;
|
||||
opzione: "carico" | "elimina";
|
||||
user?: string;
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue