Add custom per-PT branding, logo upload, zero default PT, and
customizable Invoice & BAST
This commit is contained in:
1 parent
22b36b699d
commit
efd4de1bc0
11 files changed
+1915
-440
No files matched your search
+9
-42
@@ -9,22 +9,6 @@ const prisma = new PrismaClient({
|
||||
datasources: { db: { url: dbUrl } },
|
||||
});
|
||||
|
||||
const DEFAULT_COMPANY = "PT EnterpriseCore Utama";
|
||||
|
||||
const DEFAULT_ACCOUNTS = [
|
||||
{ code: "1001", name: "Kas Kantor Operasional", type: "ASSET" },
|
||||
{ code: "1002", name: "Bank Operasional Utama", type: "ASSET" },
|
||||
{ code: "1101", name: "Piutang Dagang (AR)", type: "ASSET" },
|
||||
{ code: "1201", name: "Persediaan Barang Dagang", type: "ASSET" },
|
||||
{ code: "1301", name: "PPN Masukan (Pajak Pembelian)", type: "ASSET" },
|
||||
{ code: "2001", name: "Hutang Dagang (AP)", type: "LIABILITY" },
|
||||
{ code: "2101", name: "PPN Keluaran (Hutang Pajak Penjualan)", type: "LIABILITY" },
|
||||
{ code: "3001", name: "Modal Disetor", type: "EQUITY" },
|
||||
{ code: "4001", name: "Pendapatan Penjualan Barang", type: "REVENUE" },
|
||||
{ code: "5001", name: "Beban Pokok Penjualan (HPP)", type: "EXPENSE" },
|
||||
{ code: "6001", name: "Beban Gaji & Operasional", type: "EXPENSE" },
|
||||
];
|
||||
|
||||
const DUMMY_USERS = [
|
||||
{
|
||||
name: "Super Admin",
|
||||
@@ -104,7 +88,7 @@ async function main() {
|
||||
}
|
||||
|
||||
if (isReset) {
|
||||
console.log("Mengosongkan seluruh data transaksi & master...");
|
||||
console.log("Mengosongkan seluruh data transaksi, perusahaan, & master...");
|
||||
await prisma.deviceRecord.deleteMany();
|
||||
await prisma.salesItemBatchAllocation.deleteMany();
|
||||
await prisma.salesOrderItem.deleteMany();
|
||||
@@ -133,39 +117,22 @@ async function main() {
|
||||
await prisma.user.deleteMany();
|
||||
}
|
||||
|
||||
// 1. Default Warehouse (Gudang Utama)
|
||||
// 1. Default Warehouse (Gudang Utama - netral tanpa nama PT bawaan sistem)
|
||||
await prisma.warehouse.upsert({
|
||||
where: { code: "WH-01" },
|
||||
update: {},
|
||||
create: {
|
||||
code: "WH-01",
|
||||
name: "Gudang Utama",
|
||||
address: "Kantor Pusat Operasional",
|
||||
companyName: DEFAULT_COMPANY,
|
||||
address: "Gudang Operasional",
|
||||
companyName: "",
|
||||
},
|
||||
});
|
||||
|
||||
// 2. Clean Zero-Balance Standard COA for Default Company
|
||||
for (const acc of DEFAULT_ACCOUNTS) {
|
||||
const exists = await prisma.account.findFirst({
|
||||
where: { code: acc.code, companyName: DEFAULT_COMPANY },
|
||||
});
|
||||
if (!exists) {
|
||||
await prisma.account.create({
|
||||
data: {
|
||||
code: acc.code,
|
||||
name: acc.name,
|
||||
type: acc.type,
|
||||
companyName: DEFAULT_COMPANY,
|
||||
balance: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Clean Default System Settings
|
||||
// 2. Pengaturan Awal (Daftar PT & Profil Perusahaan KOSONG — ditambahkan manual oleh user!)
|
||||
const defaultSettings = [
|
||||
{ key: "PAYROLL_COMPANIES", value: JSON.stringify([DEFAULT_COMPANY]), category: "FINANCE" },
|
||||
{ key: "PAYROLL_COMPANIES", value: JSON.stringify([]), category: "FINANCE" },
|
||||
{ key: "COMPANY_PROFILES", value: JSON.stringify({}), category: "FINANCE" },
|
||||
{ key: "EMAIL_ENABLED", value: "false", category: "EMAIL" },
|
||||
{ key: "TELEGRAM_ENABLED", value: "false", category: "TELEGRAM" },
|
||||
{ key: "NOTIF_STOCK_IN_ENABLED", value: "true", category: "NOTIFICATION" },
|
||||
@@ -182,7 +149,7 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Create 1 Dummy User for Each of the 6 RBAC Roles
|
||||
// 3. Create 1 Dummy User for Each of the 6 RBAC Roles
|
||||
for (const u of DUMMY_USERS) {
|
||||
const hashedPassword = await bcrypt.hash(u.password, 10);
|
||||
await prisma.user.upsert({
|
||||
@@ -218,7 +185,7 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
console.log("✓ Database bersih siap pakai dengan 6 akun dummy untuk semua role RBAC!");
|
||||
console.log("✓ Database bersih siap pakai (0 PT bawaan sistem, 6 akun dummy untuk semua role RBAC)!");
|
||||
}
|
||||
|
||||
main()
|
||||
|
||||
+110
-34
@@ -1,15 +1,25 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { ensureCompanyAccounts, getSavedCompanies } from "@/lib/companies";
|
||||
import {
|
||||
ensureCompanyAccounts,
|
||||
getSavedCompanies,
|
||||
getCompanyProfiles,
|
||||
saveCompanyProfiles,
|
||||
upsertCompanyProfile,
|
||||
renameCompanyAcrossSystem,
|
||||
} from "@/lib/companies";
|
||||
|
||||
export async function GET() {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ user: null }, { status: 401 });
|
||||
}
|
||||
const companies = await getSavedCompanies();
|
||||
return NextResponse.json({ user, companies });
|
||||
const [companies, companyProfiles] = await Promise.all([
|
||||
getSavedCompanies(),
|
||||
getCompanyProfiles(),
|
||||
]);
|
||||
return NextResponse.json({ user, companies, companyProfiles });
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
@@ -21,7 +31,7 @@ export async function POST(req: Request) {
|
||||
|
||||
const body = await req.json();
|
||||
|
||||
// User Finance, Manager, dan Admin di menu keuangan bisa View & Add PT
|
||||
// Tambah Entitas PT Baru (+ profil & logo opsional)
|
||||
if (body.action === "ADD_COMPANY") {
|
||||
if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(currentUser.role)) {
|
||||
return NextResponse.json(
|
||||
@@ -50,8 +60,67 @@ export async function POST(req: Request) {
|
||||
});
|
||||
|
||||
await ensureCompanyAccounts(cleanComp);
|
||||
const companyProfiles = body.profile
|
||||
? await upsertCompanyProfile(cleanComp, body.profile)
|
||||
: await upsertCompanyProfile(cleanComp, { name: cleanComp });
|
||||
|
||||
return NextResponse.json({ success: true, companies: list, added: cleanComp });
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
companies: list,
|
||||
companyProfiles,
|
||||
added: cleanComp,
|
||||
});
|
||||
}
|
||||
|
||||
// Update Profil / Logo / Template Dokumen / Rename PT
|
||||
if (body.action === "UPDATE_COMPANY_PROFILE") {
|
||||
if (!["ADMIN", "MANAGER", "ACCOUNTANT", "SALES"].includes(currentUser.role)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Akses ditolak: Anda tidak berwenang mengubah profil atau template perusahaan." },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const oldName = String(body.oldName || body.companyName || "").trim();
|
||||
const newName = String(body.newName || body.companyName || "").trim();
|
||||
if (!oldName || !newName) {
|
||||
return NextResponse.json({ error: "Nama perusahaan wajib diisi." }, { status: 400 });
|
||||
}
|
||||
|
||||
// Hanya Admin/Manager/Accountant yang boleh me-rename PT
|
||||
if (oldName !== newName && !["ADMIN", "MANAGER", "ACCOUNTANT"].includes(currentUser.role)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Akses ditolak: Hanya Finance, Manager, dan Admin yang boleh mengubah nama PT." },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
let companies = await getSavedCompanies();
|
||||
if (oldName !== newName) {
|
||||
const renamed = await renameCompanyAcrossSystem(oldName, newName);
|
||||
companies = renamed.companies;
|
||||
} else if (!companies.includes(newName)) {
|
||||
companies.push(newName);
|
||||
await prisma.systemSetting.upsert({
|
||||
where: { key: "PAYROLL_COMPANIES" },
|
||||
update: { value: JSON.stringify(companies) },
|
||||
create: {
|
||||
key: "PAYROLL_COMPANIES",
|
||||
value: JSON.stringify(companies),
|
||||
category: "FINANCE",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await ensureCompanyAccounts(newName);
|
||||
const companyProfiles = await upsertCompanyProfile(newName, body.profile || {});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
companies,
|
||||
companyProfiles,
|
||||
companyName: newName,
|
||||
});
|
||||
}
|
||||
|
||||
// HANYA SUPERADMIN (ADMIN) YANG BISA HAPUS PT
|
||||
@@ -60,7 +129,7 @@ export async function POST(req: Request) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Akses ditolak: Hanya Super Admin yang dapat menghapus Entitas PT. Selain Super Admin hanya dapat melihat (view) dan menambah (add) PT.",
|
||||
"Akses ditolak: Hanya Super Admin yang dapat menghapus Entitas PT.",
|
||||
},
|
||||
{ status: 403 }
|
||||
);
|
||||
@@ -76,21 +145,12 @@ export async function POST(req: Request) {
|
||||
|
||||
const currentList = await getSavedCompanies();
|
||||
const updatedList = currentList.filter((c) => c !== targetComp);
|
||||
const fallbackCompany = updatedList[0] || "";
|
||||
|
||||
if (updatedList.length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Tidak dapat menghapus satu-satunya Entitas PT yang tersisa. Tambahkan PT lain terlebih dahulu sebelum menghapus PT ini.",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const profiles = await getCompanyProfiles();
|
||||
delete profiles[targetComp];
|
||||
|
||||
const fallbackCompany = updatedList[0];
|
||||
|
||||
// Simpan daftar PT terbaru dan pindahkan referensi PT yang dihapus ke PT utama yang tersisa
|
||||
await Promise.all([
|
||||
const tasks: Promise<any>[] = [
|
||||
prisma.systemSetting.upsert({
|
||||
where: { key: "PAYROLL_COMPANIES" },
|
||||
update: { value: JSON.stringify(updatedList) },
|
||||
@@ -100,31 +160,47 @@ export async function POST(req: Request) {
|
||||
category: "FINANCE",
|
||||
},
|
||||
}),
|
||||
prisma.account.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
prisma.payrollEmployee.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
prisma.payrollRecord.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
]);
|
||||
saveCompanyProfiles(profiles),
|
||||
];
|
||||
|
||||
if (fallbackCompany) {
|
||||
tasks.push(
|
||||
prisma.account.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
prisma.payrollEmployee.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
prisma.payrollRecord.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
})
|
||||
);
|
||||
} else {
|
||||
// Jika menjadi 0 PT, bersihkan akun COA bersaldo 0 milik PT yang dihapus
|
||||
tasks.push(
|
||||
prisma.account.deleteMany({
|
||||
where: { companyName: targetComp, balance: 0 },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.all(tasks);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
companies: updatedList,
|
||||
companyProfiles: profiles,
|
||||
deleted: targetComp,
|
||||
fallbackCompany,
|
||||
fallbackCompany: fallbackCompany || "ALL",
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "Aksi tidak dikenali" }, { status: 400 });
|
||||
} catch (error: any) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
return NextResponse.json({ error: error.message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+121
-64
@@ -3,6 +3,14 @@ import { prisma } from "@/lib/db";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { logAudit } from "@/lib/audit";
|
||||
import { dispatchNotification } from "@/lib/notifier";
|
||||
import {
|
||||
ensureCompanyAccounts,
|
||||
getCompanyProfiles,
|
||||
getSavedCompanies,
|
||||
saveCompanyProfiles,
|
||||
upsertCompanyProfile,
|
||||
renameCompanyAcrossSystem,
|
||||
} from "@/lib/companies";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
@@ -120,23 +128,21 @@ export async function GET() {
|
||||
payrollRecords.forEach((r) => r.role && posSet.add(r.role));
|
||||
const positions = Array.from(posSet);
|
||||
|
||||
// Gabungkan daftar Entitas PT (Perusahaan) untuk pemisahan Payroll & Bank per PT
|
||||
// Daftar Entitas PT murni dari yang ditambahkan user (tidak ada PT hardcoded by system)
|
||||
const compSet = new Set<string>();
|
||||
if (compSetting?.value) {
|
||||
try {
|
||||
const parsedComp: string[] = JSON.parse(compSetting.value);
|
||||
parsedComp.forEach((c) => c && compSet.add(c));
|
||||
parsedComp.forEach((c) => c && compSet.add(c.trim()));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
if (compSet.size === 0) {
|
||||
compSet.add("PT EnterpriseCore Utama");
|
||||
}
|
||||
accounts.forEach((a) => a.companyName && compSet.add(a.companyName));
|
||||
payrollEmployees.forEach((e) => e.companyName && compSet.add(e.companyName));
|
||||
payrollRecords.forEach((r) => r.companyName && compSet.add(r.companyName));
|
||||
const companies = Array.from(compSet);
|
||||
accounts.forEach((a) => a.companyName && compSet.add(a.companyName.trim()));
|
||||
payrollEmployees.forEach((e) => e.companyName && compSet.add(e.companyName.trim()));
|
||||
payrollRecords.forEach((r) => r.companyName && compSet.add(r.companyName.trim()));
|
||||
const companies = Array.from(compSet).filter(Boolean);
|
||||
const companyProfiles = await getCompanyProfiles();
|
||||
|
||||
const nowMs = Date.now();
|
||||
const arList = openSalesOrders
|
||||
@@ -190,6 +196,7 @@ export async function GET() {
|
||||
payrollEmployees,
|
||||
positions,
|
||||
companies,
|
||||
companyProfiles,
|
||||
arList,
|
||||
apList,
|
||||
});
|
||||
@@ -209,7 +216,7 @@ export async function POST(req: Request) {
|
||||
const body = await req.json();
|
||||
|
||||
// =========================================================================
|
||||
// A1. TAMBAH ENTITAS PT BARU UNTUK PEMISAHAN PAYROLL & AKUN BANK
|
||||
// A1. TAMBAH ENTITAS PT BARU (+ PROFIL, LOGO & COA OTOMATIS)
|
||||
// =========================================================================
|
||||
if (body.action === "ADD_COMPANY") {
|
||||
if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) {
|
||||
@@ -220,18 +227,7 @@ export async function POST(req: Request) {
|
||||
return NextResponse.json({ error: "Nama PT wajib diisi" }, { status: 400 });
|
||||
}
|
||||
|
||||
const existingSetting = await prisma.systemSetting.findUnique({
|
||||
where: { key: "PAYROLL_COMPANIES" },
|
||||
});
|
||||
|
||||
let list: string[] = ["PT EnterpriseCore Utama"];
|
||||
if (existingSetting?.value) {
|
||||
try {
|
||||
list = JSON.parse(existingSetting.value);
|
||||
} catch {
|
||||
list = ["PT EnterpriseCore Utama"];
|
||||
}
|
||||
}
|
||||
const list = await getSavedCompanies();
|
||||
if (!list.includes(newComp)) {
|
||||
list.push(newComp);
|
||||
}
|
||||
@@ -246,7 +242,71 @@ export async function POST(req: Request) {
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, companies: list });
|
||||
await ensureCompanyAccounts(newComp);
|
||||
const companyProfiles = await upsertCompanyProfile(newComp, body.profile || { name: newComp });
|
||||
|
||||
await logAudit({
|
||||
userId: user.id,
|
||||
userName: user.name,
|
||||
action: "ADD_COMPANY",
|
||||
module: "FINANCE",
|
||||
description: `[${user.role}] Menambahkan perusahaan baru: ${newComp}`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, companies: list, companyProfiles });
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// A1-A. EDIT NAMA PT, UPLOAD LOGO, & TEMPLATE DOKUMEN (INVOICE / BAST)
|
||||
// =========================================================================
|
||||
if (body.action === "UPDATE_COMPANY_PROFILE") {
|
||||
if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Akses ditolak: Hanya Finance, Manager, dan Admin yang dapat mengubah profil PT." },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const oldName = String(body.oldName || body.companyName || "").trim();
|
||||
const newName = String(body.newName || body.companyName || "").trim();
|
||||
if (!oldName || !newName) {
|
||||
return NextResponse.json({ error: "Nama PT wajib diisi" }, { status: 400 });
|
||||
}
|
||||
|
||||
let companies = await getSavedCompanies();
|
||||
if (oldName !== newName) {
|
||||
const resRename = await renameCompanyAcrossSystem(oldName, newName);
|
||||
companies = resRename.companies;
|
||||
} else if (!companies.includes(newName)) {
|
||||
companies.push(newName);
|
||||
await prisma.systemSetting.upsert({
|
||||
where: { key: "PAYROLL_COMPANIES" },
|
||||
update: { value: JSON.stringify(companies) },
|
||||
create: {
|
||||
key: "PAYROLL_COMPANIES",
|
||||
value: JSON.stringify(companies),
|
||||
category: "FINANCE",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await ensureCompanyAccounts(newName);
|
||||
const companyProfiles = await upsertCompanyProfile(newName, body.profile || {});
|
||||
|
||||
await logAudit({
|
||||
userId: user.id,
|
||||
userName: user.name,
|
||||
action: "UPDATE_COMPANY",
|
||||
module: "FINANCE",
|
||||
description: `[${user.role}] Memperbarui profil/logo/template PT${oldName !== newName ? ` (${oldName} → ${newName})` : `: ${newName}`}`,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
companies,
|
||||
companyProfiles,
|
||||
companyName: newName,
|
||||
});
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
@@ -257,39 +317,21 @@ export async function POST(req: Request) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Akses ditolak: Hanya Super Admin yang dapat menghapus Entitas PT. Selain Super Admin hanya dapat melihat (view) dan menambah (add) PT.",
|
||||
"Akses ditolak: Hanya Super Admin yang dapat menghapus Entitas PT.",
|
||||
},
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const targetComp = (body.companyName || "").trim();
|
||||
const existingSetting = await prisma.systemSetting.findUnique({
|
||||
where: { key: "PAYROLL_COMPANIES" },
|
||||
});
|
||||
|
||||
let list: string[] = ["PT EnterpriseCore Utama"];
|
||||
if (existingSetting?.value) {
|
||||
try {
|
||||
list = JSON.parse(existingSetting.value);
|
||||
} catch {
|
||||
list = ["PT EnterpriseCore Utama"];
|
||||
}
|
||||
}
|
||||
|
||||
const list = await getSavedCompanies();
|
||||
const updatedList = list.filter((c) => c !== targetComp);
|
||||
if (updatedList.length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Tidak dapat menghapus satu-satunya Entitas PT yang tersisa. Tambahkan PT lain terlebih dahulu sebelum menghapus PT ini.",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const fallbackCompany = updatedList[0] || "";
|
||||
|
||||
const fallbackCompany = updatedList[0];
|
||||
await Promise.all([
|
||||
const profiles = await getCompanyProfiles();
|
||||
delete profiles[targetComp];
|
||||
|
||||
const tasks: Promise<any>[] = [
|
||||
prisma.systemSetting.upsert({
|
||||
where: { key: "PAYROLL_COMPANIES" },
|
||||
update: { value: JSON.stringify(updatedList) },
|
||||
@@ -299,24 +341,39 @@ export async function POST(req: Request) {
|
||||
category: "FINANCE",
|
||||
},
|
||||
}),
|
||||
prisma.account.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
prisma.payrollEmployee.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
prisma.payrollRecord.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
]);
|
||||
saveCompanyProfiles(profiles),
|
||||
];
|
||||
|
||||
if (fallbackCompany) {
|
||||
tasks.push(
|
||||
prisma.account.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
prisma.payrollEmployee.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
}),
|
||||
prisma.payrollRecord.updateMany({
|
||||
where: { companyName: targetComp },
|
||||
data: { companyName: fallbackCompany },
|
||||
})
|
||||
);
|
||||
} else {
|
||||
tasks.push(
|
||||
prisma.account.deleteMany({
|
||||
where: { companyName: targetComp, balance: 0 },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.all(tasks);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
companies: updatedList,
|
||||
fallbackCompany,
|
||||
companyProfiles: profiles,
|
||||
fallbackCompany: fallbackCompany || "ALL",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1073,12 +1130,12 @@ export async function POST(req: Request) {
|
||||
});
|
||||
}
|
||||
|
||||
let compList: string[] = ["PT EnterpriseCore Utama"];
|
||||
let compList: string[] = [];
|
||||
if (compSetting?.value) {
|
||||
try {
|
||||
compList = JSON.parse(compSetting.value);
|
||||
} catch {
|
||||
compList = ["PT EnterpriseCore Utama"];
|
||||
compList = [];
|
||||
}
|
||||
}
|
||||
if (!compList.includes(cleanCompany)) {
|
||||
|
||||
+672
-115
@@ -5,6 +5,7 @@ import { AppShell } from "@/components/AppShell";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { CurrencyInput } from "@/components/CurrencyInput";
|
||||
import { formatRupiah, formatDateTime, exportToCSV, escapeHtml } from "@/lib/utils";
|
||||
import type { CompanyProfile } from "@/lib/companies";
|
||||
import {
|
||||
Plus,
|
||||
ArrowRightLeft,
|
||||
@@ -25,6 +26,8 @@ import {
|
||||
Download,
|
||||
Trash2,
|
||||
BarChart3,
|
||||
Upload,
|
||||
Image as ImageIcon,
|
||||
} from "lucide-react";
|
||||
import { FinancialChart } from "@/components/FinancialChart";
|
||||
|
||||
@@ -38,7 +41,7 @@ const DEFAULT_POSITIONS = [
|
||||
"Supervisor",
|
||||
];
|
||||
|
||||
const DEFAULT_COMPANIES = ["PT EnterpriseCore Utama"];
|
||||
const DEFAULT_COMPANIES: string[] = [];
|
||||
|
||||
const MONTHS_ID = [
|
||||
"Januari",
|
||||
@@ -67,7 +70,38 @@ export default function FinancePage() {
|
||||
const [apList, setApList] = useState<any[]>([]);
|
||||
const [positions, setPositions] = useState<string[]>(DEFAULT_POSITIONS);
|
||||
const [companies, setCompanies] = useState<string[]>(DEFAULT_COMPANIES);
|
||||
const [companyProfiles, setCompanyProfiles] = useState<Record<string, CompanyProfile>>({});
|
||||
const [selectedCompanyFilter, setSelectedCompanyFilter] = useState<string>("ALL");
|
||||
|
||||
// Modal Tambah / Edit PT, Logo & Template Dokumen (Invoice & Surat Serah Terima)
|
||||
const [isCompanyModalOpen, setIsCompanyModalOpen] = useState(false);
|
||||
const [editingCompanyOriginalName, setEditingCompanyOriginalName] = useState<string | null>(null);
|
||||
const [compFormName, setCompFormName] = useState("");
|
||||
const [compFormLogo, setCompFormLogo] = useState<string>("");
|
||||
const [compFormTagline, setCompFormTagline] = useState("");
|
||||
const [compFormAddress, setCompFormAddress] = useState("");
|
||||
const [compFormPhone, setCompFormPhone] = useState("");
|
||||
const [compFormEmail, setCompFormEmail] = useState("");
|
||||
const [compFormNpwp, setCompFormNpwp] = useState("");
|
||||
const [compFormBankInfo, setCompFormBankInfo] = useState("");
|
||||
const [compFormInvTitle, setCompFormInvTitle] = useState("INVOICE");
|
||||
const [compFormInvSubtitle, setCompFormInvSubtitle] = useState("Faktur Tagihan Penjualan Resmi");
|
||||
const [compFormInvFooter, setCompFormInvFooter] = useState("");
|
||||
const [compFormInvSignerLabel, setCompFormInvSignerLabel] = useState("Bagian Penjualan / Finance");
|
||||
const [compFormInvSignerName, setCompFormInvSignerName] = useState("");
|
||||
const [compFormDelTitle, setCompFormDelTitle] = useState("SURAT SERAH TERIMA BARANG");
|
||||
const [compFormDelSubtitle, setCompFormDelSubtitle] = useState("Berita Acara Serah Terima & Pengiriman Barang");
|
||||
const [compFormDelIntro, setCompFormDelIntro] = useState(
|
||||
"Dengan ini kami menyerahkan barang/perangkat berikut dalam kondisi baik dan lengkap kepada pihak penerima:"
|
||||
);
|
||||
const [compFormDelFooter, setCompFormDelFooter] = useState(
|
||||
"Barang yang telah diterima dan ditandatangani dianggap telah diperiksa sesuai pesanan."
|
||||
);
|
||||
const [compFormDelSenderLabel, setCompFormDelSenderLabel] = useState("Yang Menyerahkan");
|
||||
const [compFormDelSenderName, setCompFormDelSenderName] = useState("");
|
||||
const [compFormDelReceiverLabel, setCompFormDelReceiverLabel] = useState("Yang Menerima");
|
||||
const [compFormSaving, setCompFormSaving] = useState(false);
|
||||
const [compFormError, setCompFormError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState<
|
||||
"reports" | "payroll" | "coa" | "journal" | "companies"
|
||||
@@ -89,7 +123,7 @@ export default function FinancePage() {
|
||||
const [accCode, setAccCode] = useState("");
|
||||
const [accName, setAccName] = useState("");
|
||||
const [accType, setAccType] = useState("ASSET");
|
||||
const [accCompany, setAccCompany] = useState("PT EnterpriseCore Utama");
|
||||
const [accCompany, setAccCompany] = useState("");
|
||||
const [accBalance, setAccBalance] = useState<number | "">(0);
|
||||
const [accSubmitting, setAccSubmitting] = useState(false);
|
||||
const [accError, setAccError] = useState<string | null>(null);
|
||||
@@ -117,7 +151,7 @@ export default function FinancePage() {
|
||||
|
||||
// Mode Input PT (Perusahaan) pada Payroll
|
||||
const [companyInputMode, setCompanyInputMode] = useState<"SELECT" | "NEW">("SELECT");
|
||||
const [payrollCompany, setPayrollCompany] = useState("PT EnterpriseCore Utama");
|
||||
const [payrollCompany, setPayrollCompany] = useState("");
|
||||
const [newCompanyName, setNewCompanyName] = useState("");
|
||||
|
||||
// Mode Input Karyawan: jika sudah ada data payroll tersimpan, otomatis pakai Dropdown ("SELECT"), jika belum ada pakai "NEW"
|
||||
@@ -178,15 +212,19 @@ export default function FinancePage() {
|
||||
);
|
||||
setPositions(mergedPositions);
|
||||
|
||||
const mergedCompanies =
|
||||
Array.isArray(json.companies) && json.companies.length > 0
|
||||
? Array.from(new Set<string>(json.companies))
|
||||
: DEFAULT_COMPANIES;
|
||||
const mergedCompanies = Array.isArray(json.companies)
|
||||
? Array.from(new Set<string>(json.companies.filter(Boolean)))
|
||||
: [];
|
||||
const loadedProfiles: Record<string, CompanyProfile> =
|
||||
json.companyProfiles && typeof json.companyProfiles === "object"
|
||||
? json.companyProfiles
|
||||
: {};
|
||||
setCompanies(mergedCompanies);
|
||||
setCompanyProfiles(loadedProfiles);
|
||||
if (typeof window !== "undefined") {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("erp:company-sync", {
|
||||
detail: { companies: mergedCompanies },
|
||||
detail: { companies: mergedCompanies, companyProfiles: loadedProfiles },
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -194,14 +232,14 @@ export default function FinancePage() {
|
||||
if (savedEmps.length > 0) {
|
||||
setEmployeeInputMode("SELECT");
|
||||
setEmployeeName(savedEmps[0].name);
|
||||
setPayrollCompany(savedEmps[0].companyName || mergedCompanies[0]);
|
||||
setPayrollCompany(savedEmps[0].companyName || mergedCompanies[0] || "");
|
||||
setEmployeeRole(savedEmps[0].position || mergedPositions[0]);
|
||||
setBaseSalary(savedEmps[0].baseSalary || 5000000);
|
||||
setDailyMealRate(savedEmps[0].dailyMealRate || 35000);
|
||||
} else {
|
||||
setEmployeeInputMode("NEW");
|
||||
setEmployeeName("");
|
||||
setPayrollCompany(mergedCompanies[0]);
|
||||
setPayrollCompany(mergedCompanies[0] || "");
|
||||
setEmployeeRole(mergedPositions[0]);
|
||||
}
|
||||
|
||||
@@ -525,7 +563,7 @@ export default function FinancePage() {
|
||||
defaultCompany ||
|
||||
(selectedCompanyFilter !== "ALL"
|
||||
? selectedCompanyFilter
|
||||
: companies[0] || "PT EnterpriseCore Utama")
|
||||
: companies[0] || "")
|
||||
);
|
||||
setAccBalance(0);
|
||||
setIsAccountModalOpen(true);
|
||||
@@ -621,6 +659,173 @@ export default function FinancePage() {
|
||||
}
|
||||
};
|
||||
|
||||
const openCompanyProfileModal = (existingName: string | null) => {
|
||||
setCompFormError(null);
|
||||
setEditingCompanyOriginalName(existingName);
|
||||
const prof = existingName ? companyProfiles[existingName] : undefined;
|
||||
setCompFormName(existingName || "");
|
||||
setCompFormLogo(prof?.logoDataUrl || "");
|
||||
setCompFormTagline(prof?.tagline || "");
|
||||
setCompFormAddress(prof?.address || "");
|
||||
setCompFormPhone(prof?.phone || "");
|
||||
setCompFormEmail(prof?.email || "");
|
||||
setCompFormNpwp(prof?.npwp || "");
|
||||
setCompFormBankInfo(prof?.bankInfo || "");
|
||||
setCompFormInvTitle(prof?.invoiceTitle || "INVOICE");
|
||||
setCompFormInvSubtitle(prof?.invoiceSubtitle || "Faktur Tagihan Penjualan Resmi");
|
||||
setCompFormInvFooter(prof?.invoiceFooterNotes || "");
|
||||
setCompFormInvSignerLabel(prof?.invoiceSignerLabel || "Bagian Penjualan / Finance");
|
||||
setCompFormInvSignerName(prof?.invoiceSignerName || "");
|
||||
setCompFormDelTitle(prof?.deliveryTitle || "SURAT SERAH TERIMA BARANG");
|
||||
setCompFormDelSubtitle(prof?.deliverySubtitle || "Berita Acara Serah Terima & Pengiriman Barang");
|
||||
setCompFormDelIntro(
|
||||
prof?.deliveryIntroText ||
|
||||
"Dengan ini kami menyerahkan barang/perangkat berikut dalam kondisi baik dan lengkap kepada pihak penerima:"
|
||||
);
|
||||
setCompFormDelFooter(
|
||||
prof?.deliveryFooterNotes ||
|
||||
"Barang yang telah diterima dan ditandatangani dianggap telah diperiksa sesuai pesanan."
|
||||
);
|
||||
setCompFormDelSenderLabel(prof?.deliverySenderLabel || "Yang Menyerahkan");
|
||||
setCompFormDelSenderName(prof?.deliverySenderName || "");
|
||||
setCompFormDelReceiverLabel(prof?.deliveryReceiverLabel || "Yang Menerima");
|
||||
setIsCompanyModalOpen(true);
|
||||
};
|
||||
|
||||
const handleLogoFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
if (!/^image\/(png|jpeg|jpg|webp|gif)$/.test(file.type)) {
|
||||
setCompFormError("Format file logo harus PNG, JPG, atau WEBP.");
|
||||
return;
|
||||
}
|
||||
if (file.size > 3 * 1024 * 1024) {
|
||||
setCompFormError("Ukuran file logo maksimal 3 MB.");
|
||||
return;
|
||||
}
|
||||
setCompFormError(null);
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const img = new window.Image();
|
||||
img.onload = () => {
|
||||
const maxDim = 360;
|
||||
let w = img.width;
|
||||
let h = img.height;
|
||||
if (w > maxDim || h > maxDim) {
|
||||
const ratio = Math.min(maxDim / w, maxDim / h);
|
||||
w = Math.round(w * ratio);
|
||||
h = Math.round(h * ratio);
|
||||
}
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (ctx) {
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
const dataUrl = canvas.toDataURL("image/png");
|
||||
setCompFormLogo(dataUrl);
|
||||
}
|
||||
};
|
||||
img.src = String(reader.result || "");
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
const handleSaveCompanyProfile = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const cleanName = compFormName.trim();
|
||||
if (!cleanName) {
|
||||
setCompFormError("Nama Perusahaan (PT) wajib diisi.");
|
||||
return;
|
||||
}
|
||||
setCompFormSaving(true);
|
||||
setCompFormError(null);
|
||||
|
||||
try {
|
||||
const profile: Partial<CompanyProfile> = {
|
||||
name: cleanName,
|
||||
logoDataUrl: compFormLogo || "",
|
||||
tagline: compFormTagline.trim(),
|
||||
address: compFormAddress.trim(),
|
||||
phone: compFormPhone.trim(),
|
||||
email: compFormEmail.trim(),
|
||||
npwp: compFormNpwp.trim(),
|
||||
bankInfo: compFormBankInfo.trim(),
|
||||
invoiceTitle: compFormInvTitle.trim() || "INVOICE",
|
||||
invoiceSubtitle: compFormInvSubtitle.trim(),
|
||||
invoiceFooterNotes: compFormInvFooter.trim(),
|
||||
invoiceSignerLabel: compFormInvSignerLabel.trim(),
|
||||
invoiceSignerName: compFormInvSignerName.trim(),
|
||||
deliveryTitle: compFormDelTitle.trim() || "SURAT SERAH TERIMA BARANG",
|
||||
deliverySubtitle: compFormDelSubtitle.trim(),
|
||||
deliveryIntroText: compFormDelIntro.trim(),
|
||||
deliveryFooterNotes: compFormDelFooter.trim(),
|
||||
deliverySenderLabel: compFormDelSenderLabel.trim(),
|
||||
deliverySenderName: compFormDelSenderName.trim(),
|
||||
deliveryReceiverLabel: compFormDelReceiverLabel.trim(),
|
||||
};
|
||||
|
||||
const isEdit = Boolean(editingCompanyOriginalName);
|
||||
const res = await fetch("/api/finance", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(
|
||||
isEdit
|
||||
? {
|
||||
action: "UPDATE_COMPANY_PROFILE",
|
||||
oldName: editingCompanyOriginalName,
|
||||
newName: cleanName,
|
||||
profile,
|
||||
}
|
||||
: {
|
||||
action: "ADD_COMPANY",
|
||||
companyName: cleanName,
|
||||
profile,
|
||||
}
|
||||
),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "Gagal menyimpan profil perusahaan");
|
||||
|
||||
const updatedCompanies: string[] = Array.isArray(data.companies) ? data.companies : companies;
|
||||
const updatedProfiles: Record<string, CompanyProfile> =
|
||||
data.companyProfiles && typeof data.companyProfiles === "object"
|
||||
? data.companyProfiles
|
||||
: companyProfiles;
|
||||
|
||||
setCompanies(updatedCompanies);
|
||||
setCompanyProfiles(updatedProfiles);
|
||||
|
||||
const nextSelected =
|
||||
editingCompanyOriginalName && selectedCompanyFilter === editingCompanyOriginalName
|
||||
? cleanName
|
||||
: selectedCompanyFilter === "ALL" && updatedCompanies.length === 1
|
||||
? cleanName
|
||||
: selectedCompanyFilter;
|
||||
setSelectedCompanyFilter(nextSelected);
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("erp_selected_pt", nextSelected);
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("erp:company-sync", {
|
||||
detail: {
|
||||
selectedCompany: nextSelected,
|
||||
companies: updatedCompanies,
|
||||
companyProfiles: updatedProfiles,
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
setIsCompanyModalOpen(false);
|
||||
await loadData();
|
||||
} catch (err: any) {
|
||||
setCompFormError(err.message);
|
||||
} finally {
|
||||
setCompFormSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateJournal = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
@@ -801,7 +1006,12 @@ export default function FinancePage() {
|
||||
const printWindow = window.open("", "_blank", "width=800,height=700");
|
||||
if (!printWindow) return;
|
||||
|
||||
const ptName = escapeHtml(slip.companyName || "PT EnterpriseCore Utama");
|
||||
const ptNameRaw = slip.companyName || companies[0] || "";
|
||||
const ptProfile = companyProfiles[ptNameRaw];
|
||||
const ptName = escapeHtml(ptNameRaw || "Perusahaan");
|
||||
const ptLogoHtml = ptProfile?.logoDataUrl
|
||||
? `<img src="${ptProfile.logoDataUrl}" alt="Logo" style="height:46px;max-width:140px;object-fit:contain;margin-right:12px;" />`
|
||||
: "";
|
||||
const bankLabel = escapeHtml(slip.paymentAccountName || "Rekening Bank / Kas Perusahaan");
|
||||
const empName = escapeHtml(slip.employeeName);
|
||||
const empRole = escapeHtml(slip.role);
|
||||
@@ -834,10 +1044,14 @@ export default function FinancePage() {
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<div>
|
||||
<div class="company">${ptName}</div>
|
||||
<div class="sub">Dokumen Resmi Slip Gaji, Uang Makan & Kehadiran Karyawan</div>
|
||||
<div class="sub">Sumber Pembayaran: <strong>${bankLabel}</strong></div>
|
||||
<div style="display:flex;align-items:center;">
|
||||
${ptLogoHtml}
|
||||
<div>
|
||||
<div class="company">${ptName}</div>
|
||||
${ptProfile?.address ? `<div class="sub">${escapeHtml(ptProfile.address)}</div>` : ""}
|
||||
<div class="sub">Dokumen Resmi Slip Gaji, Uang Makan & Kehadiran Karyawan</div>
|
||||
<div class="sub">Sumber Pembayaran: <strong>${bankLabel}</strong></div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="text-align: right;">
|
||||
<div class="badge">LUNAS (PAID)</div>
|
||||
@@ -1954,131 +2168,159 @@ export default function FinancePage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* TAB 4: KELOLA ENTITAS PT (PERUSAHAAN) */}
|
||||
{/* TAB 4: KELOLA ENTITAS PT (PERUSAHAAN, LOGO & TEMPLATE DOKUMEN) */}
|
||||
{activeTab === "companies" && (
|
||||
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
|
||||
<div className="px-6 py-4 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-slate-50/50">
|
||||
<div>
|
||||
<h3 className="text-sm font-bold text-slate-800">
|
||||
Manajemen Entitas Perusahaan (PT) — Payroll & Rekening Bank
|
||||
Manajemen Perusahaan (PT), Logo & Template Dokumen
|
||||
</h3>
|
||||
<p className="text-[11px] text-slate-500">
|
||||
Semua pengguna Keuangan dapat melihat (View) dan menambah (Add) PT baru.{" "}
|
||||
<strong>Penghapusan PT dikhususkan hanya untuk Super Admin.</strong>
|
||||
Tambahkan atau ubah nama PT, upload logo resmi perusahaan (otomatis tampil di Sidebar & dokumen cetak), serta kustomisasi template Invoice & Surat Serah Terima Barang.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Form Cepat Tambah Entitas PT Baru */}
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Ketik nama PT baru (misal: PT Maju Jaya)..."
|
||||
value={newCompanyName}
|
||||
onChange={(e) => setNewCompanyName(e.target.value)}
|
||||
className="px-3 py-2 text-xs bg-white border border-slate-300 rounded-lg font-semibold w-64 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddCompany}
|
||||
disabled={!newCompanyName.trim()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-semibold shadow-2xs disabled:opacity-50 transition-colors shrink-0"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
<span>Tambah PT Baru</span>
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openCompanyProfileModal(null)}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white rounded-lg text-xs font-semibold shadow-2xs transition-colors shrink-0"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
<span>Tambah Perusahaan (PT)</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse text-xs">
|
||||
<thead>
|
||||
<tr className="bg-slate-50 text-slate-500 font-semibold border-b border-slate-100">
|
||||
<th className="py-3 px-6">Nama Entitas PT</th>
|
||||
<th className="py-3 px-4 text-center">Jumlah Akun / Bank</th>
|
||||
<th className="py-3 px-4 text-center">Jumlah Slip Gaji</th>
|
||||
<th className="py-3 px-4 text-right">Total Payroll Terbayar</th>
|
||||
<th className="py-3 px-6">Perusahaan & Logo</th>
|
||||
<th className="py-3 px-4">Kontak & Rekening</th>
|
||||
<th className="py-3 px-4 text-center">Akun / Slip</th>
|
||||
<th className="py-3 px-4 text-right">Total Payroll</th>
|
||||
<th className="py-3 px-6 text-right">Tindakan</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{companies.map((comp) => {
|
||||
const ptAccounts = accounts.filter(
|
||||
(a) => (a.companyName || "PT EnterpriseCore Utama") === comp
|
||||
);
|
||||
const ptPayrolls = payrollRecords.filter(
|
||||
(r) => (r.companyName || "PT EnterpriseCore Utama") === comp
|
||||
);
|
||||
const ptTotalPaid = ptPayrolls.reduce((s, r) => s + r.netSalary, 0);
|
||||
const isCurrentlySelected = selectedCompanyFilter === comp;
|
||||
{companies.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="py-12 px-6 text-center">
|
||||
<div className="max-w-md mx-auto space-y-2">
|
||||
<Building2 className="h-8 w-8 text-slate-400 mx-auto" />
|
||||
<p className="text-sm font-bold text-slate-800">
|
||||
Belum ada perusahaan (PT) yang didaftarkan
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Silakan klik tombol <strong>Tambah Perusahaan (PT)</strong> di kanan atas untuk menambahkan nama PT, logo perusahaan, dan template Invoice/Surat Serah Terima Anda.
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
companies.map((comp) => {
|
||||
const prof = companyProfiles[comp];
|
||||
const ptAccounts = accounts.filter((a) => a.companyName === comp);
|
||||
const ptPayrolls = payrollRecords.filter((r) => r.companyName === comp);
|
||||
const ptTotalPaid = ptPayrolls.reduce((s, r) => s + r.netSalary, 0);
|
||||
const isCurrentlySelected = selectedCompanyFilter === comp;
|
||||
|
||||
return (
|
||||
<tr key={comp} className="hover:bg-slate-50/60 transition-colors">
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Building2 className="h-4 w-4 text-blue-600" />
|
||||
<span className="font-bold text-slate-900 text-sm">{comp}</span>
|
||||
{isCurrentlySelected && (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
PT Aktif Terpilih
|
||||
</span>
|
||||
return (
|
||||
<tr key={comp} className="hover:bg-slate-50/60 transition-colors">
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center gap-3">
|
||||
{prof?.logoDataUrl ? (
|
||||
<img
|
||||
src={prof.logoDataUrl}
|
||||
alt={comp}
|
||||
className="h-10 w-10 rounded-lg object-contain bg-white p-1 border border-slate-200 shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-10 w-10 rounded-lg bg-slate-100 border border-slate-200 flex items-center justify-center text-slate-500 shrink-0">
|
||||
<Building2 className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-bold text-slate-900 text-sm">{comp}</span>
|
||||
{isCurrentlySelected && (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
PT Aktif
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[11px] text-slate-500 truncate max-w-[260px]">
|
||||
{prof?.address || "Alamat belum diisi — klik Edit untuk melengkapi"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-4 px-4 text-[11px] text-slate-600">
|
||||
<div>{prof?.phone || prof?.email ? [prof.phone, prof.email].filter(Boolean).join(" • ") : "-"}</div>
|
||||
{prof?.bankInfo && (
|
||||
<div className="text-[10.5px] font-mono text-slate-500 truncate max-w-[200px] mt-0.5">
|
||||
{prof.bankInfo}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-4 px-4 text-center font-semibold text-slate-700">
|
||||
{ptAccounts.length} Akun / Bank
|
||||
</td>
|
||||
<td className="py-4 px-4 text-center font-semibold text-slate-700">
|
||||
{ptPayrolls.length} Slip Gaji
|
||||
</td>
|
||||
<td className="py-4 px-4 text-right font-bold text-slate-900">
|
||||
{formatRupiah(ptTotalPaid)}
|
||||
</td>
|
||||
<td className="py-4 px-6 text-right">
|
||||
<div className="inline-flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSelectedCompanyFilter(comp);
|
||||
setPayrollCompany(comp);
|
||||
setAccCompany(comp);
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("erp_selected_pt", comp);
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("erp:company-sync", {
|
||||
detail: { selectedCompany: comp, companies },
|
||||
})
|
||||
);
|
||||
}
|
||||
}}
|
||||
className={`px-3 py-1.5 rounded-lg text-[11px] font-semibold border transition-colors ${
|
||||
isCurrentlySelected
|
||||
? "bg-emerald-600 text-white border-emerald-600"
|
||||
: "bg-slate-100 hover:bg-blue-50 text-slate-700 hover:text-blue-700 border-slate-200"
|
||||
}`}
|
||||
>
|
||||
{isCurrentlySelected ? "Sedang Dipilih" : "Pilih PT Ini"}
|
||||
</button>
|
||||
|
||||
{currentUser?.role === "ADMIN" ? (
|
||||
</td>
|
||||
<td className="py-4 px-4 text-center font-semibold text-slate-700 whitespace-nowrap">
|
||||
{ptAccounts.length} Akun • {ptPayrolls.length} Slip
|
||||
</td>
|
||||
<td className="py-4 px-4 text-right font-bold text-slate-900 whitespace-nowrap">
|
||||
{formatRupiah(ptTotalPaid)}
|
||||
</td>
|
||||
<td className="py-4 px-6 text-right">
|
||||
<div className="inline-flex items-center gap-1.5 flex-wrap justify-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeleteCompanyItem(comp)}
|
||||
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 font-semibold text-[11px] transition-colors"
|
||||
title="Hapus Entitas PT (Khusus Super Admin)"
|
||||
onClick={() => openCompanyProfileModal(comp)}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-blue-50 hover:bg-blue-100 text-blue-700 border border-blue-200 font-semibold text-[11px] transition-colors"
|
||||
title="Edit Nama PT, Upload Logo & Template Dokumen"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
<span>Hapus PT</span>
|
||||
<Pencil className="h-3 w-3" />
|
||||
<span>Edit & Logo</span>
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-[10px] text-slate-400 italic px-2">
|
||||
View & Add Only
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSelectedCompanyFilter(comp);
|
||||
setPayrollCompany(comp);
|
||||
setAccCompany(comp);
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("erp_selected_pt", comp);
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("erp:company-sync", {
|
||||
detail: { selectedCompany: comp, companies, companyProfiles },
|
||||
})
|
||||
);
|
||||
}
|
||||
}}
|
||||
className={`px-2.5 py-1.5 rounded-lg text-[11px] font-semibold border transition-colors ${
|
||||
isCurrentlySelected
|
||||
? "bg-emerald-600 text-white border-emerald-600"
|
||||
: "bg-slate-100 hover:bg-blue-50 text-slate-700 hover:text-blue-700 border-slate-200"
|
||||
}`}
|
||||
>
|
||||
{isCurrentlySelected ? "Aktif" : "Pilih"}
|
||||
</button>
|
||||
|
||||
{currentUser?.role === "ADMIN" && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeleteCompanyItem(comp)}
|
||||
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 font-semibold text-[11px] transition-colors"
|
||||
title="Hapus Entitas PT (Khusus Super Admin)"
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -2968,6 +3210,321 @@ export default function FinancePage() {
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
{/* MODAL TAMBAH / EDIT PERUSAHAAN (PT), UPLOAD LOGO & TEMPLATE DOKUMEN */}
|
||||
<Modal
|
||||
isOpen={isCompanyModalOpen}
|
||||
onClose={() => setIsCompanyModalOpen(false)}
|
||||
title={
|
||||
editingCompanyOriginalName
|
||||
? `Edit Perusahaan & Template Dokumen — ${editingCompanyOriginalName}`
|
||||
: "Tambah Perusahaan (PT), Logo & Template Dokumen"
|
||||
}
|
||||
maxWidth="max-w-3xl"
|
||||
>
|
||||
<form onSubmit={handleSaveCompanyProfile} className="space-y-5 text-xs">
|
||||
{compFormError && (
|
||||
<div className="p-3 rounded-lg bg-rose-50 text-rose-700 border border-rose-200 font-medium">
|
||||
{compFormError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Bagian 1: Identitas & Logo PT */}
|
||||
<div className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-3">
|
||||
<div className="font-bold text-slate-900 text-xs uppercase tracking-wider flex items-center gap-1.5">
|
||||
<Building2 className="h-3.5 w-3.5" />
|
||||
<span>1. Identitas & Logo Perusahaan</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 items-start">
|
||||
{/* Upload Logo */}
|
||||
<div className="sm:col-span-1 flex flex-col items-center justify-center p-3 rounded-lg bg-white border border-slate-200 gap-2">
|
||||
{compFormLogo ? (
|
||||
<img
|
||||
src={compFormLogo}
|
||||
alt="Preview Logo"
|
||||
className="h-20 max-w-[160px] object-contain rounded bg-white p-1 border border-slate-200"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-20 w-20 rounded-lg bg-slate-100 border border-dashed border-slate-300 flex flex-col items-center justify-center text-slate-500">
|
||||
<ImageIcon className="h-6 w-6 mb-1" />
|
||||
<span className="text-[10px]">Belum ada logo</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<label className="cursor-pointer inline-flex items-center gap-1 px-2.5 py-1.5 rounded-md bg-slate-900 text-white text-[11px] font-semibold hover:bg-slate-800 transition-colors">
|
||||
<Upload className="h-3 w-3" />
|
||||
<span>Upload Logo</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp,image/gif"
|
||||
onChange={handleLogoFileChange}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
{compFormLogo && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCompFormLogo("")}
|
||||
className="px-2 py-1.5 rounded-md bg-rose-50 text-rose-700 border border-rose-200 text-[11px] font-semibold hover:bg-rose-100"
|
||||
>
|
||||
Hapus
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[10px] text-slate-500 text-center">
|
||||
PNG / JPG / WEBP (otomatis tampil di Sidebar, Invoice & Surat Serah Terima)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Nama PT & Info Dasar */}
|
||||
<div className="sm:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Nama Perusahaan (PT) *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="Contoh: PT Maju Bersama Teknologi"
|
||||
value={compFormName}
|
||||
onChange={(e) => setCompFormName(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-semibold"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Tagline / Subjudul Sidebar
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Contoh: Trading & Distribution"
|
||||
value={compFormTagline}
|
||||
onChange={(e) => setCompFormTagline(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Telepon / WhatsApp
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="021-xxxxxxx / 0812-xxxx"
|
||||
value={compFormPhone}
|
||||
onChange={(e) => setCompFormPhone(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Email Resmi</label>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="finance@perusahaan.co.id"
|
||||
value={compFormEmail}
|
||||
onChange={(e) => setCompFormEmail(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">NPWP (Opsional)</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="00.000.000.0-000.000"
|
||||
value={compFormNpwp}
|
||||
onChange={(e) => setCompFormNpwp(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Alamat Perusahaan (Kop Dokumen)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Jl. Sudirman No. 123, Jakarta Selatan"
|
||||
value={compFormAddress}
|
||||
onChange={(e) => setCompFormAddress(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Informasi Rekening Pembayaran (Muncul di Invoice)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Bank BCA 123-456-7890 a/n PT ..."
|
||||
value={compFormBankInfo}
|
||||
onChange={(e) => setCompFormBankInfo(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bagian 2: Template Invoice */}
|
||||
<div className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-3">
|
||||
<div className="font-bold text-slate-900 text-xs uppercase tracking-wider flex items-center gap-1.5">
|
||||
<FileText className="h-3.5 w-3.5" />
|
||||
<span>2. Kustomisasi Default Invoice</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Judul Invoice</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormInvTitle}
|
||||
onChange={(e) => setCompFormInvTitle(e.target.value)}
|
||||
placeholder="INVOICE / FAKTUR PENJUALAN"
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Subjudul Invoice</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormInvSubtitle}
|
||||
onChange={(e) => setCompFormInvSubtitle(e.target.value)}
|
||||
placeholder="Faktur Tagihan Penjualan Resmi"
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Jabatan Penandatangan</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormInvSignerLabel}
|
||||
onChange={(e) => setCompFormInvSignerLabel(e.target.value)}
|
||||
placeholder="Finance / Direktur"
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Nama Penandatangan (Opsional)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormInvSignerName}
|
||||
onChange={(e) => setCompFormInvSignerName(e.target.value)}
|
||||
placeholder="Nama lengkap penandatangan"
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Catatan / Syarat Pembayaran (Footer Invoice)
|
||||
</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={compFormInvFooter}
|
||||
onChange={(e) => setCompFormInvFooter(e.target.value)}
|
||||
placeholder="Contoh: Mohon mencantumkan nomor Invoice pada berita transfer. Pembayaran jatuh tempo 14 hari."
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bagian 3: Template Surat Serah Terima Barang */}
|
||||
<div className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-3">
|
||||
<div className="font-bold text-slate-900 text-xs uppercase tracking-wider flex items-center gap-1.5">
|
||||
<Printer className="h-3.5 w-3.5" />
|
||||
<span>3. Kustomisasi Default Surat Serah Terima Barang (BAST / Surat Jalan)</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Judul Dokumen</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormDelTitle}
|
||||
onChange={(e) => setCompFormDelTitle(e.target.value)}
|
||||
placeholder="SURAT SERAH TERIMA BARANG"
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Subjudul Dokumen</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormDelSubtitle}
|
||||
onChange={(e) => setCompFormDelSubtitle(e.target.value)}
|
||||
placeholder="Berita Acara Serah Terima & Pengiriman Barang"
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Kalimat Pembuka Serah Terima
|
||||
</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={compFormDelIntro}
|
||||
onChange={(e) => setCompFormDelIntro(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Label Pihak Penyerah</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormDelSenderLabel}
|
||||
onChange={(e) => setCompFormDelSenderLabel(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Nama Penyerah Default (Opsional)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormDelSenderName}
|
||||
onChange={(e) => setCompFormDelSenderName(e.target.value)}
|
||||
placeholder="Bagian Gudang / Logistik"
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Label Pihak Penerima</label>
|
||||
<input
|
||||
type="text"
|
||||
value={compFormDelReceiverLabel}
|
||||
onChange={(e) => setCompFormDelReceiverLabel(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Catatan / Ketentuan Serah Terima
|
||||
</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={compFormDelFooter}
|
||||
onChange={(e) => setCompFormDelFooter(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 flex items-center justify-end gap-2 border-t border-slate-200">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsCompanyModalOpen(false)}
|
||||
className="px-4 py-2 border border-slate-300 rounded-lg text-slate-700 hover:bg-slate-100 font-semibold"
|
||||
>
|
||||
Batal
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={compFormSaving}
|
||||
className="px-5 py-2 bg-slate-900 hover:bg-slate-800 text-white rounded-lg font-semibold disabled:opacity-50"
|
||||
>
|
||||
{compFormSaving ? "Menyimpan..." : "Simpan Perusahaan & Template"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -34,7 +34,7 @@ export default function InventoryPage() {
|
||||
const [warehouses, setWarehouses] = useState<any[]>([]);
|
||||
const [categories, setCategories] = useState<any[]>([]);
|
||||
const [movements, setMovements] = useState<any[]>([]);
|
||||
const [companies, setCompanies] = useState<string[]>(["PT EnterpriseCore Utama"]);
|
||||
const [companies, setCompanies] = useState<string[]>([]);
|
||||
const [selectedCompanyFilter, setSelectedCompanyFilter] = useState<string>("ALL");
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
@@ -212,7 +212,7 @@ export default function InventoryPage() {
|
||||
setNewProduct((prev) => ({ ...prev, warehouseId: mainWhId }));
|
||||
setAdjustData((prev) => ({ ...prev, warehouseId: mainWhId }));
|
||||
}
|
||||
if (json.companies && json.companies.length > 0) {
|
||||
if (Array.isArray(json.companies)) {
|
||||
setCompanies(json.companies);
|
||||
}
|
||||
}
|
||||
@@ -650,7 +650,7 @@ export default function InventoryPage() {
|
||||
const companyName =
|
||||
selectedCompanyFilter !== "ALL"
|
||||
? selectedCompanyFilter
|
||||
: companies[0] || "PT EnterpriseCore Utama";
|
||||
: companies[0] || "";
|
||||
|
||||
const isEdit = Boolean(editingDevice);
|
||||
const numericReturnShipping =
|
||||
|
||||
@@ -43,10 +43,10 @@ export default function PurchasesPage() {
|
||||
const [warehouses, setWarehouses] = useState<any[]>([]);
|
||||
const [customers, setCustomers] = useState<any[]>([]);
|
||||
const [batches, setBatches] = useState<any[]>([]);
|
||||
const [companies, setCompanies] = useState<string[]>(["PT EnterpriseCore Utama"]);
|
||||
const [companies, setCompanies] = useState<string[]>([]);
|
||||
const [selectedCompanyFilter, setSelectedCompanyFilter] = useState<string>("ALL");
|
||||
const [poCompanyName, setPoCompanyName] = useState<string>("PT EnterpriseCore Utama");
|
||||
const [reqCompanyName, setReqCompanyName] = useState<string>("PT EnterpriseCore Utama");
|
||||
const [poCompanyName, setPoCompanyName] = useState<string>("");
|
||||
const [reqCompanyName, setReqCompanyName] = useState<string>("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Tab: "po" | "requisitions" | "batches"
|
||||
@@ -167,6 +167,7 @@ export default function PurchasesPage() {
|
||||
const [poTaxRate, setPoTaxRate] = useState<number | string>(11);
|
||||
const [supplierId, setSupplierId] = useState("");
|
||||
const [warehouseId, setWarehouseId] = useState("");
|
||||
const [companyProfiles, setCompanyProfiles] = useState<Record<string, any>>({});
|
||||
const [autoReceive, setAutoReceive] = useState(false);
|
||||
const [notes, setNotes] = useState("");
|
||||
const [items, setItems] = useState<
|
||||
@@ -182,6 +183,16 @@ export default function PurchasesPage() {
|
||||
if (meRes.ok) {
|
||||
const meJson = await meRes.json();
|
||||
setCurrentUser(meJson.user);
|
||||
if (Array.isArray(meJson.companies)) {
|
||||
setCompanies(meJson.companies);
|
||||
if (meJson.companies.length > 0) {
|
||||
setPoCompanyName((prev) => prev || meJson.companies[0]);
|
||||
setReqCompanyName((prev) => prev || meJson.companies[0]);
|
||||
}
|
||||
}
|
||||
if (meJson.companyProfiles && typeof meJson.companyProfiles === "object") {
|
||||
setCompanyProfiles(meJson.companyProfiles);
|
||||
}
|
||||
}
|
||||
|
||||
if (res.ok) {
|
||||
@@ -874,6 +885,12 @@ export default function PurchasesPage() {
|
||||
|
||||
const ptCustomer = po.requisition?.customerCompany || po.requisition?.customer?.company || "";
|
||||
|
||||
const ptNameRaw = po.companyName || companies[0] || "Perusahaan";
|
||||
const ptProf = companyProfiles[ptNameRaw];
|
||||
const ptLogoHtml = ptProf?.logoDataUrl
|
||||
? `<img src="${ptProf.logoDataUrl}" alt="Logo" style="max-height:52px;max-width:150px;object-fit:contain;margin-right:12px;" />`
|
||||
: "";
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
@@ -882,7 +899,7 @@ export default function PurchasesPage() {
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; color: #0f172a; padding: 32px; max-width: 740px; margin: 0 auto; }
|
||||
.header { display: flex; justify-content: space-between; border-bottom: 2px solid #0f172a; padding-bottom: 16px; margin-bottom: 20px; }
|
||||
.company { font-size: 20px; font-weight: bold; }
|
||||
.company { font-size: 20px; font-weight: bold; text-transform: uppercase; }
|
||||
.sub { font-size: 12px; color: #475569; margin-top: 4px; }
|
||||
.badge { padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: bold; display: inline-block; background: #ede9fe; color: #5b21b6; }
|
||||
.meta { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; background: #f8fafc; padding: 14px; border-radius: 8px; border: 1px solid #e2e8f0; margin-bottom: 20px; font-size: 13px; }
|
||||
@@ -897,9 +914,13 @@ export default function PurchasesPage() {
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<div>
|
||||
<div class="company">ENTERPRISECORE ERP</div>
|
||||
<div class="sub">Dokumen Resmi Pesanan Pembelian Barang (Purchase Order)</div>
|
||||
<div style="display:flex;align-items:center;">
|
||||
${ptLogoHtml}
|
||||
<div>
|
||||
<div class="company">${escapeHtml(ptNameRaw)}</div>
|
||||
${ptProf?.address ? `<div class="sub">${escapeHtml(ptProf.address)}</div>` : ""}
|
||||
<div class="sub">Dokumen Resmi Pesanan Pembelian Barang (Purchase Order)</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="text-align:right;">
|
||||
<div class="badge">STATUS: ${safeStatus}</div>
|
||||
|
||||
+646
-125
@@ -9,6 +9,7 @@ import { Pagination } from "@/components/Pagination";
|
||||
import { CurrencyInput } from "@/components/CurrencyInput";
|
||||
import { SerialNumberInput } from "@/components/SerialNumberInput";
|
||||
import { formatRupiah, formatDateTime, exportToCSV, escapeHtml } from "@/lib/utils";
|
||||
import type { CompanyProfile } from "@/lib/companies";
|
||||
import {
|
||||
ShoppingCart,
|
||||
Plus,
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
AlertCircle,
|
||||
RotateCcw,
|
||||
CreditCard,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
|
||||
export default function SalesPage() {
|
||||
@@ -41,11 +43,36 @@ export default function SalesPage() {
|
||||
const [activeBatches, setActiveBatches] = useState<any[]>([]);
|
||||
const [suppliers, setSuppliers] = useState<any[]>([]);
|
||||
const [selectedOrderBatchModal, setSelectedOrderBatchModal] = useState<any>(null);
|
||||
const [companies, setCompanies] = useState<string[]>(["PT EnterpriseCore Utama"]);
|
||||
const [companies, setCompanies] = useState<string[]>([]);
|
||||
const [companyProfiles, setCompanyProfiles] = useState<Record<string, CompanyProfile>>({});
|
||||
const [selectedCompanyFilter, setSelectedCompanyFilter] = useState<string>("ALL");
|
||||
const [soCompanyName, setSoCompanyName] = useState<string>("PT EnterpriseCore Utama");
|
||||
const [soCompanyName, setSoCompanyName] = useState<string>("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Modal Edit & Cetak Custom Invoice / Surat Serah Terima Barang (BAST)
|
||||
const [printModalOrder, setPrintModalOrder] = useState<any>(null);
|
||||
const [printModalType, setPrintModalType] = useState<"INVOICE" | "SURAT_JALAN">("INVOICE");
|
||||
const [docShowLogo, setDocShowLogo] = useState(true);
|
||||
const [docLogoDataUrl, setDocLogoDataUrl] = useState("");
|
||||
const [docCompanyName, setDocCompanyName] = useState("");
|
||||
const [docCompanyAddress, setDocCompanyAddress] = useState("");
|
||||
const [docCompanyContact, setDocCompanyContact] = useState("");
|
||||
const [docTitle, setDocTitle] = useState("");
|
||||
const [docSubtitle, setDocSubtitle] = useState("");
|
||||
const [docNumber, setDocNumber] = useState("");
|
||||
const [docDateText, setDocDateText] = useState("");
|
||||
const [docCustomerName, setDocCustomerName] = useState("");
|
||||
const [docCustomerAddress, setDocCustomerAddress] = useState("");
|
||||
const [docIntroText, setDocIntroText] = useState("");
|
||||
const [docBankInfo, setDocBankInfo] = useState("");
|
||||
const [docFooterNotes, setDocFooterNotes] = useState("");
|
||||
const [docSenderLabel, setDocSenderLabel] = useState("");
|
||||
const [docSenderName, setDocSenderName] = useState("");
|
||||
const [docReceiverLabel, setDocReceiverLabel] = useState("");
|
||||
const [docReceiverName, setDocReceiverName] = useState("");
|
||||
const [docSaveAsDefault, setDocSaveAsDefault] = useState(false);
|
||||
const [docSavingDefault, setDocSavingDefault] = useState(false);
|
||||
|
||||
// Modal create order
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
@@ -164,6 +191,13 @@ export default function SalesPage() {
|
||||
if (meRes.ok) {
|
||||
const meJson = await meRes.json();
|
||||
setCurrentUser(meJson.user);
|
||||
if (Array.isArray(meJson.companies)) {
|
||||
setCompanies(meJson.companies);
|
||||
setSoCompanyName((prev) => prev || meJson.companies[0] || "");
|
||||
}
|
||||
if (meJson.companyProfiles && typeof meJson.companyProfiles === "object") {
|
||||
setCompanyProfiles(meJson.companyProfiles);
|
||||
}
|
||||
}
|
||||
|
||||
if (res.ok) {
|
||||
@@ -177,8 +211,9 @@ export default function SalesPage() {
|
||||
setCustomerPrices(json.customerPrices || []);
|
||||
setActiveBatches(json.activeBatches || []);
|
||||
setSuppliers(json.suppliers || []);
|
||||
if (json.companies && json.companies.length > 0) {
|
||||
if (Array.isArray(json.companies) && json.companies.length > 0) {
|
||||
setCompanies(json.companies);
|
||||
setSoCompanyName((prev) => prev || json.companies[0] || "");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,16 +243,24 @@ export default function SalesPage() {
|
||||
loadData();
|
||||
|
||||
const handleCompanyChange = (e: any) => {
|
||||
const comp = e.detail?.company || "ALL";
|
||||
const comp = e.detail?.selectedCompany || e.detail?.company || "ALL";
|
||||
setSelectedCompanyFilter(comp);
|
||||
if (comp !== "ALL") {
|
||||
setSoCompanyName(comp);
|
||||
}
|
||||
if (Array.isArray(e.detail?.companies)) {
|
||||
setCompanies(e.detail.companies);
|
||||
}
|
||||
if (e.detail?.companyProfiles) {
|
||||
setCompanyProfiles(e.detail.companyProfiles);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("erp:company-changed", handleCompanyChange);
|
||||
window.addEventListener("erp:company-sync", handleCompanyChange);
|
||||
return () => {
|
||||
window.removeEventListener("erp:company-changed", handleCompanyChange);
|
||||
window.removeEventListener("erp:company-sync", handleCompanyChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -1157,42 +1200,296 @@ export default function SalesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handlePrintDocument = (order: any, docType: "INVOICE" | "SURAT_JALAN") => {
|
||||
const printWindow = window.open("", "_blank", "width=820,height=720");
|
||||
const openDocPrintModal = (order: any, docType: "INVOICE" | "SURAT_JALAN") => {
|
||||
const isSJ = docType === "SURAT_JALAN";
|
||||
const ptName = order.companyName || companies[0] || "";
|
||||
const prof = companyProfiles[ptName];
|
||||
|
||||
setPrintModalOrder(order);
|
||||
setPrintModalType(docType);
|
||||
setDocLogoDataUrl(prof?.logoDataUrl || "");
|
||||
setDocShowLogo(Boolean(prof?.logoDataUrl));
|
||||
setDocCompanyName(ptName || "Perusahaan");
|
||||
setDocCompanyAddress(prof?.address || "");
|
||||
setDocCompanyContact([prof?.phone, prof?.email, prof?.npwp ? `NPWP: ${prof.npwp}` : ""].filter(Boolean).join(" • "));
|
||||
setDocTitle(
|
||||
isSJ
|
||||
? prof?.deliveryTitle || "SURAT SERAH TERIMA BARANG"
|
||||
: prof?.invoiceTitle || "INVOICE"
|
||||
);
|
||||
setDocSubtitle(
|
||||
isSJ
|
||||
? prof?.deliverySubtitle || "Berita Acara Serah Terima & Pengiriman Barang"
|
||||
: prof?.invoiceSubtitle || "Faktur Tagihan Penjualan Resmi"
|
||||
);
|
||||
setDocNumber(isSJ ? order.orderNumber : order.invoiceNumber || order.orderNumber);
|
||||
setDocDateText(formatDateTime(order.orderDate || order.createdAt));
|
||||
setDocCustomerName(order.customer?.company || order.customer?.name || "-");
|
||||
setDocCustomerAddress(
|
||||
[order.customer?.phone, order.customer?.address].filter(Boolean).join(" — ")
|
||||
);
|
||||
setDocIntroText(
|
||||
isSJ
|
||||
? prof?.deliveryIntroText ||
|
||||
"Dengan ini kami menyerahkan barang/perangkat berikut dalam kondisi baik dan lengkap kepada pihak penerima:"
|
||||
: ""
|
||||
);
|
||||
setDocBankInfo(!isSJ ? prof?.bankInfo || "" : "");
|
||||
setDocFooterNotes(
|
||||
isSJ
|
||||
? prof?.deliveryFooterNotes ||
|
||||
"Barang yang telah diterima dan ditandatangani dianggap telah diperiksa sesuai pesanan."
|
||||
: prof?.invoiceFooterNotes || order.notes || ""
|
||||
);
|
||||
setDocSenderLabel(
|
||||
isSJ
|
||||
? prof?.deliverySenderLabel || "Yang Menyerahkan,"
|
||||
: "Hormat Kami,"
|
||||
);
|
||||
setDocSenderName(
|
||||
isSJ
|
||||
? prof?.deliverySenderName || "Bagian Gudang / Logistik"
|
||||
: prof?.invoiceSignerName || prof?.invoiceSignerLabel || "Bagian Penjualan / Finance"
|
||||
);
|
||||
setDocReceiverLabel(
|
||||
isSJ ? prof?.deliveryReceiverLabel || "Yang Menerima," : "Diterima Oleh,"
|
||||
);
|
||||
setDocReceiverName(order.customer?.company || order.customer?.name || "-");
|
||||
setDocSaveAsDefault(false);
|
||||
};
|
||||
|
||||
const handleDocLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
if (!/^image\/(png|jpeg|jpg|webp|gif)$/.test(file.type)) {
|
||||
alert("Format logo harus PNG, JPG, atau WEBP.");
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const img = new window.Image();
|
||||
img.onload = () => {
|
||||
const maxDim = 360;
|
||||
let w = img.width;
|
||||
let h = img.height;
|
||||
if (w > maxDim || h > maxDim) {
|
||||
const r = Math.min(maxDim / w, maxDim / h);
|
||||
w = Math.round(w * r);
|
||||
h = Math.round(h * r);
|
||||
}
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (ctx) {
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
setDocLogoDataUrl(canvas.toDataURL("image/png"));
|
||||
setDocShowLogo(true);
|
||||
}
|
||||
};
|
||||
img.src = String(reader.result || "");
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
const handleExecuteCustomPrint = async () => {
|
||||
if (!printModalOrder) return;
|
||||
const order = printModalOrder;
|
||||
const isSJ = printModalType === "SURAT_JALAN";
|
||||
|
||||
if (docSaveAsDefault && docCompanyName.trim()) {
|
||||
setDocSavingDefault(true);
|
||||
try {
|
||||
const profPatch: Partial<CompanyProfile> = {
|
||||
name: docCompanyName.trim(),
|
||||
logoDataUrl: docShowLogo ? docLogoDataUrl : "",
|
||||
address: docCompanyAddress.trim(),
|
||||
...(isSJ
|
||||
? {
|
||||
deliveryTitle: docTitle.trim(),
|
||||
deliverySubtitle: docSubtitle.trim(),
|
||||
deliveryIntroText: docIntroText.trim(),
|
||||
deliveryFooterNotes: docFooterNotes.trim(),
|
||||
deliverySenderLabel: docSenderLabel.trim(),
|
||||
deliverySenderName: docSenderName.trim(),
|
||||
deliveryReceiverLabel: docReceiverLabel.trim(),
|
||||
}
|
||||
: {
|
||||
bankInfo: docBankInfo.trim(),
|
||||
invoiceTitle: docTitle.trim(),
|
||||
invoiceSubtitle: docSubtitle.trim(),
|
||||
invoiceFooterNotes: docFooterNotes.trim(),
|
||||
invoiceSignerName: docSenderName.trim(),
|
||||
}),
|
||||
};
|
||||
const res = await fetch("/api/auth/me", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "UPDATE_COMPANY_PROFILE",
|
||||
companyName: docCompanyName.trim(),
|
||||
profile: profPatch,
|
||||
}),
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data.companyProfiles) {
|
||||
setCompanyProfiles(data.companyProfiles);
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("erp:company-sync", {
|
||||
detail: { companies: data.companies, companyProfiles: data.companyProfiles },
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Save template default error:", err);
|
||||
} finally {
|
||||
setDocSavingDefault(false);
|
||||
}
|
||||
}
|
||||
|
||||
handlePrintDocument(order, printModalType, {
|
||||
showLogo: docShowLogo,
|
||||
logoDataUrl: docLogoDataUrl,
|
||||
companyName: docCompanyName,
|
||||
companyAddress: docCompanyAddress,
|
||||
companyContact: docCompanyContact,
|
||||
docTitle,
|
||||
docSubtitle,
|
||||
docNumber,
|
||||
docDateText,
|
||||
customerName: docCustomerName,
|
||||
customerAddress: docCustomerAddress,
|
||||
introText: docIntroText,
|
||||
bankInfo: docBankInfo,
|
||||
footerNotes: docFooterNotes,
|
||||
senderLabel: docSenderLabel,
|
||||
senderName: docSenderName,
|
||||
receiverLabel: docReceiverLabel,
|
||||
receiverName: docReceiverName,
|
||||
});
|
||||
};
|
||||
|
||||
const handlePrintDocument = (
|
||||
order: any,
|
||||
docType: "INVOICE" | "SURAT_JALAN",
|
||||
custom?: {
|
||||
showLogo?: boolean;
|
||||
logoDataUrl?: string;
|
||||
companyName?: string;
|
||||
companyAddress?: string;
|
||||
companyContact?: string;
|
||||
docTitle?: string;
|
||||
docSubtitle?: string;
|
||||
docNumber?: string;
|
||||
docDateText?: string;
|
||||
customerName?: string;
|
||||
customerAddress?: string;
|
||||
introText?: string;
|
||||
bankInfo?: string;
|
||||
footerNotes?: string;
|
||||
senderLabel?: string;
|
||||
senderName?: string;
|
||||
receiverLabel?: string;
|
||||
receiverName?: string;
|
||||
}
|
||||
) => {
|
||||
const printWindow = window.open("", "_blank", "width=860,height=760");
|
||||
if (!printWindow) return;
|
||||
|
||||
const isSJ = docType === "SURAT_JALAN";
|
||||
const ptKey = custom?.companyName || order.companyName || companies[0] || "";
|
||||
const prof = companyProfiles[ptKey];
|
||||
|
||||
const finalLogo =
|
||||
custom !== undefined
|
||||
? custom.showLogo && custom.logoDataUrl
|
||||
? custom.logoDataUrl
|
||||
: ""
|
||||
: prof?.logoDataUrl || "";
|
||||
|
||||
const safeCompany = escapeHtml(ptKey || "Perusahaan");
|
||||
const safeCompAddr = escapeHtml(custom?.companyAddress ?? prof?.address ?? "");
|
||||
const safeCompContact = escapeHtml(
|
||||
custom?.companyContact ??
|
||||
[prof?.phone, prof?.email, prof?.npwp ? `NPWP: ${prof.npwp}` : ""].filter(Boolean).join(" • ")
|
||||
);
|
||||
const safeDocTitle = escapeHtml(
|
||||
custom?.docTitle ||
|
||||
(isSJ
|
||||
? prof?.deliveryTitle || "SURAT SERAH TERIMA BARANG"
|
||||
: prof?.invoiceTitle || "INVOICE")
|
||||
);
|
||||
const safeDocSub = escapeHtml(
|
||||
custom?.docSubtitle ??
|
||||
(isSJ
|
||||
? prof?.deliverySubtitle || "Berita Acara Serah Terima & Pengiriman Barang"
|
||||
: prof?.invoiceSubtitle || "Faktur Tagihan Penjualan Resmi")
|
||||
);
|
||||
const safeOrderNo = escapeHtml(order.orderNumber);
|
||||
const safeInvNo = escapeHtml(order.invoiceNumber || order.orderNumber);
|
||||
const safeDocNo = escapeHtml(
|
||||
custom?.docNumber || (isSJ ? order.orderNumber : order.invoiceNumber || order.orderNumber)
|
||||
);
|
||||
const safeDocDate = escapeHtml(
|
||||
custom?.docDateText || formatDateTime(order.orderDate || order.createdAt)
|
||||
);
|
||||
const safeCustPo = escapeHtml(order.customerPoNumber || "");
|
||||
const safeCustName = escapeHtml(order.customer?.name || "-");
|
||||
const safeCustPhone = escapeHtml(order.customer?.phone || "");
|
||||
const safeCustAddress = escapeHtml(order.customer?.address || "");
|
||||
const safeNotes = escapeHtml(order.notes || "");
|
||||
const safeCustName = escapeHtml(
|
||||
custom?.customerName || order.customer?.company || order.customer?.name || "-"
|
||||
);
|
||||
const safeCustAddr = escapeHtml(
|
||||
custom?.customerAddress ??
|
||||
[order.customer?.phone, order.customer?.address].filter(Boolean).join(" — ")
|
||||
);
|
||||
const safeIntro = escapeHtml(
|
||||
custom?.introText ??
|
||||
(isSJ
|
||||
? prof?.deliveryIntroText ||
|
||||
"Dengan ini kami menyerahkan barang/perangkat berikut dalam kondisi baik dan lengkap kepada pihak penerima:"
|
||||
: "")
|
||||
);
|
||||
const safeBankInfo = escapeHtml(custom?.bankInfo ?? (!isSJ ? prof?.bankInfo || "" : ""));
|
||||
const safeFooterNotes = escapeHtml(
|
||||
custom?.footerNotes ??
|
||||
(isSJ
|
||||
? prof?.deliveryFooterNotes ||
|
||||
"Barang yang telah diterima dan ditandatangani dianggap telah diperiksa sesuai pesanan."
|
||||
: prof?.invoiceFooterNotes || order.notes || "")
|
||||
);
|
||||
const safeSenderLabel = escapeHtml(
|
||||
custom?.senderLabel || (isSJ ? prof?.deliverySenderLabel || "Yang Menyerahkan," : "Hormat Kami,")
|
||||
);
|
||||
const safeSenderName = escapeHtml(
|
||||
custom?.senderName ||
|
||||
(isSJ
|
||||
? prof?.deliverySenderName || "Bagian Gudang / Logistik"
|
||||
: prof?.invoiceSignerName || prof?.invoiceSignerLabel || "Bagian Penjualan / Finance")
|
||||
);
|
||||
const safeReceiverLabel = escapeHtml(
|
||||
custom?.receiverLabel || (isSJ ? prof?.deliveryReceiverLabel || "Yang Menerima," : "Diterima Oleh,")
|
||||
);
|
||||
const safeReceiverName = escapeHtml(custom?.receiverName || safeCustName);
|
||||
const safeStatus = escapeHtml(order.status || "");
|
||||
const safePaymentStatus = escapeHtml(order.paymentStatus || "");
|
||||
const isManagedService = order.saleType === "MANAGED_SERVICE";
|
||||
const saleTypeLabel = isManagedService ? "JUAL MANAGE SERVICE" : "JUAL PUTUS";
|
||||
|
||||
const title = isSJ
|
||||
? `SURAT JALAN (DELIVERY ORDER) — ${safeOrderNo}`
|
||||
: `FAKTUR PENJUALAN (INVOICE) — ${safeInvNo}`;
|
||||
const title = `${safeDocTitle} — ${safeDocNo}`;
|
||||
|
||||
const rowsHtml = (order.items || [])
|
||||
.map(
|
||||
(it: any, idx: number) => `
|
||||
<tr>
|
||||
<td>${idx + 1}</td>
|
||||
<td style="text-align:center;">${idx + 1}</td>
|
||||
<td>
|
||||
<strong>${escapeHtml(it.product?.name || "-")}</strong><br/>
|
||||
<span style="font-size:11px;color:#64748b;">SKU: ${escapeHtml(it.product?.sku || "-")}</span>
|
||||
${it.serialNumbers ? `<br/><span style="font-size:10.5px;color:#b45309;background:#fef3c7;border:1px solid #fde68a;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;font-family:monospace;">🔢 SN Device: ${escapeHtml(it.serialNumbers)}</span>` : ""}
|
||||
${it.damagedSerialNumbers ? `<br/><span style="font-size:10.5px;color:#b91c1c;background:#fee2e2;border:1px solid #fca5a5;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;font-family:monospace;">⚠️ SN Rusak: ${escapeHtml(it.damagedSerialNumbers)}</span>` : ""}
|
||||
${it.replacementSerialNumbers ? `<br/><span style="font-size:10.5px;color:#047857;background:#ecfdf5;border:1px solid #a7f3d0;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;font-family:monospace;">🔄 SN Baru Pengganti: ${escapeHtml(it.replacementSerialNumbers)}</span>` : ""}
|
||||
${it.serviceFee > 0 ? `<br/><span style="font-size:10.5px;color:#4338ca;background:#eef2ff;border:1px solid #c7d2fe;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;">🛠️ Biaya Jasa Service: ${formatRupiah(it.serviceFee)}</span>` : ""}
|
||||
${it.batchAllocationNotes ? `<br/><span style="font-size:10.5px;color:#0284c7;background:#f0f9ff;border:1px solid #bae6fd;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:3px;">📦 Sumber Batch PO: ${escapeHtml(it.batchAllocationNotes)}</span>` : ""}
|
||||
${it.warrantyExpiry ? `<br/><span style="font-size:10.5px;color:#0369a1;background:#e0f2fe;border:1px solid #bae6fd;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;">🛡️ Garansi: s/d ${formatDateTime(it.warrantyExpiry)}</span>` : ""}
|
||||
${it.serviceStatus && it.serviceStatus !== "NORMAL" ? `<br/><span style="font-size:10.5px;color:#92400e;background:#fef3c7;border:1px solid #fde68a;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;">🔧 Purna Jual: ${it.serviceStatus === "REPLACED" ? `Unit Diganti Baru (${it.replacedQty} unit)` : it.serviceStatus}</span>` : ""}
|
||||
<span style="font-size:11px;color:#475569;">SKU: ${escapeHtml(it.product?.sku || "-")}</span>
|
||||
${it.serialNumbers ? `<br/><span style="font-size:10.5px;color:#92400e;background:#fef3c7;border:1px solid #fde68a;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;font-family:monospace;">SN: ${escapeHtml(it.serialNumbers)}</span>` : ""}
|
||||
${it.damagedSerialNumbers ? `<br/><span style="font-size:10.5px;color:#b91c1c;background:#fee2e2;border:1px solid #fca5a5;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;font-family:monospace;">SN Rusak: ${escapeHtml(it.damagedSerialNumbers)}</span>` : ""}
|
||||
${it.replacementSerialNumbers ? `<br/><span style="font-size:10.5px;color:#047857;background:#ecfdf5;border:1px solid #a7f3d0;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;font-family:monospace;">SN Pengganti: ${escapeHtml(it.replacementSerialNumbers)}</span>` : ""}
|
||||
${it.serviceFee > 0 ? `<br/><span style="font-size:10.5px;color:#3730a3;background:#eef2ff;border:1px solid #c7d2fe;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;">Biaya Service: ${formatRupiah(it.serviceFee)}</span>` : ""}
|
||||
${it.warrantyExpiry ? `<br/><span style="font-size:10.5px;color:#0369a1;background:#e0f2fe;border:1px solid #bae6fd;padding:1px 6px;border-radius:4px;display:inline-block;margin-top:2px;">Garansi s/d ${formatDateTime(it.warrantyExpiry)}</span>` : ""}
|
||||
</td>
|
||||
<td style="text-align:center;"><strong>${Number(it.quantity) || 0} ${escapeHtml(
|
||||
it.product?.unit || "Unit"
|
||||
@@ -1211,81 +1508,76 @@ export default function SalesPage() {
|
||||
)
|
||||
.join("");
|
||||
|
||||
const logoHtml = finalLogo
|
||||
? `<img src="${finalLogo}" alt="Logo" style="max-height:58px;max-width:160px;object-fit:contain;margin-right:14px;" />`
|
||||
: "";
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>${title}</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; color: #0f172a; padding: 32px; max-width: 740px; margin: 0 auto; }
|
||||
.header { display: flex; justify-content: space-between; border-bottom: 2px solid #0f172a; padding-bottom: 16px; margin-bottom: 20px; }
|
||||
.company { font-size: 20px; font-weight: bold; }
|
||||
.sub { font-size: 12px; color: #475569; margin-top: 4px; }
|
||||
.badge { padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: bold; display: inline-block; background: #e0f2fe; color: #0369a1; }
|
||||
.meta { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; background: #f8fafc; padding: 14px; border-radius: 8px; border: 1px solid #e2e8f0; margin-bottom: 20px; font-size: 13px; }
|
||||
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; font-size: 13px; }
|
||||
th { background: #f1f5f9; text-align: left; padding: 10px 12px; border-bottom: 1px solid #cbd5e1; }
|
||||
td { padding: 10px 12px; border-bottom: 1px solid #e2e8f0; }
|
||||
.total-box { background: #0f172a; color: white; padding: 14px 20px; border-radius: 8px; display: flex; justify-content: space-between; font-size: 16px; font-weight: bold; margin-bottom: 24px; }
|
||||
.signatures { display: flex; justify-content: space-between; margin-top: 40px; font-size: 13px; text-align: center; }
|
||||
.sig-line { margin-top: 60px; border-top: 1px solid #64748b; padding-top: 6px; width: 200px; }
|
||||
body { font-family: Arial, sans-serif; color: #0f172a; padding: 30px; max-width: 760px; margin: 0 auto; }
|
||||
.header { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; border-bottom: 2px solid #0f172a; padding-bottom: 16px; margin-bottom: 18px; }
|
||||
.brand { display: flex; align-items: center; }
|
||||
.company { font-size: 18px; font-weight: bold; text-transform: uppercase; letter-spacing: 0.3px; }
|
||||
.sub { font-size: 11.5px; color: #334155; margin-top: 3px; line-height: 1.4; }
|
||||
.doc-title { font-size: 17px; font-weight: 800; letter-spacing: 0.5px; color: #0f172a; text-transform: uppercase; }
|
||||
.badge { padding: 3px 9px; border-radius: 5px; font-size: 10.5px; font-weight: bold; display: inline-block; background: #f1f5f9; color: #0f172a; border: 1px solid #cbd5e1; margin-top: 6px; }
|
||||
.meta { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; background: #f8fafc; padding: 13px 15px; border-radius: 8px; border: 1px solid #cbd5e1; margin-bottom: 18px; font-size: 12.5px; line-height: 1.5; }
|
||||
.intro { font-size: 12.5px; color: #1e293b; margin-bottom: 14px; line-height: 1.55; }
|
||||
table { width: 100%; border-collapse: collapse; margin-bottom: 18px; font-size: 12.5px; }
|
||||
th { background: #f1f5f9; text-align: left; padding: 9px 11px; border-bottom: 1.5px solid #94a3b8; }
|
||||
td { padding: 9px 11px; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
|
||||
.total-box { background: #0f172a; color: white; padding: 13px 18px; border-radius: 8px; display: flex; justify-content: space-between; font-size: 15px; font-weight: bold; margin-bottom: 16px; }
|
||||
.info-box { padding: 11px 14px; background: #f8fafc; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 12px; margin-bottom: 14px; line-height: 1.55; }
|
||||
.signatures { display: flex; justify-content: space-between; margin-top: 34px; font-size: 12.5px; text-align: center; }
|
||||
.sig-line { margin-top: 56px; border-top: 1px solid #475569; padding-top: 6px; width: 210px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<div>
|
||||
<div class="company">${escapeHtml(order.companyName || "PT EnterpriseCore Utama").toUpperCase()}</div>
|
||||
<div class="sub">${
|
||||
isSJ
|
||||
? "Dokumen Resmi Surat Jalan Pengiriman Barang Gudang"
|
||||
: "Faktur Tagihan Penjualan Resmi (Commercial Invoice)"
|
||||
}</div>
|
||||
<div class="brand">
|
||||
${logoHtml}
|
||||
<div>
|
||||
<div class="company">${safeCompany}</div>
|
||||
${safeCompAddr ? `<div class="sub">${safeCompAddr}</div>` : ""}
|
||||
${safeCompContact ? `<div class="sub">${safeCompContact}</div>` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<div style="text-align:right;">
|
||||
<div class="badge">${
|
||||
isSJ ? `STATUS: ${safeStatus}` : `PEMBAYARAN: ${safePaymentStatus}`
|
||||
}</div>
|
||||
<div class="sub" style="font-family:monospace;margin-top:6px;">No. Dokumen: ${isSJ ? safeOrderNo : safeInvNo}</div>
|
||||
${!isSJ && safeInvNo !== safeOrderNo ? `<div class="sub" style="font-family:monospace;font-size:11px;color:#64748b;">Ref SO: ${safeOrderNo}</div>` : ""}
|
||||
<div style="text-align:right;min-width:210px;">
|
||||
<div class="doc-title">${safeDocTitle}</div>
|
||||
${safeDocSub ? `<div class="sub">${safeDocSub}</div>` : ""}
|
||||
<div class="badge">${isSJ ? `STATUS: ${safeStatus}` : `PEMBAYARAN: ${safePaymentStatus}`}</div>
|
||||
<div class="sub" style="font-family:monospace;margin-top:5px;">No: <strong>${safeDocNo}</strong></div>
|
||||
${!isSJ && safeDocNo !== safeOrderNo ? `<div class="sub" style="font-family:monospace;font-size:10.5px;">Ref SO: ${safeOrderNo}</div>` : ""}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="meta">
|
||||
<div>
|
||||
<div><strong>Kepada Pelanggan:</strong></div>
|
||||
<div style="font-size:15px;font-weight:bold;margin-top:2px;">${safeCustName}</div>
|
||||
<div style="color:#475569;">${safeCustPhone} ${
|
||||
safeCustAddress ? `— ${safeCustAddress}` : ""
|
||||
}</div>
|
||||
<div style="font-size:11px;text-transform:uppercase;color:#475569;font-weight:bold;">Kepada / Penerima:</div>
|
||||
<div style="font-size:14px;font-weight:bold;margin-top:2px;">${safeCustName}</div>
|
||||
${safeCustAddr ? `<div style="color:#334155;">${safeCustAddr}</div>` : ""}
|
||||
</div>
|
||||
<div style="text-align:right;">
|
||||
<div><strong>Tanggal Dokumen:</strong> ${formatDateTime(
|
||||
order.orderDate || order.createdAt
|
||||
)}</div>
|
||||
<div><strong>Skema Barang Keluar:</strong> <span style="padding:2px 8px;border-radius:4px;font-weight:bold;font-size:11px;${isManagedService ? "background:#f3e8ff;color:#6b21a8;border:1px solid #d8b4fe;" : "background:#e0f2fe;color:#0369a1;border:1px solid #bae6fd;"}">${saleTypeLabel}</span></div>
|
||||
<div><strong>Referensi SO:</strong> ${safeOrderNo}</div>
|
||||
${safeCustPo ? `<div><strong>No. PO Customer:</strong> <span style="font-family:monospace;font-weight:bold;color:#0284c7;">${safeCustPo}</span></div>` : ""}
|
||||
${order.courierName ? `<div><strong>Ekspedisi / Kurir:</strong> <span style="font-weight:bold;color:#0369a1;">${escapeHtml(order.courierName)}</span></div>` : ""}
|
||||
${order.trackingNumber ? `<div><strong>No. Resi Pengiriman:</strong> <span style="font-family:monospace;font-weight:bold;background:#e0f2fe;color:#0369a1;padding:1px 6px;border-radius:4px;">${escapeHtml(order.trackingNumber)}</span></div>` : ""}
|
||||
${order.shippingNotes ? `<div><strong>Catatan Pengiriman:</strong> <span style="font-weight:bold;color:#475569;">${escapeHtml(order.shippingNotes)}</span></div>` : ""}
|
||||
${safeNotes ? `<div><strong>Catatan:</strong> ${safeNotes}</div>` : ""}
|
||||
<div><strong>Tanggal:</strong> ${safeDocDate}</div>
|
||||
<div><strong>Skema:</strong> ${saleTypeLabel}</div>
|
||||
${safeCustPo ? `<div><strong>No. PO Customer:</strong> <span style="font-family:monospace;font-weight:bold;">${safeCustPo}</span></div>` : ""}
|
||||
${order.courierName ? `<div><strong>Kurir:</strong> ${escapeHtml(order.courierName)}${order.trackingNumber ? ` (Resi: <span style="font-family:monospace;">${escapeHtml(order.trackingNumber)}</span>)` : ""}</div>` : ""}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${isSJ && safeIntro ? `<div class="intro">${safeIntro}</div>` : ""}
|
||||
|
||||
${
|
||||
!isSJ && order.paymentStatus === "PARTIAL"
|
||||
? `
|
||||
<div style="background:#fffbeb;border:2px solid #f59e0b;padding:12px 18px;border-radius:8px;margin-bottom:20px;">
|
||||
<div style="color:#b45309;font-weight:bold;font-size:13px;">
|
||||
⚠️ PEMBERITAHUAN: STATUS PEMBAYARAN SEBAGIAN (KURANG BAYAR)
|
||||
</div>
|
||||
<div style="font-size:12px;color:#78350f;margin-top:6px;line-height:1.6;">
|
||||
Total Nilai Tagihan: <strong>${formatRupiah(order.totalAmount)}</strong> |
|
||||
Telah Diterima: <strong style="color:#047857;">${formatRupiah(order.paidAmount || 0)}</strong><br/>
|
||||
<span style="color:#b91c1c;font-size:13px;font-weight:bold;">
|
||||
SISA KEKURANGAN YANG HARUS DILUNASI: ${formatRupiah(order.totalAmount - (order.paidAmount || 0))}
|
||||
</span>
|
||||
</div>
|
||||
<div style="background:#fffbeb;border:1.5px solid #f59e0b;padding:11px 16px;border-radius:8px;margin-bottom:16px;font-size:12px;">
|
||||
<strong style="color:#92400e;">STATUS PEMBAYARAN SEBAGIAN (KURANG BAYAR)</strong><br/>
|
||||
Total Tagihan: <strong>${formatRupiah(order.totalAmount)}</strong> | Telah Dibayar: <strong>${formatRupiah(order.paidAmount || 0)}</strong> |
|
||||
<strong style="color:#b91c1c;">Sisa: ${formatRupiah(order.totalAmount - (order.paidAmount || 0))}</strong>
|
||||
</div>
|
||||
`
|
||||
: ""
|
||||
@@ -1294,13 +1586,13 @@ export default function SalesPage() {
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:40px;">No</th>
|
||||
<th>Deskripsi Barang & SKU</th>
|
||||
<th style="text-align:center;">Qty</th>
|
||||
<th style="width:36px;text-align:center;">No</th>
|
||||
<th>Deskripsi Barang & Serial Number</th>
|
||||
<th style="text-align:center;width:85px;">Qty</th>
|
||||
${
|
||||
!isSJ
|
||||
? `<th style="text-align:right;">Harga Satuan</th><th style="text-align:right;">Subtotal</th>`
|
||||
: `<th style="text-align:center;">Kondisi Fisik</th>`
|
||||
? `<th style="text-align:right;width:125px;">Harga Satuan</th><th style="text-align:right;width:130px;">Subtotal</th>`
|
||||
: `<th style="text-align:center;width:120px;">Kondisi Fisik</th>`
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -1309,64 +1601,48 @@ export default function SalesPage() {
|
||||
|
||||
${
|
||||
!isSJ && order.shippingCost > 0
|
||||
? `
|
||||
<div style="display:flex;justify-content:space-between;padding:10px 16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;margin-bottom:12px;font-size:13px;">
|
||||
<div>
|
||||
<strong>Ongkos Kirim & Ekspedisi Kargo:</strong>
|
||||
${order.courierName ? `<span style="color:#0369a1;font-weight:bold;margin-left:6px;">${escapeHtml(order.courierName)}</span>` : ""}
|
||||
${order.trackingNumber ? `<span style="font-family:monospace;color:#0f172a;background:#e2e8f0;padding:1px 6px;border-radius:4px;margin-left:6px;">Resi: ${escapeHtml(order.trackingNumber)}</span>` : ""}
|
||||
${order.shippingNotes ? `<span style="color:#64748b;margin-left:6px;">(${escapeHtml(order.shippingNotes)})</span>` : ""}
|
||||
</div>
|
||||
<div style="font-weight:bold;color:#0f172a;">${formatRupiah(order.shippingCost)}</div>
|
||||
</div>
|
||||
`
|
||||
? `<div style="display:flex;justify-content:space-between;padding:9px 14px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:10px;font-size:12.5px;">
|
||||
<span><strong>Ongkos Kirim${order.courierName ? ` (${escapeHtml(order.courierName)})` : ""}:</strong></span>
|
||||
<strong>${formatRupiah(order.shippingCost)}</strong>
|
||||
</div>`
|
||||
: ""
|
||||
}
|
||||
|
||||
${
|
||||
!isSJ && order.includeTax && order.taxAmount > 0
|
||||
? `
|
||||
<div style="display:flex;justify-content:space-between;padding:10px 16px;background:#fffbeb;border:1px solid #fef3c7;border-radius:8px;margin-bottom:12px;font-size:13px;color:#92400e;">
|
||||
<div>
|
||||
<strong>PPN Penjualan (${order.taxRate || 11}%):</strong>
|
||||
</div>
|
||||
<div style="font-weight:bold;">${formatRupiah(order.taxAmount)}</div>
|
||||
</div>
|
||||
`
|
||||
? `<div style="display:flex;justify-content:space-between;padding:9px 14px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:10px;font-size:12.5px;">
|
||||
<span><strong>PPN (${order.taxRate || 11}%):</strong></span>
|
||||
<strong>${formatRupiah(order.taxAmount)}</strong>
|
||||
</div>`
|
||||
: ""
|
||||
}
|
||||
|
||||
${
|
||||
!isSJ
|
||||
? `<div class="total-box"><span>TOTAL TAGIHAN INVOICE</span><span>${formatRupiah(
|
||||
order.totalAmount
|
||||
)}</span></div>`
|
||||
? `<div class="total-box"><span>TOTAL TAGIHAN</span><span>${formatRupiah(order.totalAmount)}</span></div>`
|
||||
: ""
|
||||
}
|
||||
|
||||
${!isSJ && safeBankInfo ? `<div class="info-box"><strong>Pembayaran Transfer ke Rekening:</strong><br/>${safeBankInfo}</div>` : ""}
|
||||
${safeFooterNotes ? `<div class="info-box"><strong>Catatan / Ketentuan:</strong><br/>${safeFooterNotes.replace(/\n/g, "<br/>")}</div>` : ""}
|
||||
|
||||
<div class="signatures">
|
||||
<div>
|
||||
<div>Diserahkan Oleh,</div>
|
||||
${!isSJ ? `
|
||||
<div style="margin-top:12px;margin-bottom:8px;">
|
||||
${order.paymentStatus === "PAID"
|
||||
? `<span style="display:inline-block;padding:5px 18px;border-radius:6px;font-size:14px;font-weight:900;letter-spacing:1.5px;background:#ecfdf5;color:#047857;border:2px solid #10b981;">PAID</span>`
|
||||
: order.paymentStatus === "PARTIAL"
|
||||
? `<div style="display:inline-block;padding:5px 14px;border-radius:6px;font-size:12px;font-weight:900;background:#fffbeb;color:#b45309;border:2px solid #f59e0b;">
|
||||
KURANG BAYAR<br/>
|
||||
<span style="font-size:10px;font-weight:normal;">Sisa: ${formatRupiah(order.totalAmount - (order.paidAmount || 0))}</span>
|
||||
</div>`
|
||||
: `<span style="display:inline-block;padding:5px 18px;border-radius:6px;font-size:14px;font-weight:900;letter-spacing:1.5px;background:#fff1f2;color:#be123c;border:2px solid #f43f5e;">UNPAID</span>`
|
||||
}
|
||||
</div>
|
||||
<div style="border-top:1px solid #64748b;padding-top:6px;width:200px;margin:0 auto;"><strong>Bagian Penjualan / Finance</strong></div>
|
||||
` : `
|
||||
<div class="sig-line"><strong>Bagian Gudang / Logistik</strong></div>
|
||||
`}
|
||||
<div>${safeSenderLabel}</div>
|
||||
${
|
||||
!isSJ
|
||||
? `<div style="margin-top:14px;margin-bottom:10px;">
|
||||
<span style="display:inline-block;padding:4px 16px;border-radius:5px;font-size:12px;font-weight:900;letter-spacing:1px;border:2px solid ${
|
||||
order.paymentStatus === "PAID" ? "#047857;color:#047857" : order.paymentStatus === "PARTIAL" ? "#b45309;color:#b45309" : "#be123c;color:#be123c"
|
||||
};">${order.paymentStatus === "PAID" ? "PAID" : order.paymentStatus === "PARTIAL" ? "PARTIAL" : "UNPAID"}</span>
|
||||
</div>
|
||||
<div style="border-top:1px solid #475569;padding-top:6px;width:210px;margin:0 auto;"><strong>${safeSenderName}</strong></div>`
|
||||
: `<div class="sig-line"><strong>${safeSenderName}</strong></div>`
|
||||
}
|
||||
</div>
|
||||
<div>
|
||||
<div>Diterima Oleh,</div>
|
||||
<div class="sig-line"><strong>${safeCustName}</strong></div>
|
||||
<div>${safeReceiverLabel}</div>
|
||||
<div class="sig-line"><strong>${safeReceiverName}</strong></div>
|
||||
</div>
|
||||
</div>
|
||||
<script>window.onload = () => { window.print(); };</script>
|
||||
@@ -1920,9 +2196,9 @@ export default function SalesPage() {
|
||||
{canSeeSalesMoney && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handlePrintDocument(o, "INVOICE")}
|
||||
onClick={() => openDocPrintModal(o, "INVOICE")}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded bg-slate-100 hover:bg-blue-50 text-slate-700 hover:text-blue-700 border border-slate-200 text-[11px] font-semibold whitespace-nowrap transition-colors"
|
||||
title="Cetak Faktur Tagihan (Invoice)"
|
||||
title="Edit & Cetak Custom Invoice (dengan Logo PT)"
|
||||
>
|
||||
<FileText className="h-3 w-3" />
|
||||
<span>Invoice</span>
|
||||
@@ -1930,12 +2206,12 @@ export default function SalesPage() {
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handlePrintDocument(o, "SURAT_JALAN")}
|
||||
onClick={() => openDocPrintModal(o, "SURAT_JALAN")}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded bg-slate-100 hover:bg-emerald-50 text-slate-700 hover:text-emerald-700 border border-slate-200 text-[11px] font-semibold whitespace-nowrap transition-colors"
|
||||
title="Cetak Surat Jalan Gudang (Delivery Order)"
|
||||
title="Edit & Cetak Surat Serah Terima Barang / Surat Jalan (dengan Logo PT)"
|
||||
>
|
||||
<Printer className="h-3 w-3" />
|
||||
<span>Surat Jalan</span>
|
||||
<span>Serah Terima</span>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
@@ -4600,6 +4876,251 @@ export default function SalesPage() {
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* MODAL EDIT & CETAK CUSTOM INVOICE / SURAT SERAH TERIMA BARANG */}
|
||||
<Modal
|
||||
isOpen={Boolean(printModalOrder)}
|
||||
onClose={() => setPrintModalOrder(null)}
|
||||
title={
|
||||
printModalType === "SURAT_JALAN"
|
||||
? "Edit & Cetak Surat Serah Terima Barang (Custom & Logo)"
|
||||
: "Edit & Cetak Invoice (Custom & Logo)"
|
||||
}
|
||||
maxWidth="max-w-2xl"
|
||||
>
|
||||
<div className="space-y-4 text-xs">
|
||||
{/* Baris Logo PT */}
|
||||
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
{docShowLogo && docLogoDataUrl ? (
|
||||
<img
|
||||
src={docLogoDataUrl}
|
||||
alt="Logo"
|
||||
className="h-12 max-w-[120px] object-contain bg-white p-1 rounded border border-slate-200"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-12 w-12 rounded bg-slate-100 border border-dashed border-slate-300 flex items-center justify-center text-[10px] text-slate-500">
|
||||
No Logo
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<div className="font-bold text-slate-900">Logo Perusahaan pada Dokumen</div>
|
||||
<label className="inline-flex items-center gap-1.5 mt-1 cursor-pointer text-[11px] text-slate-600">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={docShowLogo}
|
||||
onChange={(e) => setDocShowLogo(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span>Tampilkan logo di kop surat</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<label className="cursor-pointer inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-slate-900 text-white text-[11px] font-semibold hover:bg-slate-800">
|
||||
<Upload className="h-3 w-3" />
|
||||
<span>Upload / Ganti Logo</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp,image/gif"
|
||||
onChange={handleDocLogoUpload}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Judul Dokumen</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docTitle}
|
||||
onChange={(e) => setDocTitle(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-semibold"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Subjudul / Keterangan Kop</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docSubtitle}
|
||||
onChange={(e) => setDocSubtitle(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Nomor Dokumen</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docNumber}
|
||||
onChange={(e) => setDocNumber(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Tanggal Dokumen</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docDateText}
|
||||
onChange={(e) => setDocDateText(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Nama Perusahaan Pengirim</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docCompanyName}
|
||||
onChange={(e) => setDocCompanyName(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-semibold"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Kontak / NPWP Perusahaan</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docCompanyContact}
|
||||
onChange={(e) => setDocCompanyContact(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">Alamat Perusahaan</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docCompanyAddress}
|
||||
onChange={(e) => setDocCompanyAddress(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Nama Penerima / Customer</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docCustomerName}
|
||||
onChange={(e) => setDocCustomerName(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-semibold"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Telepon & Alamat Customer</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docCustomerAddress}
|
||||
onChange={(e) => setDocCustomerAddress(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{printModalType === "SURAT_JALAN" ? (
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Kalimat Pembuka Surat Serah Terima
|
||||
</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={docIntroText}
|
||||
onChange={(e) => setDocIntroText(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Informasi Rekening Pembayaran
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docBankInfo}
|
||||
onChange={(e) => setDocBankInfo(e.target.value)}
|
||||
placeholder="Contoh: Bank BCA 123-456-7890 a/n PT ..."
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="sm:col-span-2">
|
||||
<label className="block font-semibold text-slate-700 mb-1">
|
||||
Catatan / Syarat & Ketentuan Kustom
|
||||
</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={docFooterNotes}
|
||||
onChange={(e) => setDocFooterNotes(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Label TTD Penyerah / Pengirim</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docSenderLabel}
|
||||
onChange={(e) => setDocSenderLabel(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Nama Penandatangan Pengirim</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docSenderName}
|
||||
onChange={(e) => setDocSenderName(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Label TTD Penerima</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docReceiverLabel}
|
||||
onChange={(e) => setDocReceiverLabel(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block font-semibold text-slate-700 mb-1">Nama Penerima di Kolom TTD</label>
|
||||
<input
|
||||
type="text"
|
||||
value={docReceiverName}
|
||||
onChange={(e) => setDocReceiverName(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-2 p-2.5 rounded-lg bg-slate-50 border border-slate-200 cursor-pointer text-[11px] font-medium text-slate-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={docSaveAsDefault}
|
||||
onChange={(e) => setDocSaveAsDefault(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span>Simpan perubahan logo & template ini sebagai default untuk <strong>{docCompanyName || "PT ini"}</strong></span>
|
||||
</label>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-2 border-t border-slate-200">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPrintModalOrder(null)}
|
||||
className="px-4 py-2 border border-slate-300 rounded-lg text-slate-700 hover:bg-slate-100 font-semibold"
|
||||
>
|
||||
Tutup
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={docSavingDefault}
|
||||
onClick={handleExecuteCustomPrint}
|
||||
className="inline-flex items-center gap-1.5 px-5 py-2 bg-slate-900 hover:bg-slate-800 text-white rounded-lg font-semibold disabled:opacity-50"
|
||||
>
|
||||
<Printer className="h-3.5 w-3.5" />
|
||||
<span>{docSavingDefault ? "Menyimpan..." : "Cetak / Simpan PDF"}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { Sidebar } from "./Sidebar";
|
||||
import { Navbar } from "./Navbar";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import { canAccessRoute, getDefaultLandingRoute } from "@/lib/permissions";
|
||||
import type { CompanyProfile } from "@/lib/companies";
|
||||
import { ShieldAlert, ArrowLeft } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
@@ -16,7 +17,8 @@ interface UserSession {
|
||||
}
|
||||
|
||||
let memoryCachedUser: UserSession | null = null;
|
||||
let memoryCachedCompanies: string[] = ["PT EnterpriseCore Utama"];
|
||||
let memoryCachedCompanies: string[] = [];
|
||||
let memoryCachedProfiles: Record<string, CompanyProfile> = {};
|
||||
|
||||
interface AppShellProps {
|
||||
children: ReactNode;
|
||||
@@ -45,6 +47,9 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
|
||||
});
|
||||
|
||||
const [companies, setCompanies] = useState<string[]>(memoryCachedCompanies);
|
||||
const [companyProfiles, setCompanyProfiles] = useState<Record<string, CompanyProfile>>(
|
||||
memoryCachedProfiles
|
||||
);
|
||||
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
|
||||
const [selectedCompany, setSelectedCompany] = useState<string>(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
@@ -63,9 +68,22 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
|
||||
if (mounted) {
|
||||
memoryCachedUser = data.user;
|
||||
setUser(data.user);
|
||||
if (Array.isArray(data.companies) && data.companies.length > 0) {
|
||||
if (Array.isArray(data.companies)) {
|
||||
memoryCachedCompanies = data.companies;
|
||||
setCompanies(data.companies);
|
||||
if (
|
||||
selectedCompany !== "ALL" &&
|
||||
!data.companies.includes(selectedCompany)
|
||||
) {
|
||||
setSelectedCompany("ALL");
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("erp_selected_pt", "ALL");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (data.companyProfiles && typeof data.companyProfiles === "object") {
|
||||
memoryCachedProfiles = data.companyProfiles;
|
||||
setCompanyProfiles(data.companyProfiles);
|
||||
}
|
||||
if (typeof window !== "undefined") {
|
||||
sessionStorage.setItem("erp_cached_user", JSON.stringify(data.user));
|
||||
@@ -85,10 +103,14 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
|
||||
checkUser();
|
||||
|
||||
const handleExternalCompanyUpdate = (e: any) => {
|
||||
if (e?.detail?.companies) {
|
||||
if (Array.isArray(e?.detail?.companies)) {
|
||||
memoryCachedCompanies = e.detail.companies;
|
||||
setCompanies(e.detail.companies);
|
||||
}
|
||||
if (e?.detail?.companyProfiles && typeof e.detail.companyProfiles === "object") {
|
||||
memoryCachedProfiles = e.detail.companyProfiles;
|
||||
setCompanyProfiles(e.detail.companyProfiles);
|
||||
}
|
||||
if (e?.detail?.selectedCompany) {
|
||||
setSelectedCompany(e.detail.selectedCompany);
|
||||
localStorage.setItem("erp_selected_pt", e.detail.selectedCompany);
|
||||
@@ -226,6 +248,9 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
|
||||
{/* Sidebar with role-filtered menus (responsive drawer on mobile) */}
|
||||
<Sidebar
|
||||
user={user}
|
||||
companies={companies}
|
||||
selectedCompany={selectedCompany}
|
||||
companyProfiles={companyProfiles}
|
||||
mobileOpen={mobileMenuOpen}
|
||||
onCloseMobile={() => setMobileMenuOpen(false)}
|
||||
/>
|
||||
|
||||
@@ -15,7 +15,7 @@ export function Navbar({
|
||||
userRole,
|
||||
onOpenMobileMenu,
|
||||
showCompanySelector = false,
|
||||
companies = ["PT EnterpriseCore Utama"],
|
||||
companies = [],
|
||||
selectedCompany = "ALL",
|
||||
onSelectCompany,
|
||||
}: {
|
||||
@@ -70,7 +70,9 @@ export function Navbar({
|
||||
className="bg-transparent text-xs font-medium text-slate-800 focus:outline-none cursor-pointer pr-1 max-w-[190px] truncate"
|
||||
title="Filter Entitas Perusahaan (PT)"
|
||||
>
|
||||
<option value="ALL">Semua Perusahaan ({companies.length})</option>
|
||||
<option value="ALL">
|
||||
{companies.length === 0 ? "Belum ada PT" : `Semua Perusahaan (${companies.length})`}
|
||||
</option>
|
||||
{companies.map((pt) => (
|
||||
<option key={pt} value={pt}>
|
||||
{pt}
|
||||
@@ -120,7 +122,9 @@ export function Navbar({
|
||||
className="flex-1 min-w-0 bg-white border border-slate-200 rounded-md px-2.5 py-1 text-xs font-medium text-slate-800 focus:outline-none focus:ring-1 focus:ring-slate-400"
|
||||
title="Filter Entitas Perusahaan (PT)"
|
||||
>
|
||||
<option value="ALL">Semua Perusahaan ({companies.length})</option>
|
||||
<option value="ALL">
|
||||
{companies.length === 0 ? "Belum ada PT" : `Semua Perusahaan (${companies.length})`}
|
||||
</option>
|
||||
{companies.map((pt) => (
|
||||
<option key={pt} value={pt}>
|
||||
{pt}
|
||||
|
||||
+75
-26
@@ -26,6 +26,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { canAccessRoute } from "@/lib/permissions";
|
||||
import type { CompanyProfile } from "@/lib/companies";
|
||||
|
||||
const allNavigation = [
|
||||
{ name: "Dashboard", href: "/", icon: LayoutDashboard },
|
||||
@@ -68,10 +69,16 @@ const roleLabelMap: Record<string, string> = {
|
||||
|
||||
export function Sidebar({
|
||||
user,
|
||||
companies = [],
|
||||
selectedCompany = "ALL",
|
||||
companyProfiles = {},
|
||||
mobileOpen = false,
|
||||
onCloseMobile,
|
||||
}: {
|
||||
user?: { name: string; role: string; email: string } | null;
|
||||
companies?: string[];
|
||||
selectedCompany?: string;
|
||||
companyProfiles?: Record<string, CompanyProfile>;
|
||||
mobileOpen?: boolean;
|
||||
onCloseMobile?: () => void;
|
||||
}) {
|
||||
@@ -253,33 +260,75 @@ export function Sidebar({
|
||||
mobileOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"
|
||||
)}
|
||||
>
|
||||
{/* Brand Header */}
|
||||
<div className="h-15 flex items-center justify-between px-4 gap-2 border-b border-slate-200/80">
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<div className="h-8 w-8 shrink-0 rounded-lg bg-slate-900 dark:bg-white flex items-center justify-center text-white dark:text-slate-950">
|
||||
<Building2 className="h-4 w-4" />
|
||||
{/* Brand Header (Otomatis menampilkan Logo & Nama PT aktif) */}
|
||||
{(() => {
|
||||
const activePtName =
|
||||
selectedCompany && selectedCompany !== "ALL" && companies.includes(selectedCompany)
|
||||
? selectedCompany
|
||||
: companies.length === 1
|
||||
? companies[0]
|
||||
: "";
|
||||
const activeProfile = activePtName ? companyProfiles[activePtName] : undefined;
|
||||
const fallbackLogo =
|
||||
!activeProfile?.logoDataUrl && companies.length > 0
|
||||
? companyProfiles[companies[0]]?.logoDataUrl
|
||||
: undefined;
|
||||
const displayLogo = activeProfile?.logoDataUrl || fallbackLogo;
|
||||
const displayTitle =
|
||||
activePtName || (companies.length > 1 ? "Multi-Perusahaan" : "ERP System");
|
||||
const displaySubtitle =
|
||||
activeProfile?.tagline ||
|
||||
(companies.length === 0
|
||||
? "Belum ada PT terdaftar"
|
||||
: selectedCompany === "ALL" && companies.length > 1
|
||||
? `${companies.length} Perusahaan Aktif`
|
||||
: "Enterprise ERP");
|
||||
|
||||
return (
|
||||
<div className="h-15 flex items-center justify-between px-4 gap-2 border-b border-slate-200/80">
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
{displayLogo ? (
|
||||
<img
|
||||
src={displayLogo}
|
||||
alt={displayTitle}
|
||||
className="h-9 w-9 shrink-0 rounded-lg object-contain bg-white p-0.5 border border-slate-200/80"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-8 w-8 shrink-0 rounded-lg bg-slate-900 dark:bg-white flex items-center justify-center text-white dark:text-slate-950">
|
||||
<Building2 className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<span
|
||||
className="font-semibold text-sm tracking-tight text-slate-900 dark:text-white block truncate"
|
||||
title={displayTitle}
|
||||
>
|
||||
{displayTitle}
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5 text-[10px] font-semibold text-slate-800 dark:text-slate-100 truncate">
|
||||
<span
|
||||
className={cn(
|
||||
"h-1.5 w-1.5 rounded-full shrink-0",
|
||||
companies.length > 0 ? "bg-emerald-500" : "bg-amber-400"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{displaySubtitle}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{onCloseMobile && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCloseMobile}
|
||||
aria-label="Tutup Menu"
|
||||
className="lg:hidden p-1.5 rounded-lg text-slate-400 hover:text-slate-900 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="font-semibold text-sm tracking-tight text-slate-900 dark:text-white block truncate">
|
||||
EnterpriseCore
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5 text-[10px] font-semibold text-slate-800 dark:text-slate-100">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
|
||||
Enterprise ERP
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{onCloseMobile && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCloseMobile}
|
||||
aria-label="Tutup Menu"
|
||||
className="lg:hidden p-1.5 rounded-lg text-slate-400 hover:text-slate-900 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Navigation Links */}
|
||||
<div className="flex-1 py-4 px-3 space-y-1 overflow-y-auto">
|
||||
|
||||
+216
-18
@@ -1,10 +1,35 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export const DEFAULT_COMPANIES = ["PT EnterpriseCore Utama"];
|
||||
export const DEFAULT_COMPANIES: string[] = [];
|
||||
|
||||
export interface CompanyProfile {
|
||||
name: string;
|
||||
logoDataUrl?: string;
|
||||
tagline?: string;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
npwp?: string;
|
||||
bankInfo?: string;
|
||||
// Custom Invoice Template
|
||||
invoiceTitle?: string;
|
||||
invoiceSubtitle?: string;
|
||||
invoiceFooterNotes?: string;
|
||||
invoiceSignerLabel?: string;
|
||||
invoiceSignerName?: string;
|
||||
// Custom Surat Serah Terima Barang / Surat Jalan Template
|
||||
deliveryTitle?: string;
|
||||
deliverySubtitle?: string;
|
||||
deliveryIntroText?: string;
|
||||
deliveryFooterNotes?: string;
|
||||
deliverySenderLabel?: string;
|
||||
deliverySenderName?: string;
|
||||
deliveryReceiverLabel?: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_ACCOUNTS_TEMPLATE = [
|
||||
{ code: "1001", name: "Kas Kantor Operasional", type: "ASSET" },
|
||||
{ code: "1002", name: "Bank BCA Utama", type: "ASSET" },
|
||||
{ code: "1002", name: "Bank Operasional Utama", type: "ASSET" },
|
||||
{ code: "1101", name: "Piutang Dagang (AR)", type: "ASSET" },
|
||||
{ code: "1201", name: "Persediaan Barang Dagang", type: "ASSET" },
|
||||
{ code: "1301", name: "PPN Masukan (Pajak Pembelian)", type: "ASSET" },
|
||||
@@ -16,6 +41,20 @@ export const DEFAULT_ACCOUNTS_TEMPLATE = [
|
||||
{ code: "6001", name: "Beban Gaji & Operasional", type: "EXPENSE" },
|
||||
];
|
||||
|
||||
export function sanitizeLogoDataUrl(raw?: string | null): string | undefined {
|
||||
if (!raw) return undefined;
|
||||
const trimmed = String(raw).trim();
|
||||
if (!trimmed) return undefined;
|
||||
// Tolak SVG (cegah XSS), hanya izinkan raster aman PNG/JPG/WEBP/GIF max ~1.5MB base64
|
||||
if (!/^data:image\/(png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$/.test(trimmed)) {
|
||||
throw new Error("Format logo tidak didukung. Gunakan file PNG, JPG, atau WEBP.");
|
||||
}
|
||||
if (trimmed.length > 1_500_000) {
|
||||
throw new Error("Ukuran file logo terlalu besar (maksimal 1 MB).");
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export async function getSavedCompanies(): Promise<string[]> {
|
||||
try {
|
||||
const setting = await prisma.systemSetting.findUnique({
|
||||
@@ -24,20 +63,176 @@ export async function getSavedCompanies(): Promise<string[]> {
|
||||
if (setting?.value) {
|
||||
try {
|
||||
const parsed: string[] = JSON.parse(setting.value);
|
||||
const filtered = parsed.filter(Boolean);
|
||||
if (filtered.length > 0) {
|
||||
return Array.from(new Set(filtered));
|
||||
}
|
||||
return Array.from(new Set(parsed.map((c) => String(c || "").trim()).filter(Boolean)));
|
||||
} catch {
|
||||
// ignore
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return DEFAULT_COMPANIES;
|
||||
return [];
|
||||
} catch {
|
||||
return DEFAULT_COMPANIES;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCompanyProfiles(): Promise<Record<string, CompanyProfile>> {
|
||||
try {
|
||||
const setting = await prisma.systemSetting.findUnique({
|
||||
where: { key: "COMPANY_PROFILES" },
|
||||
});
|
||||
if (setting?.value) {
|
||||
try {
|
||||
const parsed = JSON.parse(setting.value);
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||
return parsed;
|
||||
}
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
return {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveCompanyProfiles(
|
||||
profiles: Record<string, CompanyProfile>
|
||||
): Promise<void> {
|
||||
await prisma.systemSetting.upsert({
|
||||
where: { key: "COMPANY_PROFILES" },
|
||||
update: { value: JSON.stringify(profiles) },
|
||||
create: {
|
||||
key: "COMPANY_PROFILES",
|
||||
value: JSON.stringify(profiles),
|
||||
category: "FINANCE",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertCompanyProfile(
|
||||
companyName: string,
|
||||
patch: Partial<CompanyProfile>
|
||||
): Promise<Record<string, CompanyProfile>> {
|
||||
const cleanComp = companyName.trim();
|
||||
const profiles = await getCompanyProfiles();
|
||||
const existing = profiles[cleanComp] || { name: cleanComp };
|
||||
|
||||
let nextLogo = existing.logoDataUrl;
|
||||
if (patch.logoDataUrl !== undefined) {
|
||||
nextLogo = patch.logoDataUrl ? sanitizeLogoDataUrl(patch.logoDataUrl) : undefined;
|
||||
}
|
||||
|
||||
profiles[cleanComp] = {
|
||||
...existing,
|
||||
...patch,
|
||||
name: cleanComp,
|
||||
logoDataUrl: nextLogo,
|
||||
};
|
||||
|
||||
await saveCompanyProfiles(profiles);
|
||||
return profiles;
|
||||
}
|
||||
|
||||
export async function renameCompanyAcrossSystem(
|
||||
oldName: string,
|
||||
newName: string
|
||||
): Promise<{ companies: string[]; companyProfiles: Record<string, CompanyProfile> }> {
|
||||
const cleanOld = oldName.trim();
|
||||
const cleanNew = newName.trim();
|
||||
if (!cleanOld || !cleanNew) {
|
||||
throw new Error("Nama PT lama dan nama PT baru wajib diisi.");
|
||||
}
|
||||
|
||||
const list = await getSavedCompanies();
|
||||
if (cleanOld !== cleanNew && list.includes(cleanNew)) {
|
||||
throw new Error(`Nama perusahaan "${cleanNew}" sudah terdaftar.`);
|
||||
}
|
||||
|
||||
const updatedList = list.map((c) => (c === cleanOld ? cleanNew : c));
|
||||
if (!updatedList.includes(cleanNew)) {
|
||||
updatedList.push(cleanNew);
|
||||
}
|
||||
|
||||
const profiles = await getCompanyProfiles();
|
||||
if (cleanOld !== cleanNew) {
|
||||
const oldProfile = profiles[cleanOld] || { name: cleanOld };
|
||||
delete profiles[cleanOld];
|
||||
profiles[cleanNew] = { ...oldProfile, name: cleanNew };
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
prisma.systemSetting.upsert({
|
||||
where: { key: "PAYROLL_COMPANIES" },
|
||||
update: { value: JSON.stringify(updatedList) },
|
||||
create: {
|
||||
key: "PAYROLL_COMPANIES",
|
||||
value: JSON.stringify(updatedList),
|
||||
category: "FINANCE",
|
||||
},
|
||||
}),
|
||||
saveCompanyProfiles(profiles),
|
||||
...(cleanOld !== cleanNew
|
||||
? [
|
||||
prisma.account.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.journalEntry.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.salesOrder.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.purchaseOrder.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.purchaseRequisition.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.stockMovement.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.deviceRecord.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.payrollRecord.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.payrollEmployee.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
prisma.warehouse.updateMany({
|
||||
where: { companyName: cleanOld },
|
||||
data: { companyName: cleanNew },
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
|
||||
// Rapikan suffix nama PT di nama akun COA (misal "(PT Lama)" -> "(PT Baru)")
|
||||
if (cleanOld !== cleanNew) {
|
||||
const renamedAccs = await prisma.account.findMany({ where: { companyName: cleanNew } });
|
||||
for (const acc of renamedAccs) {
|
||||
if (acc.name.includes(`(${cleanOld})`)) {
|
||||
await prisma.account.update({
|
||||
where: { id: acc.id },
|
||||
data: { name: acc.name.replace(`(${cleanOld})`, `(${cleanNew})`) },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { companies: updatedList, companyProfiles: profiles };
|
||||
}
|
||||
|
||||
export async function ensureCompanyAccounts(companyName: string) {
|
||||
const cleanComp = (companyName || "").trim();
|
||||
if (!cleanComp) return;
|
||||
@@ -50,7 +245,7 @@ export async function ensureCompanyAccounts(companyName: string) {
|
||||
await prisma.account.create({
|
||||
data: {
|
||||
code: t.code,
|
||||
name: cleanComp === "PT EnterpriseCore Utama" ? t.name : `${t.name} (${cleanComp})`,
|
||||
name: `${t.name} (${cleanComp})`,
|
||||
type: t.type,
|
||||
companyName: cleanComp,
|
||||
balance: 0,
|
||||
@@ -68,14 +263,12 @@ export async function getCompanyAccount(code: string, companyName?: string) {
|
||||
});
|
||||
if (matched) return matched;
|
||||
|
||||
// Auto-provision seluruh template akun untuk PT ini agar transaksi TIDAK pernah bocor ke PT lain!
|
||||
await ensureCompanyAccounts(cleanComp);
|
||||
const provisioned = await prisma.account.findFirst({
|
||||
where: { code, companyName: cleanComp },
|
||||
});
|
||||
if (provisioned) return provisioned;
|
||||
|
||||
// Jika kode custom di luar template, buat akun khusus untuk PT ini (bukan fallback ke PT lain)
|
||||
const templateRef = await prisma.account.findFirst({ where: { code } });
|
||||
return prisma.account.create({
|
||||
data: {
|
||||
@@ -83,16 +276,21 @@ export async function getCompanyAccount(code: string, companyName?: string) {
|
||||
name: templateRef
|
||||
? `${templateRef.name.replace(/\s*\([^)]+\)\s*$/, "")} (${cleanComp})`
|
||||
: `Akun ${code} (${cleanComp})`,
|
||||
type: templateRef?.type || (code.startsWith("2") ? "LIABILITY" : code.startsWith("3") ? "EQUITY" : code.startsWith("4") ? "REVENUE" : code.startsWith("5") || code.startsWith("6") ? "EXPENSE" : "ASSET"),
|
||||
type:
|
||||
templateRef?.type ||
|
||||
(code.startsWith("2")
|
||||
? "LIABILITY"
|
||||
: code.startsWith("3")
|
||||
? "EQUITY"
|
||||
: code.startsWith("4")
|
||||
? "REVENUE"
|
||||
: code.startsWith("5") || code.startsWith("6")
|
||||
? "EXPENSE"
|
||||
: "ASSET"),
|
||||
companyName: cleanComp,
|
||||
balance: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
// Fallback hanya jika benar-benar tidak ada companyName yang dikirim
|
||||
const fallback = await prisma.account.findFirst({
|
||||
where: { code, companyName: "PT EnterpriseCore Utama" },
|
||||
});
|
||||
if (fallback) return fallback;
|
||||
return prisma.account.findFirst({ where: { code } });
|
||||
}
|
||||
Reference in new issue
Block a user