pelagia-portal/App/app/(portal)/admin/companies/actions.ts
Hardik e308d86e93 feat: Companies — multi-company PO support with admin CRUD and export integration
Schema:
- New Company model (name, gstNumber, address, telephone, mobile, email, invoiceAddress, isActive)
- PurchaseOrder.companyId FK (optional, SET NULL on company delete)
- Migration: 20260530000003_add_company

Admin:
- /admin/companies page with full CRUD (create, edit, deactivate, delete)
- Companies table shows name, GST, contact details, status
- Companies link added to Admin section of sidebar (Briefcase icon)

PO forms (new / edit / import / manager-edit):
- Company dropdown appears at the top of Order Information when companies exist
- Pre-populated with first active company; selection persisted to DB via companyId

Import form:
- parseSheet() now extracts companyName from Excel row 1 (col A)
- Import preview auto-matches detected company name against known companies
- Shows detected name as a hint; user can override before saving

Export (PDF + XLSX):
- Company constants (CO_NAME, CO_ADDR, CO_TEL, INV_ADDR, INV_GST) are now
  derived from the linked Company record when present, falling back to the
  original Pelagia Marine hardcoded defaults when no company is set

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 19:31:34 +05:30

97 lines
4.2 KiB
TypeScript

"use server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { z } from "zod";
import { revalidatePath } from "next/cache";
type ActionResult = { ok: true } | { error: string };
const companySchema = z.object({
name: z.string().min(1, "Company name is required"),
gstNumber: z.string().optional(),
address: z.string().optional(),
telephone: z.string().optional(),
mobile: z.string().optional(),
email: z.string().email("Invalid email").optional().or(z.literal("")),
invoiceAddress: z.string().optional(),
});
export async function createCompany(formData: FormData): Promise<ActionResult> {
const session = await auth();
if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
return { error: "Unauthorized" };
}
const parsed = companySchema.safeParse({
name: formData.get("name"),
gstNumber: (formData.get("gstNumber") as string) || undefined,
address: (formData.get("address") as string) || undefined,
telephone: (formData.get("telephone") as string) || undefined,
mobile: (formData.get("mobile") as string) || undefined,
email: (formData.get("email") as string) || undefined,
invoiceAddress: (formData.get("invoiceAddress") as string) || undefined,
});
if (!parsed.success) return { error: parsed.error.errors[0]?.message ?? "Validation failed" };
const { name, gstNumber, address, telephone, mobile, email, invoiceAddress } = parsed.data;
await db.company.create({
data: { name, gstNumber: gstNumber ?? null, address: address ?? null, telephone: telephone ?? null, mobile: mobile ?? null, email: email || null, invoiceAddress: invoiceAddress ?? null },
});
revalidatePath("/admin/companies");
return { ok: true };
}
export async function updateCompany(formData: FormData): Promise<ActionResult> {
const session = await auth();
if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
return { error: "Unauthorized" };
}
const id = formData.get("id") as string;
if (!id) return { error: "Company ID is required" };
const parsed = companySchema.safeParse({
name: formData.get("name"),
gstNumber: (formData.get("gstNumber") as string) || undefined,
address: (formData.get("address") as string) || undefined,
telephone: (formData.get("telephone") as string) || undefined,
mobile: (formData.get("mobile") as string) || undefined,
email: (formData.get("email") as string) || undefined,
invoiceAddress: (formData.get("invoiceAddress") as string) || undefined,
});
if (!parsed.success) return { error: parsed.error.errors[0]?.message ?? "Validation failed" };
const { name, gstNumber, address, telephone, mobile, email, invoiceAddress } = parsed.data;
await db.company.update({
where: { id },
data: { name, gstNumber: gstNumber ?? null, address: address ?? null, telephone: telephone ?? null, mobile: mobile ?? null, email: email || null, invoiceAddress: invoiceAddress ?? null },
});
revalidatePath("/admin/companies");
return { ok: true };
}
export async function deleteCompany(id: string): Promise<ActionResult> {
const session = await auth();
if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) return { error: "Unauthorized" };
const inUse = await db.purchaseOrder.findFirst({ where: { companyId: id } });
if (inUse) return { error: "Cannot delete: company is referenced in purchase orders." };
await db.company.delete({ where: { id } });
revalidatePath("/admin/companies");
return { ok: true };
}
export async function toggleCompanyActive(id: string): Promise<ActionResult> {
const session = await auth();
if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
return { error: "Unauthorized" };
}
const company = await db.company.findUnique({ where: { id }, select: { isActive: true } });
if (!company) return { error: "Company not found" };
await db.company.update({ where: { id }, data: { isActive: !company.isActive } });
revalidatePath("/admin/companies");
return { ok: true };
}