fix: product merge unique constraint, partial payment KPI calculations, input clearing UX, PO deletion, and table pagination
This commit is contained in:
1 parent
ad678cd06e
commit
f895f522d0
7 files changed
+611
-183
No files matched your search
@@ -346,15 +346,40 @@ export async function PUT(req: Request) {
|
||||
data: { productId: target.id },
|
||||
});
|
||||
|
||||
await prisma.purchaseRequisitionItem.updateMany({
|
||||
where: { productId: source.id },
|
||||
data: { productId: target.id },
|
||||
});
|
||||
|
||||
await prisma.salesOrderItem.updateMany({
|
||||
where: { productId: source.id },
|
||||
data: { productId: target.id },
|
||||
});
|
||||
|
||||
await prisma.customerProductPrice.updateMany({
|
||||
// Pindahkan harga khusus pelanggan (customerProductPrice) dengan aman tanpa melanggar unique constraint
|
||||
const sourcePrices = await prisma.customerProductPrice.findMany({
|
||||
where: { productId: source.id },
|
||||
data: { productId: target.id },
|
||||
});
|
||||
for (const sp of sourcePrices) {
|
||||
const existingTargetPrice = await prisma.customerProductPrice.findUnique({
|
||||
where: {
|
||||
customerId_productId: {
|
||||
customerId: sp.customerId,
|
||||
productId: target.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (existingTargetPrice) {
|
||||
// Jika target sudah punya harga khusus untuk customer ini, hapus data lama dari source
|
||||
await prisma.customerProductPrice.delete({ where: { id: sp.id } });
|
||||
} else {
|
||||
// Pindahkan harga khusus source ke target
|
||||
await prisma.customerProductPrice.update({
|
||||
where: { id: sp.id },
|
||||
data: { productId: target.id },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Catat mutasi penggabungan
|
||||
const defaultWh = await prisma.warehouse.findFirst();
|
||||
@@ -520,9 +545,9 @@ export async function DELETE(req: Request) {
|
||||
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
|
||||
}
|
||||
|
||||
if (user.role !== "ADMIN") {
|
||||
if (user.role !== "ADMIN" && user.role !== "MANAGER") {
|
||||
return NextResponse.json(
|
||||
{ error: "Akses ditolak: Hanya Superadmin (ADMIN) yang dapat menghapus produk." },
|
||||
{ error: "Akses ditolak: Hanya Superadmin (ADMIN) atau Manager yang dapat menghapus produk." },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1188,43 +1188,71 @@ export async function DELETE(req: Request) {
|
||||
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
|
||||
}
|
||||
|
||||
if (user.role !== "ADMIN") {
|
||||
if (user.role !== "ADMIN" && user.role !== "MANAGER") {
|
||||
return NextResponse.json(
|
||||
{ error: "Akses ditolak: Hanya Superadmin (ADMIN) yang memiliki wewenang menghapus data pembelian." },
|
||||
{ error: "Akses ditolak: Hanya Superadmin (ADMIN) atau Manager yang memiliki wewenang menghapus data pembelian." },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const id = searchParams.get("id");
|
||||
const type = searchParams.get("type") || "po"; // "po" or "pr"
|
||||
const type = searchParams.get("type") || "po"; // "po", "pr", or "batch"
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "ID transaksi wajib disertakan" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (type === "pr") {
|
||||
const pr = await prisma.purchaseRequisition.findUnique({ where: { id } });
|
||||
const pr = await prisma.purchaseRequisition.findFirst({
|
||||
where: { OR: [{ id }, { reqNumber: id }] },
|
||||
});
|
||||
if (!pr) return NextResponse.json({ error: "Pengajuan PR tidak ditemukan" }, { status: 404 });
|
||||
|
||||
await prisma.purchaseRequisitionItem.deleteMany({ where: { requisitionId: id } });
|
||||
await prisma.purchaseRequisition.delete({ where: { id } });
|
||||
await prisma.purchaseRequisitionItem.deleteMany({ where: { requisitionId: pr.id } });
|
||||
await prisma.purchaseOrder.updateMany({
|
||||
where: { requisitionId: pr.id },
|
||||
data: { requisitionId: null },
|
||||
});
|
||||
await prisma.purchaseRequisition.delete({ where: { id: pr.id } });
|
||||
|
||||
await logAudit({
|
||||
userId: user.id,
|
||||
userName: user.name,
|
||||
action: "DELETE",
|
||||
module: "PURCHASING",
|
||||
description: `[SUPERADMIN] Menghapus Pengajuan Pembelian PR ${pr.reqNumber}`,
|
||||
metadata: { requisitionId: id, reqNumber: pr.reqNumber },
|
||||
description: `[${user.role}] Menghapus Pengajuan Pembelian PR ${pr.reqNumber}`,
|
||||
metadata: { requisitionId: pr.id, reqNumber: pr.reqNumber },
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, message: `PR ${pr.reqNumber} berhasil dihapus.` });
|
||||
}
|
||||
|
||||
// Default: PO Vendor
|
||||
const po = await prisma.purchaseOrder.findUnique({
|
||||
where: { id },
|
||||
if (type === "batch") {
|
||||
const batch = await prisma.purchaseBatch.findUnique({
|
||||
where: { id },
|
||||
include: { purchaseOrder: true },
|
||||
});
|
||||
if (!batch) return NextResponse.json({ error: "Batch PO tidak ditemukan" }, { status: 404 });
|
||||
|
||||
await prisma.salesItemBatchAllocation.deleteMany({ where: { purchaseBatchId: batch.id } });
|
||||
await prisma.purchaseBatch.delete({ where: { id: batch.id } });
|
||||
|
||||
await logAudit({
|
||||
userId: user.id,
|
||||
userName: user.name,
|
||||
action: "DELETE_BATCH",
|
||||
module: "PURCHASING",
|
||||
description: `[${user.role}] Menghapus Batch FIFO PO ${batch.poNumber} (${batch.productId})`,
|
||||
metadata: { batchId: batch.id, poNumber: batch.poNumber },
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, message: `Batch ${batch.poNumber} berhasil dihapus.` });
|
||||
}
|
||||
|
||||
// Default: PO Vendor (cari berdasarkan ID UUID atau poNumber)
|
||||
const po = await prisma.purchaseOrder.findFirst({
|
||||
where: { OR: [{ id }, { poNumber: id }] },
|
||||
include: { batches: true, items: true },
|
||||
});
|
||||
if (!po) return NextResponse.json({ error: "PO Vendor tidak ditemukan" }, { status: 404 });
|
||||
@@ -1233,26 +1261,31 @@ export async function DELETE(req: Request) {
|
||||
for (const b of po.batches) {
|
||||
await prisma.salesItemBatchAllocation.deleteMany({ where: { purchaseBatchId: b.id } });
|
||||
}
|
||||
await prisma.purchaseBatch.deleteMany({ where: { purchaseOrderId: id } });
|
||||
await prisma.purchaseOrderItem.deleteMany({ where: { purchaseOrderId: id } });
|
||||
await prisma.purchaseBatch.deleteMany({ where: { purchaseOrderId: po.id } });
|
||||
await prisma.purchaseOrderItem.deleteMany({ where: { purchaseOrderId: po.id } });
|
||||
|
||||
await prisma.stockMovement.deleteMany({
|
||||
where: { referenceType: "PURCHASE_ORDER", referenceId: po.poNumber },
|
||||
});
|
||||
|
||||
await prisma.journalEntry.deleteMany({
|
||||
const entries = await prisma.journalEntry.findMany({
|
||||
where: { reference: po.poNumber },
|
||||
select: { id: true },
|
||||
});
|
||||
for (const entry of entries) {
|
||||
await prisma.journalLine.deleteMany({ where: { journalEntryId: entry.id } });
|
||||
await prisma.journalEntry.delete({ where: { id: entry.id } });
|
||||
}
|
||||
|
||||
await prisma.purchaseOrder.delete({ where: { id } });
|
||||
await prisma.purchaseOrder.delete({ where: { id: po.id } });
|
||||
|
||||
await logAudit({
|
||||
userId: user.id,
|
||||
userName: user.name,
|
||||
action: "DELETE",
|
||||
module: "PURCHASING",
|
||||
description: `[SUPERADMIN] Menghapus PO Vendor ${po.poNumber} senilai Rp ${po.totalAmount.toLocaleString("id-ID")}`,
|
||||
metadata: { purchaseOrderId: id, poNumber: po.poNumber },
|
||||
description: `[${user.role}] Menghapus PO Vendor ${po.poNumber} senilai Rp ${po.totalAmount.toLocaleString("id-ID")}`,
|
||||
metadata: { purchaseOrderId: po.id, poNumber: po.poNumber },
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, message: `PO Vendor ${po.poNumber} berhasil dihapus.` });
|
||||
|
||||
@@ -1106,9 +1106,9 @@ export async function DELETE(req: Request) {
|
||||
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
|
||||
}
|
||||
|
||||
if (user.role !== "ADMIN") {
|
||||
if (user.role !== "ADMIN" && user.role !== "MANAGER") {
|
||||
return NextResponse.json(
|
||||
{ error: "Akses ditolak: Hanya Superadmin (ADMIN) yang memiliki wewenang menghapus Sales Order." },
|
||||
{ error: "Akses ditolak: Hanya Superadmin (ADMIN) atau Manager yang memiliki wewenang menghapus Sales Order." },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
@@ -1119,8 +1119,8 @@ export async function DELETE(req: Request) {
|
||||
return NextResponse.json({ error: "ID pesanan penjualan wajib disertakan" }, { status: 400 });
|
||||
}
|
||||
|
||||
const order = await prisma.salesOrder.findUnique({
|
||||
where: { id },
|
||||
const order = await prisma.salesOrder.findFirst({
|
||||
where: { OR: [{ id }, { orderNumber: id }] },
|
||||
include: { items: true },
|
||||
});
|
||||
|
||||
@@ -1128,24 +1128,37 @@ export async function DELETE(req: Request) {
|
||||
return NextResponse.json({ error: "Pesanan penjualan tidak ditemukan" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Bersihkan alokasi batch jika ada
|
||||
for (const item of order.items) {
|
||||
await prisma.salesItemBatchAllocation.deleteMany({
|
||||
where: { salesOrderItemId: item.id },
|
||||
});
|
||||
}
|
||||
|
||||
// Bersihkan mutasi stok dan jurnal terkait SO ini
|
||||
await prisma.stockMovement.deleteMany({
|
||||
where: { referenceType: "SALES_ORDER", referenceId: order.orderNumber },
|
||||
});
|
||||
|
||||
await prisma.journalEntry.deleteMany({
|
||||
const entries = await prisma.journalEntry.findMany({
|
||||
where: { reference: order.orderNumber },
|
||||
select: { id: true },
|
||||
});
|
||||
for (const entry of entries) {
|
||||
await prisma.journalLine.deleteMany({ where: { journalEntryId: entry.id } });
|
||||
await prisma.journalEntry.delete({ where: { id: entry.id } });
|
||||
}
|
||||
|
||||
await prisma.salesOrder.delete({ where: { id } });
|
||||
await prisma.salesOrderItem.deleteMany({ where: { salesOrderId: order.id } });
|
||||
await prisma.salesOrder.delete({ where: { id: order.id } });
|
||||
|
||||
await logAudit({
|
||||
userId: user.id,
|
||||
userName: user.name,
|
||||
action: "DELETE",
|
||||
module: "SALES",
|
||||
description: `[SUPERADMIN] Menghapus Sales Order ${order.orderNumber} senilai Rp ${order.totalAmount.toLocaleString("id-ID")} secara permanen`,
|
||||
metadata: { orderId: id, orderNumber: order.orderNumber },
|
||||
description: `[${user.role}] Menghapus Sales Order ${order.orderNumber} senilai Rp ${order.totalAmount.toLocaleString("id-ID")} secara permanen`,
|
||||
metadata: { orderId: order.id, orderNumber: order.orderNumber },
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
|
||||
+87
-23
@@ -3,6 +3,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { Pagination } from "@/components/Pagination";
|
||||
import { formatRupiah, formatDateTime, exportToCSV } from "@/lib/utils";
|
||||
import {
|
||||
Boxes,
|
||||
@@ -35,6 +36,12 @@ export default function InventoryPage() {
|
||||
const [selectedCategory, setSelectedCategory] = useState("ALL");
|
||||
const [activeTab, setActiveTab] = useState<"catalog" | "movements">("catalog");
|
||||
|
||||
// Pagination States (Default 5 items, pilihan 5, 10, 25, 50)
|
||||
const [prodPage, setProdPage] = useState(1);
|
||||
const [prodPageSize, setProdPageSize] = useState(5);
|
||||
const [movPage, setMovPage] = useState(1);
|
||||
const [movPageSize, setMovPageSize] = useState(5);
|
||||
|
||||
// Modals state
|
||||
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
|
||||
const [isAdjustModalOpen, setIsAdjustModalOpen] = useState(false);
|
||||
@@ -43,7 +50,17 @@ export default function InventoryPage() {
|
||||
const [selectedProduct, setSelectedProduct] = useState<any>(null);
|
||||
|
||||
// Edit Product state
|
||||
const [editProductData, setEditProductData] = useState({
|
||||
const [editProductData, setEditProductData] = useState<{
|
||||
id: string;
|
||||
sku: string;
|
||||
name: string;
|
||||
description: string;
|
||||
unit: string;
|
||||
purchasePrice: number | string;
|
||||
sellingPrice: number | string;
|
||||
minStock: number | string;
|
||||
categoryId: string;
|
||||
}>({
|
||||
id: "",
|
||||
sku: "",
|
||||
name: "",
|
||||
@@ -64,7 +81,19 @@ export default function InventoryPage() {
|
||||
const [newCatName, setNewCatName] = useState("");
|
||||
|
||||
// Form states
|
||||
const [newProduct, setNewProduct] = useState({
|
||||
const [newProduct, setNewProduct] = useState<{
|
||||
sku: string;
|
||||
name: string;
|
||||
description: string;
|
||||
isService: boolean;
|
||||
unit: string;
|
||||
purchasePrice: number | string;
|
||||
sellingPrice: number | string;
|
||||
minStock: number | string;
|
||||
categoryId: string;
|
||||
warehouseId: string;
|
||||
initialQuantity: number | string;
|
||||
}>({
|
||||
sku: "",
|
||||
name: "",
|
||||
description: "",
|
||||
@@ -176,10 +205,18 @@ export default function InventoryPage() {
|
||||
setFormError(null);
|
||||
|
||||
try {
|
||||
const cleanProduct = {
|
||||
...newProduct,
|
||||
purchasePrice: typeof newProduct.purchasePrice === "string" ? parseFloat(newProduct.purchasePrice) || 0 : newProduct.purchasePrice,
|
||||
sellingPrice: typeof newProduct.sellingPrice === "string" ? parseFloat(newProduct.sellingPrice) || 0 : newProduct.sellingPrice,
|
||||
minStock: typeof newProduct.minStock === "string" ? parseInt(newProduct.minStock) || 0 : newProduct.minStock,
|
||||
initialQuantity: typeof newProduct.initialQuantity === "string" ? parseInt(newProduct.initialQuantity) || 0 : newProduct.initialQuantity,
|
||||
};
|
||||
|
||||
const res = await fetch("/api/inventory", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(newProduct),
|
||||
body: JSON.stringify(cleanProduct),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
@@ -365,6 +402,10 @@ export default function InventoryPage() {
|
||||
return true;
|
||||
});
|
||||
|
||||
// Pagination Slices (Default 5 items, pilihan 5, 10, 25, 50)
|
||||
const paginatedProducts = filteredProducts.slice((prodPage - 1) * prodPageSize, prodPage * prodPageSize);
|
||||
const paginatedMovements = filteredMovements.slice((movPage - 1) * movPageSize, movPage * movPageSize);
|
||||
|
||||
const totalPhysicalUnits = products.reduce((s, p) => s + getProductStockForPT(p), 0);
|
||||
const lowStockCount = products.filter((p) => getProductStockForPT(p) <= p.minStock).length;
|
||||
|
||||
@@ -585,14 +626,14 @@ export default function InventoryPage() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{filteredProducts.length === 0 ? (
|
||||
{paginatedProducts.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="py-8 text-center text-slate-400">
|
||||
Belum ada produk yang terdaftar atau cocok dengan pencarian.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredProducts.map((p) => {
|
||||
paginatedProducts.map((p) => {
|
||||
const pStock = getProductStockForPT(p);
|
||||
const isLow = !p.isService && pStock <= p.minStock;
|
||||
const relevantStockItems = (p.stockItems || []).filter((s: any) =>
|
||||
@@ -709,11 +750,11 @@ export default function InventoryPage() {
|
||||
<span>Mutasi Stok</span>
|
||||
</button>
|
||||
)}
|
||||
{currentUser?.role === "ADMIN" && (
|
||||
{(currentUser?.role === "ADMIN" || currentUser?.role === "MANAGER") && (
|
||||
<button
|
||||
onClick={() => handleDeleteProduct(p)}
|
||||
className="inline-flex items-center gap-1 px-2 py-1.5 rounded-md bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 transition-colors text-xs font-medium"
|
||||
title="Hapus Produk Secara Permanen (Superadmin)"
|
||||
title="Hapus Produk Secara Permanen (Superadmin/Manager)"
|
||||
>
|
||||
<Trash2 className="h-3 w-3 text-rose-600" />
|
||||
<span>Hapus</span>
|
||||
@@ -729,6 +770,16 @@ export default function InventoryPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination Katalog Produk */}
|
||||
<Pagination
|
||||
currentPage={prodPage}
|
||||
totalItems={filteredProducts.length}
|
||||
pageSize={prodPageSize}
|
||||
onPageChange={setProdPage}
|
||||
onPageSizeChange={setProdPageSize}
|
||||
pageSizeOptions={[5, 10, 25, 50]}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
|
||||
@@ -745,14 +796,14 @@ export default function InventoryPage() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{filteredMovements.length === 0 ? (
|
||||
{paginatedMovements.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="py-8 text-center text-slate-400">
|
||||
Belum ada riwayat mutasi stok barang.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredMovements.map((m) => (
|
||||
paginatedMovements.map((m) => (
|
||||
<tr key={m.id} className="hover:bg-slate-50/60 transition-colors">
|
||||
<td className="py-3 px-6 text-slate-500">
|
||||
{formatDateTime(m.createdAt)}
|
||||
@@ -825,6 +876,16 @@ export default function InventoryPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination Mutasi Stok */}
|
||||
<Pagination
|
||||
currentPage={movPage}
|
||||
totalItems={filteredMovements.length}
|
||||
pageSize={movPageSize}
|
||||
onPageChange={setMovPage}
|
||||
onPageSizeChange={setMovPageSize}
|
||||
pageSizeOptions={[5, 10, 25, 50]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -977,10 +1038,11 @@ export default function InventoryPage() {
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
value={newProduct.minStock}
|
||||
onChange={(e) =>
|
||||
setNewProduct({ ...newProduct, minStock: parseInt(e.target.value) || 0 })
|
||||
}
|
||||
value={newProduct.minStock === "" ? "" : newProduct.minStock}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setNewProduct({ ...newProduct, minStock: v === "" ? "" : parseInt(v) || 0 });
|
||||
}}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
@@ -995,13 +1057,14 @@ export default function InventoryPage() {
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
value={newProduct.purchasePrice}
|
||||
onChange={(e) =>
|
||||
value={newProduct.purchasePrice === "" ? "" : newProduct.purchasePrice}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setNewProduct({
|
||||
...newProduct,
|
||||
purchasePrice: parseFloat(e.target.value) || 0,
|
||||
})
|
||||
}
|
||||
purchasePrice: v === "" ? "" : parseFloat(v) || 0,
|
||||
});
|
||||
}}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
@@ -1012,13 +1075,14 @@ export default function InventoryPage() {
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
value={newProduct.sellingPrice}
|
||||
onChange={(e) =>
|
||||
value={newProduct.sellingPrice === "" ? "" : newProduct.sellingPrice}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setNewProduct({
|
||||
...newProduct,
|
||||
sellingPrice: parseFloat(e.target.value) || 0,
|
||||
})
|
||||
}
|
||||
sellingPrice: v === "" ? "" : parseFloat(v) || 0,
|
||||
});
|
||||
}}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-semibold text-blue-700"
|
||||
/>
|
||||
</div>
|
||||
|
||||
+191
-74
@@ -4,6 +4,7 @@ import { useEffect, useState, useRef } from "react";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { StatusBadge } from "@/components/Badge";
|
||||
import { Pagination } from "@/components/Pagination";
|
||||
import { formatRupiah, formatDateTime, exportToCSV, escapeHtml, cn } from "@/lib/utils";
|
||||
import {
|
||||
Truck,
|
||||
@@ -76,13 +77,23 @@ export default function PurchasesPage() {
|
||||
|
||||
// Modal Pengajuan Sales (Requisition)
|
||||
const [isReqModalOpen, setIsReqModalOpen] = useState(false);
|
||||
// Pagination States (Default 5 items, pilihan 5, 10, 25, 50)
|
||||
const [poPage, setPoPage] = useState(1);
|
||||
const [poPageSize, setPoPageSize] = useState(5);
|
||||
|
||||
const [reqPage, setReqPage] = useState(1);
|
||||
const [reqPageSize, setReqPageSize] = useState(5);
|
||||
|
||||
const [batchPage, setBatchPage] = useState(1);
|
||||
const [batchPageSize, setBatchPageSize] = useState(5);
|
||||
|
||||
const [reqCustomerId, setReqCustomerId] = useState("");
|
||||
const [reqCustomCompany, setReqCustomCompany] = useState("");
|
||||
const [reqPurpose, setReqPurpose] = useState("");
|
||||
const [reqCustomerPoRef, setReqCustomerPoRef] = useState("");
|
||||
const [reqUrgency, setReqUrgency] = useState<"LOW" | "NORMAL" | "HIGH" | "URGENT">("NORMAL");
|
||||
const [reqNotes, setReqNotes] = useState("");
|
||||
const [reqItems, setReqItems] = useState<{ productId: string; quantity: number; notes: string }[]>([
|
||||
const [reqItems, setReqItems] = useState<{ productId: string; quantity: number | string; notes: string }[]>([
|
||||
{ productId: "", quantity: 1, notes: "" },
|
||||
]);
|
||||
const [reqSubmitting, setReqSubmitting] = useState(false);
|
||||
@@ -109,18 +120,18 @@ export default function PurchasesPage() {
|
||||
const [selectedReqId, setSelectedReqId] = useState<string | null>(null);
|
||||
const [customPoNumber, setCustomPoNumber] = useState("");
|
||||
const [currency, setCurrency] = useState<"IDR" | "USD">("IDR");
|
||||
const [exchangeRate, setExchangeRate] = useState<number>(16250);
|
||||
const [exchangeRate, setExchangeRate] = useState<number | string>(16250);
|
||||
const [logisticsMode, setLogisticsMode] = useState<"DETAILED" | "ASSISTED_ALL_IN">("DETAILED");
|
||||
const [forwardingCompanyInput, setForwardingCompanyInput] = useState("");
|
||||
const [allInCostInput, setAllInCostInput] = useState<number>(0);
|
||||
const [shippingCostInput, setShippingCostInput] = useState<number>(0);
|
||||
const [exportCostInput, setExportCostInput] = useState<number>(0);
|
||||
const [allInCostInput, setAllInCostInput] = useState<number | string>(0);
|
||||
const [shippingCostInput, setShippingCostInput] = useState<number | string>(0);
|
||||
const [exportCostInput, setExportCostInput] = useState<number | string>(0);
|
||||
const [supplierId, setSupplierId] = useState("");
|
||||
const [warehouseId, setWarehouseId] = useState("");
|
||||
const [autoReceive, setAutoReceive] = useState(false);
|
||||
const [notes, setNotes] = useState("");
|
||||
const [items, setItems] = useState<
|
||||
{ productId: string; quantity: number; unitCost: number; unitCostUsd?: number }[]
|
||||
{ productId: string; quantity: number | string; unitCost: number | string; unitCostUsd?: number | string }[]
|
||||
>([{ productId: "", quantity: 1, unitCost: 0, unitCostUsd: 0 }]);
|
||||
|
||||
const loadData = async () => {
|
||||
@@ -271,7 +282,12 @@ export default function PurchasesPage() {
|
||||
setReqSubmitting(true);
|
||||
setFormError(null);
|
||||
|
||||
const invalid = reqItems.some((it) => !it.productId || it.quantity <= 0);
|
||||
const cleanReqItems = reqItems.map((it) => ({
|
||||
...it,
|
||||
quantity: typeof it.quantity === "string" ? parseInt(it.quantity) || 0 : it.quantity,
|
||||
}));
|
||||
|
||||
const invalid = cleanReqItems.some((it) => !it.productId || it.quantity <= 0);
|
||||
if (invalid) {
|
||||
setFormError("Pastikan semua item memilih produk katalog dan kuantitas lebih dari 0");
|
||||
setReqSubmitting(false);
|
||||
@@ -298,7 +314,7 @@ export default function PurchasesPage() {
|
||||
customerPoRef: reqCustomerPoRef,
|
||||
urgency: reqUrgency,
|
||||
notes: reqNotes,
|
||||
items: reqItems,
|
||||
items: cleanReqItems,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -343,7 +359,7 @@ export default function PurchasesPage() {
|
||||
productId: it.productId,
|
||||
quantity: it.requestedQty || 1,
|
||||
unitCost: cost,
|
||||
unitCostUsd: exchangeRate > 0 ? Number((cost / exchangeRate).toFixed(2)) : 0,
|
||||
unitCostUsd: Number(exchangeRate) > 0 ? Number((cost / Number(exchangeRate)).toFixed(2)) : 0,
|
||||
};
|
||||
});
|
||||
setItems(convertedItems);
|
||||
@@ -398,46 +414,49 @@ export default function PurchasesPage() {
|
||||
updated[index].productId = pId;
|
||||
const defaultCost = selectedProd ? selectedProd.purchasePrice : 0;
|
||||
updated[index].unitCost = defaultCost;
|
||||
updated[index].unitCostUsd = exchangeRate > 0 ? Number((defaultCost / exchangeRate).toFixed(2)) : 0;
|
||||
updated[index].unitCostUsd = Number(exchangeRate) > 0 ? Number((defaultCost / Number(exchangeRate)).toFixed(2)) : 0;
|
||||
setItems(updated);
|
||||
};
|
||||
|
||||
const calculateProductsSubtotalIdr = () => {
|
||||
const numEx = typeof exchangeRate === "string" ? parseFloat(exchangeRate) || 16250 : exchangeRate;
|
||||
return items.reduce((acc, curr) => {
|
||||
const costIdr =
|
||||
currency === "USD"
|
||||
? Math.round((curr.unitCostUsd || 0) * exchangeRate)
|
||||
: curr.unitCost;
|
||||
return acc + curr.quantity * costIdr;
|
||||
const q = typeof curr.quantity === "string" ? parseFloat(curr.quantity) || 0 : curr.quantity;
|
||||
const cUsd = typeof curr.unitCostUsd === "string" ? parseFloat(curr.unitCostUsd) || 0 : (curr.unitCostUsd || 0);
|
||||
const cIdr = typeof curr.unitCost === "string" ? parseFloat(curr.unitCost) || 0 : curr.unitCost;
|
||||
const costIdr = currency === "USD" ? Math.round(cUsd * numEx) : cIdr;
|
||||
return acc + q * costIdr;
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const calculateProductsSubtotalUsd = () => {
|
||||
return items.reduce((acc, curr) => acc + curr.quantity * (curr.unitCostUsd || 0), 0);
|
||||
return items.reduce((acc, curr) => {
|
||||
const q = typeof curr.quantity === "string" ? parseFloat(curr.quantity) || 0 : curr.quantity;
|
||||
const cUsd = typeof curr.unitCostUsd === "string" ? parseFloat(curr.unitCostUsd) || 0 : (curr.unitCostUsd || 0);
|
||||
return acc + q * cUsd;
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const calculateTotalIdr = () => {
|
||||
const productsSubtotal = calculateProductsSubtotalIdr();
|
||||
const numAllIn = typeof allInCostInput === "string" ? parseFloat(allInCostInput) || 0 : allInCostInput;
|
||||
const numShip = typeof shippingCostInput === "string" ? parseFloat(shippingCostInput) || 0 : shippingCostInput;
|
||||
const numExp = typeof exportCostInput === "string" ? parseFloat(exportCostInput) || 0 : exportCostInput;
|
||||
const numEx = typeof exchangeRate === "string" ? parseFloat(exchangeRate) || 16250 : exchangeRate;
|
||||
|
||||
if (logisticsMode === "ASSISTED_ALL_IN") {
|
||||
// Mode Dibantu Perusahaan Lain: gabungan Ongkos Kirim + Pajak Masuk dibayar 1 pintu dalam Rupiah
|
||||
return productsSubtotal + allInCostInput;
|
||||
return productsSubtotal + numAllIn;
|
||||
}
|
||||
// Mode Rincian Terpisah: Ongkir jika USD dikonversi kurs; Biaya Bea Cukai & Dokumen selalu Rupiah
|
||||
const shippingIdr =
|
||||
currency === "USD"
|
||||
? Math.round(shippingCostInput * exchangeRate)
|
||||
: shippingCostInput;
|
||||
const customsDocIdr = exportCostInput;
|
||||
return productsSubtotal + shippingIdr + customsDocIdr;
|
||||
const shippingIdr = currency === "USD" ? Math.round(numShip * numEx) : numShip;
|
||||
return productsSubtotal + shippingIdr + numExp;
|
||||
};
|
||||
|
||||
const calculateTotalUsd = () => {
|
||||
const numShip = typeof shippingCostInput === "string" ? parseFloat(shippingCostInput) || 0 : shippingCostInput;
|
||||
if (logisticsMode === "ASSISTED_ALL_IN") {
|
||||
// Jika dibantu perusahaan forwarder All-In, ke vendor luar negeri hanya bayar harga barang (USD)
|
||||
return calculateProductsSubtotalUsd();
|
||||
}
|
||||
// Tagihan ke vendor luar negeri: Produk + Ongkir Freight internasional
|
||||
return calculateProductsSubtotalUsd() + shippingCostInput;
|
||||
return calculateProductsSubtotalUsd() + numShip;
|
||||
};
|
||||
|
||||
const handleCreatePO = async (e: React.FormEvent) => {
|
||||
@@ -445,7 +464,19 @@ export default function PurchasesPage() {
|
||||
setSubmitting(true);
|
||||
setFormError(null);
|
||||
|
||||
const invalidItem = items.some(
|
||||
const numExchangeRate = typeof exchangeRate === "string" ? parseFloat(exchangeRate) || 16250 : exchangeRate;
|
||||
const numAllInCost = typeof allInCostInput === "string" ? parseFloat(allInCostInput) || 0 : allInCostInput;
|
||||
const numShippingCost = typeof shippingCostInput === "string" ? parseFloat(shippingCostInput) || 0 : shippingCostInput;
|
||||
const numExportCost = typeof exportCostInput === "string" ? parseFloat(exportCostInput) || 0 : exportCostInput;
|
||||
|
||||
const cleanItems = items.map((i) => ({
|
||||
productId: i.productId,
|
||||
quantity: typeof i.quantity === "string" ? parseInt(i.quantity) || 0 : i.quantity,
|
||||
unitCost: typeof i.unitCost === "string" ? parseFloat(i.unitCost) || 0 : i.unitCost,
|
||||
unitCostUsd: i.unitCostUsd !== undefined ? (typeof i.unitCostUsd === "string" ? parseFloat(i.unitCostUsd) || 0 : i.unitCostUsd) : undefined,
|
||||
}));
|
||||
|
||||
const invalidItem = cleanItems.some(
|
||||
(i) =>
|
||||
!i.productId ||
|
||||
i.quantity <= 0 ||
|
||||
@@ -467,34 +498,29 @@ export default function PurchasesPage() {
|
||||
companyName: poCompanyName,
|
||||
supplierId,
|
||||
currency,
|
||||
exchangeRate: currency === "USD" ? exchangeRate : 1,
|
||||
exchangeRate: currency === "USD" ? numExchangeRate : 1,
|
||||
warehouseId: warehouseId || warehouses[0]?.id,
|
||||
autoReceive,
|
||||
logisticsMode,
|
||||
forwardingCompany:
|
||||
logisticsMode === "ASSISTED_ALL_IN" ? forwardingCompanyInput.trim() || undefined : undefined,
|
||||
allInCost: logisticsMode === "ASSISTED_ALL_IN" ? allInCostInput : undefined,
|
||||
allInCost: logisticsMode === "ASSISTED_ALL_IN" ? numAllInCost : undefined,
|
||||
shippingCost:
|
||||
logisticsMode === "ASSISTED_ALL_IN"
|
||||
? 0
|
||||
: currency === "USD"
|
||||
? Math.round(shippingCostInput * exchangeRate)
|
||||
: shippingCostInput,
|
||||
? Math.round(numShippingCost * numExchangeRate)
|
||||
: numShippingCost,
|
||||
exportCost:
|
||||
logisticsMode === "ASSISTED_ALL_IN" ? allInCostInput : exportCostInput,
|
||||
logisticsMode === "ASSISTED_ALL_IN" ? numAllInCost : numExportCost,
|
||||
shippingCostUsd:
|
||||
logisticsMode === "ASSISTED_ALL_IN"
|
||||
? undefined
|
||||
: currency === "USD"
|
||||
? shippingCostInput
|
||||
? numShippingCost
|
||||
: undefined,
|
||||
notes,
|
||||
items: items.map((i) => ({
|
||||
productId: i.productId,
|
||||
quantity: i.quantity,
|
||||
unitCost: i.unitCost,
|
||||
unitCostUsd: i.unitCostUsd,
|
||||
})),
|
||||
items: cleanItems,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -615,19 +641,20 @@ export default function PurchasesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Superadmin Delete PO
|
||||
// Superadmin / Manager Delete PO
|
||||
const handleDeletePO = async (po: any) => {
|
||||
const poId = po.id || po.purchaseOrderId || po.poNumber;
|
||||
if (
|
||||
!confirm(
|
||||
`[SUPERADMIN] Apakah Anda yakin ingin menghapus PO Vendor "${po.poNumber}" (${formatRupiah(
|
||||
po.totalAmount
|
||||
`[SUPERADMIN/MANAGER] Apakah Anda yakin ingin menghapus PO Vendor "${po.poNumber}" (${formatRupiah(
|
||||
po.totalAmount || 0
|
||||
)}) secara permanen? Data batch gudang dan alokasi stok terkait akan dihapus.`
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`/api/purchases?id=${po.id}&type=po`, { method: "DELETE" });
|
||||
const res = await fetch(`/api/purchases?id=${poId}&type=po`, { method: "DELETE" });
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
alert(data.message || "PO Vendor berhasil dihapus.");
|
||||
@@ -637,6 +664,26 @@ export default function PurchasesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Superadmin / Manager Delete Batch Saja
|
||||
const handleDeleteBatch = async (batch: any) => {
|
||||
if (
|
||||
!confirm(
|
||||
`[SUPERADMIN/MANAGER] Apakah Anda yakin ingin menghapus Batch FIFO "${batch.poNumber}" (${batch.product?.name})?`
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`/api/purchases?id=${batch.id}&type=batch`, { method: "DELETE" });
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
alert(data.message || "Batch berhasil dihapus.");
|
||||
loadData();
|
||||
} catch (err: any) {
|
||||
alert(err.message || "Gagal menghapus batch");
|
||||
}
|
||||
};
|
||||
|
||||
// Superadmin Delete PR
|
||||
const handleDeletePR = async (req: any) => {
|
||||
if (
|
||||
@@ -830,6 +877,11 @@ export default function PurchasesPage() {
|
||||
return true;
|
||||
});
|
||||
|
||||
// Pagination Slices (Default 5 items, pilihan 5, 10, 25, 50)
|
||||
const paginatedOrders = filteredOrders.slice((poPage - 1) * poPageSize, poPage * poPageSize);
|
||||
const paginatedRequisitions = filteredRequisitions.slice((reqPage - 1) * reqPageSize, reqPage * reqPageSize);
|
||||
const paginatedBatches = filteredBatches.slice((batchPage - 1) * batchPageSize, batchPage * batchPageSize);
|
||||
|
||||
// Hitungan Metrik
|
||||
const pendingFinancePOsCount = filteredOrders.filter(
|
||||
(o) => o.status === "PENDING_FINANCE" || o.status === "ON_HOLD"
|
||||
@@ -1179,14 +1231,14 @@ export default function PurchasesPage() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{filteredOrders.length === 0 ? (
|
||||
{paginatedOrders.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="py-12 text-center text-slate-400">
|
||||
Belum ada dokumen Purchase Order (PO).
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredOrders.map((po) => (
|
||||
paginatedOrders.map((po) => (
|
||||
<tr key={po.id} className="hover:bg-slate-50/60 transition-colors">
|
||||
<td className="py-4 px-5 align-top">
|
||||
<div className="font-mono font-bold text-amber-700">{po.poNumber}</div>
|
||||
@@ -1446,12 +1498,12 @@ export default function PurchasesPage() {
|
||||
</button>
|
||||
)}
|
||||
|
||||
{currentUser?.role === "ADMIN" && (
|
||||
{(currentUser?.role === "ADMIN" || currentUser?.role === "MANAGER") && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeletePO(po)}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 transition-colors text-[11px] font-semibold"
|
||||
title="Hapus PO Vendor Secara Permanen (Superadmin)"
|
||||
title="Hapus PO Vendor Secara Permanen (Superadmin/Manager)"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-rose-600" />
|
||||
<span>Hapus</span>
|
||||
@@ -1465,6 +1517,16 @@ export default function PurchasesPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination PO */}
|
||||
<Pagination
|
||||
currentPage={poPage}
|
||||
totalItems={filteredOrders.length}
|
||||
pageSize={poPageSize}
|
||||
onPageChange={setPoPage}
|
||||
onPageSizeChange={setPoPageSize}
|
||||
pageSizeOptions={[5, 10, 25, 50]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1512,14 +1574,14 @@ export default function PurchasesPage() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{filteredRequisitions.length === 0 ? (
|
||||
{paginatedRequisitions.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="py-12 text-center text-slate-400">
|
||||
Belum ada pengajuan pengadaan dari Sales.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredRequisitions.map((req) => (
|
||||
paginatedRequisitions.map((req) => (
|
||||
<tr key={req.id} className="hover:bg-slate-50/60 transition-colors">
|
||||
<td className="py-4 px-5 align-top">
|
||||
<div className="font-mono font-bold text-blue-700">{req.reqNumber}</div>
|
||||
@@ -1599,12 +1661,12 @@ export default function PurchasesPage() {
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
{currentUser?.role === "ADMIN" && (
|
||||
{(currentUser?.role === "ADMIN" || currentUser?.role === "MANAGER") && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeletePR(req)}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 transition-colors text-[11px] font-semibold ml-2"
|
||||
title="Hapus Pengajuan PR (Superadmin)"
|
||||
title="Hapus Pengajuan PR (Superadmin/Manager)"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-rose-600" />
|
||||
<span>Hapus</span>
|
||||
@@ -1617,6 +1679,16 @@ export default function PurchasesPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination Requisitions */}
|
||||
<Pagination
|
||||
currentPage={reqPage}
|
||||
totalItems={filteredRequisitions.length}
|
||||
pageSize={reqPageSize}
|
||||
onPageChange={setReqPage}
|
||||
onPageSizeChange={setReqPageSize}
|
||||
pageSizeOptions={[5, 10, 25, 50]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1673,12 +1745,13 @@ export default function PurchasesPage() {
|
||||
<th className="py-3 px-4 text-center">Sisa Stok Saat Ini</th>
|
||||
<th className="py-3 px-4 text-right">Modal HPP / Unit</th>
|
||||
<th className="py-3 px-5">Riwayat Penjualan yang Mengambil dari PO Ini</th>
|
||||
<th className="py-3 px-4 text-right">Tindakan</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{filteredBatches.length === 0 ? (
|
||||
{paginatedBatches.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="py-12 text-center text-slate-500">
|
||||
<td colSpan={7} className="py-12 text-center text-slate-500">
|
||||
<div className="max-w-md mx-auto space-y-2">
|
||||
<Layers className="h-8 w-8 text-slate-400 mx-auto" />
|
||||
<div className="font-bold text-slate-700 text-sm">
|
||||
@@ -1691,7 +1764,7 @@ export default function PurchasesPage() {
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredBatches.map((b) => {
|
||||
paginatedBatches.map((b) => {
|
||||
const isExhausted = b.remainingQty === 0;
|
||||
const isPartial = b.remainingQty > 0 && b.remainingQty < b.initialQty;
|
||||
const percentLeft = b.initialQty > 0 ? Math.round((b.remainingQty / b.initialQty) * 100) : 0;
|
||||
@@ -1825,6 +1898,36 @@ export default function PurchasesPage() {
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
|
||||
<td className="py-3.5 px-4 text-right align-top">
|
||||
{(currentUser?.role === "ADMIN" || currentUser?.role === "MANAGER") && (
|
||||
<div className="flex flex-col items-end gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
handleDeletePO({
|
||||
id: b.purchaseOrderId || b.purchaseOrder?.id,
|
||||
poNumber: b.poNumber,
|
||||
totalAmount: b.initialQty * b.unitCost,
|
||||
})
|
||||
}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 transition-colors text-[11px] font-semibold whitespace-nowrap shadow-2xs"
|
||||
title="Hapus PO Vendor ini secara permanen"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-rose-600" />
|
||||
<span>Hapus PO</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeleteBatch(b)}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded bg-slate-100 hover:bg-rose-50 text-slate-600 hover:text-rose-700 border border-slate-200 text-[10px] font-medium transition-colors whitespace-nowrap"
|
||||
title="Hapus hanya record batch FIFO ini"
|
||||
>
|
||||
<span>Hapus Batch</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
@@ -1832,6 +1935,16 @@ export default function PurchasesPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination Batches */}
|
||||
<Pagination
|
||||
currentPage={batchPage}
|
||||
totalItems={filteredBatches.length}
|
||||
pageSize={batchPageSize}
|
||||
onPageChange={setBatchPage}
|
||||
onPageSizeChange={setBatchPageSize}
|
||||
pageSizeOptions={[5, 10, 25, 50]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -2015,10 +2128,11 @@ export default function PurchasesPage() {
|
||||
min="1"
|
||||
required
|
||||
placeholder="Qty"
|
||||
value={item.quantity}
|
||||
value={item.quantity === "" ? "" : item.quantity}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
const updated = [...reqItems];
|
||||
updated[idx].quantity = parseInt(e.target.value) || 1;
|
||||
updated[idx].quantity = v === "" ? "" : parseInt(v) || 0;
|
||||
setReqItems(updated);
|
||||
}}
|
||||
className="w-full px-2 py-1.5 border border-slate-300 rounded text-center font-bold"
|
||||
@@ -2324,10 +2438,11 @@ export default function PurchasesPage() {
|
||||
min="1"
|
||||
required
|
||||
placeholder="Qty"
|
||||
value={item.quantity}
|
||||
value={item.quantity === "" ? "" : item.quantity}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
const updated = [...items];
|
||||
updated[idx].quantity = parseInt(e.target.value) || 1;
|
||||
updated[idx].quantity = v === "" ? "" : parseInt(v) || 0;
|
||||
setItems(updated);
|
||||
}}
|
||||
className="w-full px-2 py-1.5 border border-slate-300 rounded text-center font-bold"
|
||||
@@ -2342,10 +2457,11 @@ export default function PurchasesPage() {
|
||||
step="0.01"
|
||||
required
|
||||
placeholder="Harga $ USD"
|
||||
value={item.unitCostUsd}
|
||||
value={item.unitCostUsd === "" ? "" : item.unitCostUsd}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
const updated = [...items];
|
||||
updated[idx].unitCostUsd = parseFloat(e.target.value) || 0;
|
||||
updated[idx].unitCostUsd = v === "" ? "" : parseFloat(v) || 0;
|
||||
setItems(updated);
|
||||
}}
|
||||
className="w-full px-2 py-1.5 border border-amber-300 rounded text-right font-bold text-amber-900 bg-white"
|
||||
@@ -2356,10 +2472,11 @@ export default function PurchasesPage() {
|
||||
min="0"
|
||||
required
|
||||
placeholder="Harga Rp"
|
||||
value={item.unitCost}
|
||||
value={item.unitCost === "" ? "" : item.unitCost}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
const updated = [...items];
|
||||
updated[idx].unitCost = parseFloat(e.target.value) || 0;
|
||||
updated[idx].unitCost = v === "" ? "" : parseFloat(v) || 0;
|
||||
setItems(updated);
|
||||
}}
|
||||
className="w-full px-2 py-1.5 border border-slate-300 rounded text-right font-bold text-slate-800"
|
||||
@@ -2435,9 +2552,9 @@ export default function PurchasesPage() {
|
||||
onChange={(e) => setShippingCostInput(parseFloat(e.target.value) || 0)}
|
||||
className="w-full h-9 px-3 py-1.5 border border-slate-300 rounded-lg bg-white font-mono text-xs focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
{currency === "USD" && shippingCostInput > 0 && (
|
||||
{currency === "USD" && Number(shippingCostInput) > 0 && (
|
||||
<p className="text-[10px] text-slate-500 mt-0.5">
|
||||
≈ {formatRupiah(shippingCostInput * exchangeRate)}
|
||||
≈ {formatRupiah(Number(shippingCostInput) * Number(exchangeRate))}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -2512,31 +2629,31 @@ export default function PurchasesPage() {
|
||||
<span className="font-mono">{formatRupiah(calculateProductsSubtotalIdr())}</span>
|
||||
</div>
|
||||
{logisticsMode === "ASSISTED_ALL_IN" ? (
|
||||
allInCostInput > 0 && (
|
||||
Number(allInCostInput) > 0 && (
|
||||
<div className="flex items-center justify-between text-xs text-teal-300">
|
||||
<span>
|
||||
Biaya Via Forwarder
|
||||
{forwardingCompanyInput.trim() ? ` (${forwardingCompanyInput.trim()})` : ""}:
|
||||
</span>
|
||||
<span className="font-mono font-bold">{formatRupiah(allInCostInput)}</span>
|
||||
<span className="font-mono font-bold">{formatRupiah(Number(allInCostInput))}</span>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
(shippingCostInput > 0 || exportCostInput > 0) && (
|
||||
(Number(shippingCostInput) > 0 || Number(exportCostInput) > 0) && (
|
||||
<>
|
||||
{shippingCostInput > 0 && (
|
||||
{Number(shippingCostInput) > 0 && (
|
||||
<div className="flex items-center justify-between text-xs text-slate-300">
|
||||
<span>Biaya Ongkir ({currency === "USD" ? `$${shippingCostInput.toLocaleString("en-US", { minimumFractionDigits: 2 })} USD` : "IDR"}):</span>
|
||||
<span>Biaya Ongkir ({currency === "USD" ? `$${Number(shippingCostInput).toLocaleString("en-US", { minimumFractionDigits: 2 })} USD` : "IDR"}):</span>
|
||||
<span className="font-mono text-blue-300">
|
||||
{formatRupiah(currency === "USD" ? Math.round(shippingCostInput * exchangeRate) : shippingCostInput)}
|
||||
{formatRupiah(currency === "USD" ? Math.round(Number(shippingCostInput) * Number(exchangeRate)) : Number(shippingCostInput))}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{exportCostInput > 0 && (
|
||||
{Number(exportCostInput) > 0 && (
|
||||
<div className="flex items-center justify-between text-xs text-slate-300">
|
||||
<span>Biaya Bea Cukai & Pajak Masuk:</span>
|
||||
<span className="font-mono text-purple-300">
|
||||
{formatRupiah(exportCostInput)}
|
||||
{formatRupiah(Number(exportCostInput))}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
+110
-57
@@ -5,6 +5,7 @@ import Link from "next/link";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { StatusBadge } from "@/components/Badge";
|
||||
import { Pagination } from "@/components/Pagination";
|
||||
import { formatRupiah, formatDateTime, exportToCSV, escapeHtml } from "@/lib/utils";
|
||||
import {
|
||||
ShoppingCart,
|
||||
@@ -82,10 +83,14 @@ export default function SalesPage() {
|
||||
const [rmaSubmitting, setRmaSubmitting] = useState(false);
|
||||
const [rmaFeedbackMsg, setRmaFeedbackMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
|
||||
|
||||
// Pagination State (Default 5 items, pilihan 5, 10, 25, 50)
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(5);
|
||||
|
||||
// Invoicing & Payment Modal State (Pemberitahuan Kurang Bayar / Bayar Sebagian)
|
||||
const [isPaymentModalOpen, setIsPaymentModalOpen] = useState(false);
|
||||
const [selectedPaymentOrder, setSelectedPaymentOrder] = useState<any>(null);
|
||||
const [paymentAmountInput, setPaymentAmountInput] = useState<number>(0);
|
||||
const [paymentAmountInput, setPaymentAmountInput] = useState<number | string>(0);
|
||||
const [paymentNotesInput, setPaymentNotesInput] = useState<string>("");
|
||||
const [paymentSubmitting, setPaymentSubmitting] = useState(false);
|
||||
const [paymentFeedbackMsg, setPaymentFeedbackMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
|
||||
@@ -103,10 +108,10 @@ export default function SalesPage() {
|
||||
const [items, setItems] = useState<
|
||||
{
|
||||
productId: string;
|
||||
quantity: number;
|
||||
unitPrice: number;
|
||||
quantity: number | string;
|
||||
unitPrice: number | string;
|
||||
isManualPo?: boolean;
|
||||
allocations?: { batchId: string; quantity: number }[];
|
||||
allocations?: { batchId: string; quantity: number | string }[];
|
||||
}[]
|
||||
>([{ productId: "", quantity: 1, unitPrice: 0, allocations: [] }]);
|
||||
|
||||
@@ -245,7 +250,7 @@ export default function SalesPage() {
|
||||
const handleProductChange = (index: number, pId: string) => {
|
||||
const selectedProd = products.find((p) => p.id === pId);
|
||||
const updated = [...items];
|
||||
const prevQty = updated[index].quantity || 1;
|
||||
const prevQty = Number(updated[index].quantity) || 1;
|
||||
updated[index].productId = pId;
|
||||
|
||||
// Cek harga khusus pelanggan terlebih dahulu
|
||||
@@ -279,16 +284,16 @@ export default function SalesPage() {
|
||||
setItems(updated);
|
||||
};
|
||||
|
||||
const handleItemQtyChange = (index: number, newQty: number) => {
|
||||
const handleItemQtyChange = (index: number, newQty: number | string) => {
|
||||
const updated = [...items];
|
||||
const qty = Math.max(1, newQty);
|
||||
updated[index].quantity = qty;
|
||||
updated[index].quantity = newQty;
|
||||
|
||||
const numQty = typeof newQty === "string" ? (parseInt(newQty) || 0) : newQty;
|
||||
if (updated[index].allocations && updated[index].allocations!.length > 0) {
|
||||
const allocs = [...updated[index].allocations!];
|
||||
const firstBatch = activeBatches.find((b) => b.id === allocs[0].batchId);
|
||||
if (firstBatch && allocs.length === 1) {
|
||||
allocs[0].quantity = Math.min(qty, firstBatch.remainingQty);
|
||||
allocs[0].quantity = Math.min(numQty, firstBatch.remainingQty);
|
||||
}
|
||||
updated[index].allocations = allocs;
|
||||
}
|
||||
@@ -304,8 +309,9 @@ export default function SalesPage() {
|
||||
const existingBatchIds = (item.allocations || []).map((a) => a.batchId);
|
||||
const nextBatch = matchingBatches.find((b) => !existingBatchIds.includes(b.id));
|
||||
|
||||
const totalAllocated = (item.allocations || []).reduce((acc, a) => acc + (a.quantity || 0), 0);
|
||||
const shortfall = Math.max(1, item.quantity - totalAllocated);
|
||||
const totalAllocated = (item.allocations || []).reduce((acc, a) => acc + (Number(a.quantity) || 0), 0);
|
||||
const itemNumQty = typeof item.quantity === "string" ? (parseInt(item.quantity) || 0) : item.quantity;
|
||||
const shortfall = Math.max(1, itemNumQty - totalAllocated);
|
||||
|
||||
const newAlloc = {
|
||||
batchId: nextBatch ? nextBatch.id : (matchingBatches[0]?.id || ""),
|
||||
@@ -336,41 +342,47 @@ export default function SalesPage() {
|
||||
if (field === "batchId") {
|
||||
const b = activeBatches.find((batch) => batch.id === val);
|
||||
allocs[allocIndex].batchId = val;
|
||||
if (b && allocs[allocIndex].quantity > b.remainingQty) {
|
||||
if (b && Number(allocs[allocIndex].quantity) > b.remainingQty) {
|
||||
allocs[allocIndex].quantity = b.remainingQty;
|
||||
}
|
||||
} else if (field === "quantity") {
|
||||
const b = activeBatches.find((batch) => batch.id === allocs[allocIndex].batchId);
|
||||
const parsed = Math.max(0, parseInt(val) || 0);
|
||||
allocs[allocIndex].quantity = b ? Math.min(parsed, b.remainingQty) : parsed;
|
||||
const parsed = val === "" ? "" : Math.max(0, parseInt(val) || 0);
|
||||
allocs[allocIndex].quantity = b && typeof parsed === "number" ? Math.min(parsed, b.remainingQty) : parsed;
|
||||
}
|
||||
updated[itemIndex].allocations = allocs;
|
||||
setItems(updated);
|
||||
};
|
||||
|
||||
const calculateTotal = () => {
|
||||
return items.reduce((acc, curr) => acc + curr.quantity * curr.unitPrice, 0);
|
||||
return items.reduce((acc, curr) => {
|
||||
const q = typeof curr.quantity === "string" ? parseFloat(curr.quantity) || 0 : curr.quantity;
|
||||
const p = typeof curr.unitPrice === "string" ? parseFloat(curr.unitPrice) || 0 : curr.unitPrice;
|
||||
return acc + q * p;
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const calculateTotalHpp = () => {
|
||||
return items.reduce((acc, curr) => {
|
||||
const prod = products.find((p) => p.id === curr.productId);
|
||||
if (!prod) return acc;
|
||||
const numQty = typeof curr.quantity === "string" ? parseFloat(curr.quantity) || 0 : curr.quantity;
|
||||
if (curr.allocations && curr.allocations.length > 0) {
|
||||
let itemCost = 0;
|
||||
let allocated = 0;
|
||||
for (const al of curr.allocations) {
|
||||
const b = activeBatches.find((batch) => batch.id === al.batchId);
|
||||
const cost = b ? b.unitCost : (prod.purchasePrice || 0);
|
||||
itemCost += (al.quantity || 0) * cost;
|
||||
allocated += (al.quantity || 0);
|
||||
const alQty = typeof al.quantity === "string" ? parseFloat(al.quantity) || 0 : al.quantity;
|
||||
itemCost += alQty * cost;
|
||||
allocated += alQty;
|
||||
}
|
||||
if (allocated < curr.quantity) {
|
||||
itemCost += (curr.quantity - allocated) * (prod.purchasePrice || 0);
|
||||
if (allocated < numQty) {
|
||||
itemCost += (numQty - allocated) * (prod.purchasePrice || 0);
|
||||
}
|
||||
return acc + itemCost;
|
||||
}
|
||||
return acc + curr.quantity * (prod.purchasePrice || 0);
|
||||
return acc + numQty * (prod.purchasePrice || 0);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
@@ -477,7 +489,17 @@ export default function SalesPage() {
|
||||
setSubmitting(true);
|
||||
setFormError(null);
|
||||
|
||||
const invalidItem = items.some((i) => !i.productId || i.quantity <= 0);
|
||||
const cleanItems = items.map((i) => ({
|
||||
...i,
|
||||
quantity: typeof i.quantity === "string" ? parseInt(i.quantity) || 0 : i.quantity,
|
||||
unitPrice: typeof i.unitPrice === "string" ? parseFloat(i.unitPrice) || 0 : i.unitPrice,
|
||||
allocations: (i.allocations || []).map((a) => ({
|
||||
...a,
|
||||
quantity: typeof a.quantity === "string" ? parseInt(a.quantity) || 0 : a.quantity,
|
||||
})),
|
||||
}));
|
||||
|
||||
const invalidItem = cleanItems.some((i) => !i.productId || i.quantity <= 0);
|
||||
if (invalidItem) {
|
||||
setFormError("Pastikan semua item memiliki produk yang dipilih dan jumlah > 0");
|
||||
setSubmitting(false);
|
||||
@@ -498,7 +520,7 @@ export default function SalesPage() {
|
||||
customerId,
|
||||
warehouseId,
|
||||
notes,
|
||||
items,
|
||||
items: cleanItems,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -651,6 +673,8 @@ export default function SalesPage() {
|
||||
const targetPaidAmount =
|
||||
overridePaidAmount !== undefined
|
||||
? overridePaidAmount
|
||||
: typeof paymentAmountInput === "string"
|
||||
? parseFloat(paymentAmountInput) || 0
|
||||
: paymentAmountInput;
|
||||
|
||||
try {
|
||||
@@ -892,12 +916,21 @@ export default function SalesPage() {
|
||||
});
|
||||
|
||||
const totalSalesAmount = filteredOrders.reduce((s, o) => s + (o.totalAmount || 0), 0);
|
||||
const unpaidSalesAmount = filteredOrders
|
||||
.filter((o) => o.paymentStatus !== "PAID")
|
||||
.reduce((s, o) => s + (o.totalAmount || 0), 0);
|
||||
const paidSalesAmount = filteredOrders
|
||||
.filter((o) => o.paymentStatus === "PAID")
|
||||
.reduce((s, o) => s + (o.totalAmount || 0), 0);
|
||||
const paidSalesAmount = filteredOrders.reduce((s, o) => {
|
||||
if (o.paymentStatus === "PAID") return s + (o.totalAmount || 0);
|
||||
return s + (o.paidAmount || 0);
|
||||
}, 0);
|
||||
const unpaidSalesAmount = filteredOrders.reduce((s, o) => {
|
||||
if (o.paymentStatus === "PAID") return s;
|
||||
const remaining = Math.max(0, (o.totalAmount || 0) - (o.paidAmount || 0));
|
||||
return s + remaining;
|
||||
}, 0);
|
||||
|
||||
// Pagination Slice
|
||||
const paginatedOrders = filteredOrders.slice(
|
||||
(currentPage - 1) * pageSize,
|
||||
currentPage * pageSize
|
||||
);
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
@@ -926,13 +959,13 @@ export default function SalesPage() {
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-4 shadow-2xs flex items-center justify-between">
|
||||
<div>
|
||||
<span className="text-[11px] font-bold uppercase tracking-wider text-slate-400">
|
||||
Tagihan Lunas (Paid)
|
||||
Tagihan Terbayar / Uang Masuk
|
||||
</span>
|
||||
<div className="text-2xl font-bold text-emerald-600 mt-0.5">
|
||||
{formatRupiah(paidSalesAmount)}
|
||||
</div>
|
||||
<span className="text-[11px] text-slate-500">
|
||||
Sudah masuk ke Rekening Bank
|
||||
Sudah masuk Kas/Bank (Lunas & Sebagian)
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-10 w-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
|
||||
@@ -943,13 +976,13 @@ export default function SalesPage() {
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-4 shadow-2xs flex items-center justify-between">
|
||||
<div>
|
||||
<span className="text-[11px] font-bold uppercase tracking-wider text-slate-400">
|
||||
Piutang Belum Lunas (Unpaid)
|
||||
Sisa Piutang Belum Lunas
|
||||
</span>
|
||||
<div className="text-2xl font-bold text-amber-600 mt-0.5">
|
||||
{formatRupiah(unpaidSalesAmount)}
|
||||
</div>
|
||||
<span className="text-[11px] text-slate-500">
|
||||
Menunggu verifikasi pembayaran
|
||||
Sisa tagihan yang masih harus ditagih
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-10 w-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center">
|
||||
@@ -1068,7 +1101,7 @@ export default function SalesPage() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{filteredOrders.length === 0 ? (
|
||||
{paginatedOrders.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={9} className="py-10 text-center text-slate-400">
|
||||
Belum ada pesanan penjualan. Klik <strong>+ Pelanggan Baru</strong> lalu{" "}
|
||||
@@ -1076,7 +1109,7 @@ export default function SalesPage() {
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredOrders.map((o) => (
|
||||
paginatedOrders.map((o) => (
|
||||
<tr key={o.id} className="hover:bg-slate-50/60 transition-colors">
|
||||
<td className="py-3.5 px-4 align-top">
|
||||
<div className="font-mono font-bold text-blue-600 truncate">
|
||||
@@ -1319,12 +1352,12 @@ export default function SalesPage() {
|
||||
<span>Lengkap</span>
|
||||
</span>
|
||||
)}
|
||||
{currentUser?.role === "ADMIN" && (
|
||||
{(currentUser?.role === "ADMIN" || currentUser?.role === "MANAGER") && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeleteSalesOrder(o)}
|
||||
className="inline-flex items-center gap-1 px-2 py-1.5 rounded-md bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 transition-colors text-[11px] font-semibold whitespace-nowrap shadow-2xs"
|
||||
title="Hapus Sales Order Secara Permanen (Superadmin)"
|
||||
title="Hapus Sales Order Secara Permanen (Superadmin/Manager)"
|
||||
>
|
||||
<Trash2 className="h-3 w-3 text-rose-600" />
|
||||
<span>Hapus</span>
|
||||
@@ -1338,6 +1371,16 @@ export default function SalesPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination SO */}
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalItems={filteredOrders.length}
|
||||
pageSize={pageSize}
|
||||
onPageChange={setCurrentPage}
|
||||
onPageSizeChange={setPageSize}
|
||||
pageSizeOptions={[5, 10, 25, 50]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Modal: Tambah Pelanggan Baru (Sub-modal: z-[70] agar tampil di depan modal Buat SO) */}
|
||||
@@ -1621,7 +1664,7 @@ export default function SalesPage() {
|
||||
? [
|
||||
{
|
||||
batchId: prodBatches[0].id,
|
||||
quantity: Math.min(it.quantity, prodBatches[0].remainingQty),
|
||||
quantity: Math.min(Number(it.quantity) || 1, prodBatches[0].remainingQty),
|
||||
},
|
||||
]
|
||||
: [];
|
||||
@@ -1671,10 +1714,11 @@ export default function SalesPage() {
|
||||
{items.map((item, idx) => {
|
||||
const selectedProd = products.find((p) => p.id === item.productId);
|
||||
const costPrice = selectedProd ? selectedProd.purchasePrice : 0;
|
||||
const unitProfit = item.unitPrice - costPrice;
|
||||
const totalItemProfit = unitProfit * item.quantity;
|
||||
const numPrice = Number(item.unitPrice) || 0;
|
||||
const unitProfit = numPrice - costPrice;
|
||||
const totalItemProfit = unitProfit * (Number(item.quantity) || 0);
|
||||
const marginPct = costPrice > 0 ? Math.round((unitProfit / costPrice) * 100) : 100;
|
||||
const isLoss = item.unitPrice > 0 && costPrice > 0 && item.unitPrice < costPrice;
|
||||
const isLoss = numPrice > 0 && costPrice > 0 && numPrice < costPrice;
|
||||
|
||||
return (
|
||||
<div key={idx} className="p-3 bg-white rounded-xl border border-slate-200 shadow-2xs space-y-2.5">
|
||||
@@ -1713,8 +1757,11 @@ export default function SalesPage() {
|
||||
min="1"
|
||||
required
|
||||
placeholder="Qty"
|
||||
value={item.quantity}
|
||||
onChange={(e) => handleItemQtyChange(idx, parseInt(e.target.value) || 1)}
|
||||
value={item.quantity === "" ? "" : item.quantity}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
handleItemQtyChange(idx, v === "" ? "" : parseInt(v) || 0);
|
||||
}}
|
||||
className="w-full h-9 px-2 py-1.5 border border-slate-300 rounded-lg text-center bg-white font-bold text-xs text-slate-900 focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
@@ -1727,10 +1774,12 @@ export default function SalesPage() {
|
||||
type="number"
|
||||
min="0"
|
||||
required
|
||||
value={item.unitPrice}
|
||||
placeholder="Harga Jual"
|
||||
value={item.unitPrice === "" ? "" : item.unitPrice}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
const updated = [...items];
|
||||
updated[idx].unitPrice = parseFloat(e.target.value) || 0;
|
||||
updated[idx].unitPrice = v === "" ? "" : parseFloat(v) || 0;
|
||||
setItems(updated);
|
||||
}}
|
||||
className={`w-full h-9 px-3 py-1.5 border rounded-lg text-right bg-white font-bold text-xs focus:ring-1 focus:ring-blue-500 ${
|
||||
@@ -1766,7 +1815,7 @@ export default function SalesPage() {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{item.unitPrice > 0 && (
|
||||
{Number(item.unitPrice) > 0 && (
|
||||
<div>
|
||||
{isLoss ? (
|
||||
<span className="text-rose-600 font-bold">
|
||||
@@ -1793,8 +1842,8 @@ export default function SalesPage() {
|
||||
|
||||
if (isManual) {
|
||||
const allocs = item.allocations && item.allocations.length > 0 ? item.allocations : [];
|
||||
const totalAllocated = allocs.reduce((acc, a) => acc + (a.quantity || 0), 0);
|
||||
const shortfall = item.quantity - totalAllocated;
|
||||
const totalAllocated = allocs.reduce((acc, a) => acc + (Number(a.quantity) || 0), 0);
|
||||
const shortfall = (Number(item.quantity) || 1) - totalAllocated;
|
||||
const hasMoreBatches = prodBatches.some((b) => !allocs.some((a) => a.batchId === b.id));
|
||||
|
||||
return (
|
||||
@@ -1850,7 +1899,7 @@ export default function SalesPage() {
|
||||
{allocs.map((alloc, aIdx) => {
|
||||
const currentBatch = prodBatches.find((b) => b.id === alloc.batchId);
|
||||
const maxCap = currentBatch ? currentBatch.remainingQty : 0;
|
||||
const remainingInThisBatch = currentBatch ? Math.max(0, currentBatch.remainingQty - alloc.quantity) : 0;
|
||||
const remainingInThisBatch = currentBatch ? Math.max(0, currentBatch.remainingQty - (Number(alloc.quantity) || 0)) : 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -1894,7 +1943,7 @@ export default function SalesPage() {
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
value={alloc.quantity}
|
||||
value={alloc.quantity === "" ? "" : alloc.quantity}
|
||||
onChange={(e) =>
|
||||
handleUpdateBatchAllocation(idx, aIdx, "quantity", e.target.value)
|
||||
}
|
||||
@@ -1979,7 +2028,7 @@ export default function SalesPage() {
|
||||
}
|
||||
|
||||
// Mode FIFO Otomatis (Default)
|
||||
const sim = getSimulatedBatchAllocation(item.productId, warehouseId, Math.max(1, item.quantity));
|
||||
const sim = getSimulatedBatchAllocation(item.productId, warehouseId, Math.max(1, Number(item.quantity) || 1));
|
||||
const isShortage = sim && sim.unallocatedQty > 0;
|
||||
|
||||
return (
|
||||
@@ -2007,13 +2056,14 @@ export default function SalesPage() {
|
||||
);
|
||||
if (matching.length > 0) {
|
||||
const first = matching[0];
|
||||
const takeFirst = Math.min(item.quantity, first.remainingQty);
|
||||
const itemQty = Number(item.quantity) || 1;
|
||||
const takeFirst = Math.min(itemQty, first.remainingQty);
|
||||
const initialAllocs = [{ batchId: first.id, quantity: takeFirst }];
|
||||
if (item.quantity > takeFirst && matching.length > 1) {
|
||||
if (itemQty > takeFirst && matching.length > 1) {
|
||||
const sec = matching[1];
|
||||
initialAllocs.push({
|
||||
batchId: sec.id,
|
||||
quantity: Math.min(item.quantity - takeFirst, sec.remainingQty),
|
||||
quantity: Math.min(itemQty - takeFirst, sec.remainingQty),
|
||||
});
|
||||
}
|
||||
updated[idx].allocations = initialAllocs;
|
||||
@@ -2106,7 +2156,7 @@ export default function SalesPage() {
|
||||
<span>Belum ada pasokan PO Vendor untuk barang ini. Klik tombol untuk menerbitkan PO Vendor ke-1.</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleOpenQuickPo(selectedProd, item.quantity || 50)}
|
||||
onClick={() => handleOpenQuickPo(selectedProd, Number(item.quantity) || 50)}
|
||||
className="px-2 py-1 bg-amber-600 hover:bg-amber-700 text-white rounded font-bold whitespace-nowrap"
|
||||
>
|
||||
+ Terbitkan PO-1 Vendor
|
||||
@@ -2945,8 +2995,11 @@ export default function SalesPage() {
|
||||
type="number"
|
||||
min={0}
|
||||
step="any"
|
||||
value={paymentAmountInput}
|
||||
onChange={(e) => setPaymentAmountInput(Math.max(0, parseFloat(e.target.value) || 0))}
|
||||
value={paymentAmountInput === "" ? "" : paymentAmountInput}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setPaymentAmountInput(v === "" ? "" : parseFloat(v) || 0);
|
||||
}}
|
||||
className="w-full pl-9 pr-3 py-2 border border-slate-300 rounded-lg text-slate-800 font-semibold focus:ring-2 focus:ring-blue-500 text-sm"
|
||||
placeholder="Contoh: 800000"
|
||||
/>
|
||||
@@ -2973,7 +3026,7 @@ export default function SalesPage() {
|
||||
{/* Dynamic Status / Underpayment Warning Alert */}
|
||||
{(() => {
|
||||
const total = selectedPaymentOrder.totalAmount;
|
||||
const paid = paymentAmountInput;
|
||||
const paid = typeof paymentAmountInput === "string" ? (parseFloat(paymentAmountInput) || 0) : paymentAmountInput;
|
||||
const diff = total - paid;
|
||||
|
||||
if (paid <= 0) {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
|
||||
interface PaginationProps {
|
||||
currentPage: number;
|
||||
totalItems: number;
|
||||
pageSize: number;
|
||||
onPageChange: (page: number) => void;
|
||||
onPageSizeChange: (size: number) => void;
|
||||
pageSizeOptions?: number[];
|
||||
}
|
||||
|
||||
export function Pagination({
|
||||
currentPage,
|
||||
totalItems,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
pageSizeOptions = [5, 10, 25, 50],
|
||||
}: PaginationProps) {
|
||||
const totalPages = Math.max(1, Math.ceil(totalItems / pageSize));
|
||||
const safeCurrentPage = Math.min(Math.max(1, currentPage), totalPages);
|
||||
|
||||
const startItem = totalItems === 0 ? 0 : (safeCurrentPage - 1) * pageSize + 1;
|
||||
const endItem = Math.min(safeCurrentPage * pageSize, totalItems);
|
||||
|
||||
// Generate visible page numbers
|
||||
const getPageNumbers = () => {
|
||||
const pages: (number | string)[] = [];
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) pages.push(i);
|
||||
} else {
|
||||
if (safeCurrentPage <= 4) {
|
||||
pages.push(1, 2, 3, 4, 5, "...", totalPages);
|
||||
} else if (safeCurrentPage >= totalPages - 3) {
|
||||
pages.push(1, "...", totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages);
|
||||
} else {
|
||||
pages.push(1, "...", safeCurrentPage - 1, safeCurrentPage, safeCurrentPage + 1, "...", totalPages);
|
||||
}
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="px-5 py-3.5 bg-slate-50 border-t border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-slate-600">
|
||||
<div className="flex items-center gap-3">
|
||||
<span>
|
||||
Menampilkan <strong className="text-slate-800">{startItem}</strong> -{" "}
|
||||
<strong className="text-slate-800">{endItem}</strong> dari{" "}
|
||||
<strong className="text-slate-800">{totalItems}</strong> data
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5 pl-3 border-l border-slate-200">
|
||||
<span className="text-[11px] text-slate-500">Tampilkan:</span>
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => {
|
||||
onPageSizeChange(Number(e.target.value));
|
||||
onPageChange(1);
|
||||
}}
|
||||
className="px-2 py-1 bg-white border border-slate-300 rounded text-xs font-semibold text-slate-700 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
{pageSizeOptions.map((opt) => (
|
||||
<option key={opt} value={opt}>
|
||||
{opt} / hal
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPageChange(Math.max(1, safeCurrentPage - 1))}
|
||||
disabled={safeCurrentPage <= 1}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-slate-200 bg-white hover:bg-slate-100 disabled:opacity-40 disabled:hover:bg-white text-xs font-medium transition-colors"
|
||||
>
|
||||
<ChevronLeft className="h-3.5 w-3.5" />
|
||||
<span>Sebelumnya</span>
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-1 px-1">
|
||||
{getPageNumbers().map((p, idx) => {
|
||||
if (p === "...") {
|
||||
return (
|
||||
<span key={`ellipsis-${idx}`} className="px-2 text-slate-400 font-bold">
|
||||
...
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const pageNum = Number(p);
|
||||
const isActive = pageNum === safeCurrentPage;
|
||||
return (
|
||||
<button
|
||||
key={pageNum}
|
||||
type="button"
|
||||
onClick={() => onPageChange(pageNum)}
|
||||
className={`min-w-[28px] h-7 px-1.5 rounded-md font-semibold text-xs transition-colors ${
|
||||
isActive
|
||||
? "bg-blue-600 text-white shadow-2xs"
|
||||
: "bg-white border border-slate-200 text-slate-700 hover:bg-slate-100"
|
||||
}`}
|
||||
>
|
||||
{pageNum}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPageChange(Math.min(totalPages, safeCurrentPage + 1))}
|
||||
disabled={safeCurrentPage >= totalPages}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-slate-200 bg-white hover:bg-slate-100 disabled:opacity-40 disabled:hover:bg-white text-xs font-medium transition-colors"
|
||||
>
|
||||
<span>Berikutnya</span>
|
||||
<ChevronRight className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user