Add full project files
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { clientSchema, type ClientFormValues } from "@/lib/validations";
|
||||
|
||||
export async function getClients() {
|
||||
return prisma.client.findMany({
|
||||
orderBy: { companyName: "asc" },
|
||||
include: { _count: { select: { jobs: true } } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getClient(id: string) {
|
||||
return prisma.client.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
jobs: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: { _count: { select: { shots: true, assets: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createClient(data: ClientFormValues) {
|
||||
const validated = clientSchema.parse(data);
|
||||
const client = await prisma.client.create({ data: validated });
|
||||
revalidatePath("/clients");
|
||||
return { success: true, client };
|
||||
}
|
||||
|
||||
export async function updateClient(id: string, data: ClientFormValues) {
|
||||
const validated = clientSchema.parse(data);
|
||||
const client = await prisma.client.update({ where: { id }, data: validated });
|
||||
revalidatePath("/clients");
|
||||
revalidatePath(`/clients/${id}`);
|
||||
return { success: true, client };
|
||||
}
|
||||
|
||||
export async function deleteClient(id: string) {
|
||||
await prisma.client.delete({ where: { id } });
|
||||
revalidatePath("/clients");
|
||||
return { success: true };
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { invoiceSchema, invoicePaymentSchema, type InvoiceFormValues, type InvoicePaymentFormValues } from "@/lib/validations";
|
||||
import Decimal from "decimal.js";
|
||||
|
||||
// ─── Auto invoice numbering ───────────────────────────────────────────────────
|
||||
|
||||
async function getNextInvoiceNumber(): Promise<string> {
|
||||
const year = new Date().getFullYear();
|
||||
const latest = await prisma.invoice.findFirst({
|
||||
where: { invoiceNumber: { startsWith: `INV-${year}-` } },
|
||||
orderBy: { invoiceNumber: "desc" },
|
||||
});
|
||||
if (!latest) return `INV-${year}-0001`;
|
||||
const parts = latest.invoiceNumber.split("-");
|
||||
const seq = parseInt(parts[parts.length - 1] ?? "0", 10) + 1;
|
||||
return `INV-${year}-${String(seq).padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
// ─── Invoice CRUD ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getInvoices(filters?: { clientId?: string; jobId?: string; status?: string }) {
|
||||
return prisma.invoice.findMany({
|
||||
where: {
|
||||
...(filters?.clientId && { clientId: filters.clientId }),
|
||||
...(filters?.jobId && { jobId: filters.jobId }),
|
||||
...(filters?.status && { status: filters.status as any }),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
client: { select: { companyName: true } },
|
||||
job: { select: { projectTitle: true, projectCode: true } },
|
||||
payments: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getInvoice(id: string) {
|
||||
return prisma.invoice.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
client: true,
|
||||
job: {
|
||||
include: {
|
||||
paymentSchedule: { include: { milestones: true } },
|
||||
},
|
||||
},
|
||||
milestone: true,
|
||||
payments: { orderBy: { paymentDate: "asc" } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createInvoice(data: InvoiceFormValues) {
|
||||
const validated = invoiceSchema.parse(data);
|
||||
const taxAmount = new Decimal(validated.subtotal)
|
||||
.mul(new Decimal(validated.taxPercent).div(100))
|
||||
.toFixed(4);
|
||||
const totalAmount = new Decimal(validated.subtotal).add(taxAmount).toFixed(4);
|
||||
|
||||
const invoice = await prisma.invoice.create({
|
||||
data: {
|
||||
...validated,
|
||||
invoiceNumber: validated.invoiceNumber,
|
||||
issueDate: new Date(validated.issueDate),
|
||||
dueDate: validated.dueDate ? new Date(validated.dueDate) : undefined,
|
||||
milestoneId: validated.milestoneId || undefined,
|
||||
subtotal: new Decimal(validated.subtotal),
|
||||
taxPercent: new Decimal(validated.taxPercent),
|
||||
taxAmount: new Decimal(taxAmount),
|
||||
totalAmount: new Decimal(totalAmount),
|
||||
amountPaid: new Decimal(0),
|
||||
amountDue: new Decimal(totalAmount),
|
||||
},
|
||||
});
|
||||
|
||||
// Update milestone status if linked
|
||||
if (validated.milestoneId) {
|
||||
await prisma.paymentMilestone.update({
|
||||
where: { id: validated.milestoneId },
|
||||
data: { status: "INVOICED" },
|
||||
});
|
||||
}
|
||||
|
||||
revalidatePath("/invoices");
|
||||
return { success: true, invoice };
|
||||
}
|
||||
|
||||
export async function updateInvoice(id: string, data: InvoiceFormValues) {
|
||||
const validated = invoiceSchema.parse(data);
|
||||
const taxAmount = new Decimal(validated.subtotal)
|
||||
.mul(new Decimal(validated.taxPercent).div(100))
|
||||
.toFixed(4);
|
||||
const totalAmount = new Decimal(validated.subtotal).add(taxAmount).toFixed(4);
|
||||
|
||||
const existing = await prisma.invoice.findUnique({ where: { id }, include: { payments: true } });
|
||||
const amountPaid = existing?.payments.reduce((sum, p) => sum.add(p.amount), new Decimal(0)) ?? new Decimal(0);
|
||||
const amountDue = new Decimal(totalAmount).sub(amountPaid);
|
||||
|
||||
const invoice = await prisma.invoice.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...validated,
|
||||
issueDate: new Date(validated.issueDate),
|
||||
dueDate: validated.dueDate ? new Date(validated.dueDate) : null,
|
||||
milestoneId: validated.milestoneId || null,
|
||||
subtotal: new Decimal(validated.subtotal),
|
||||
taxPercent: new Decimal(validated.taxPercent),
|
||||
taxAmount: new Decimal(taxAmount),
|
||||
totalAmount: new Decimal(totalAmount),
|
||||
amountDue: amountDue.gt(0) ? amountDue : new Decimal(0),
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/invoices");
|
||||
revalidatePath(`/invoices/${id}`);
|
||||
return { success: true, invoice };
|
||||
}
|
||||
|
||||
export async function deleteInvoice(id: string) {
|
||||
await prisma.invoice.delete({ where: { id } });
|
||||
revalidatePath("/invoices");
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function nextInvoiceNumber() {
|
||||
return getNextInvoiceNumber();
|
||||
}
|
||||
|
||||
// ─── From milestone ───────────────────────────────────────────────────────────
|
||||
|
||||
export async function createInvoiceFromMilestone(milestoneId: string, jobTotal?: number) {
|
||||
// Check if invoice already exists for this milestone
|
||||
const existingInvoice = await prisma.invoice.findUnique({ where: { milestoneId } });
|
||||
if (existingInvoice) throw new Error("Invoice already exists for this milestone");
|
||||
|
||||
const milestone = await prisma.paymentMilestone.findUnique({
|
||||
where: { id: milestoneId },
|
||||
include: {
|
||||
schedule: {
|
||||
include: {
|
||||
job: { include: { client: true } },
|
||||
milestones: true, // needed to determine remaining uninvoiced milestones
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!milestone) throw new Error("Milestone not found");
|
||||
|
||||
const job = milestone.schedule.job;
|
||||
const effectiveJobTotal = new Decimal(jobTotal ?? 0);
|
||||
const invoiceNumber = await getNextInvoiceNumber();
|
||||
|
||||
// ── Remaining-balance calculation ─────────────────────────────────────────
|
||||
// Sum the subtotals of all non-cancelled invoices already generated for this job.
|
||||
// This ensures sent invoices are never modified — only uninvoiced milestones adjust.
|
||||
const priorInvoices = await prisma.invoice.findMany({
|
||||
where: { jobId: job.id, status: { not: "CANCELLED" } },
|
||||
select: { subtotal: true },
|
||||
});
|
||||
const alreadyInvoicedTotal = priorInvoices.reduce(
|
||||
(sum, inv) => sum.add(new Decimal(inv.subtotal.toString())),
|
||||
new Decimal(0)
|
||||
);
|
||||
|
||||
// Find which milestones in this schedule have already been invoiced
|
||||
const priorMilestoneInvoices = await prisma.invoice.findMany({
|
||||
where: { jobId: job.id, milestoneId: { not: null }, status: { not: "CANCELLED" } },
|
||||
select: { milestoneId: true },
|
||||
});
|
||||
const invoicedMilestoneIds = new Set(priorMilestoneInvoices.map(r => r.milestoneId!));
|
||||
|
||||
// Uninvoiced milestones = not cancelled and no existing invoice (includes current milestone)
|
||||
const uninvoicedMilestones = milestone.schedule.milestones.filter(
|
||||
m => m.status !== "CANCELLED" && !invoicedMilestoneIds.has(m.id)
|
||||
);
|
||||
const totalUninvoicedPercent = uninvoicedMilestones.reduce(
|
||||
(sum, m) => sum + Number(m.percentOfTotal),
|
||||
0
|
||||
);
|
||||
|
||||
// Amount still to be invoiced after previously sent invoices
|
||||
const remainingAmount = effectiveJobTotal.sub(alreadyInvoicedTotal).toDecimalPlaces(2);
|
||||
|
||||
// ── Subtotal calculation ──────────────────────────────────────────────────
|
||||
// Fixed amount overrides all percentage logic.
|
||||
// For percent-based milestones: distribute remaining balance proportionally so that
|
||||
// sum(all milestone invoices) = jobTotal regardless of when shots/assets were added.
|
||||
// The final uninvoiced milestone absorbs any rounding variance.
|
||||
let subtotal: Decimal;
|
||||
if (milestone.fixedAmount && new Decimal(milestone.fixedAmount.toString()).gt(0)) {
|
||||
subtotal = new Decimal(milestone.fixedAmount.toString());
|
||||
} else if (effectiveJobTotal.gt(0)) {
|
||||
if (remainingAmount.gt(0) && totalUninvoicedPercent > 0) {
|
||||
const isLastUninvoiced = uninvoicedMilestones.length === 1;
|
||||
if (isLastUninvoiced) {
|
||||
// Final milestone absorbs the full remaining balance (handles scope changes cleanly)
|
||||
subtotal = remainingAmount;
|
||||
} else {
|
||||
// Proportional share of the remaining balance across uninvoiced milestones
|
||||
subtotal = remainingAmount
|
||||
.mul(new Decimal(milestone.percentOfTotal.toString()).div(totalUninvoicedPercent))
|
||||
.toDecimalPlaces(2);
|
||||
}
|
||||
} else {
|
||||
// All balance already covered by prior invoices
|
||||
subtotal = new Decimal(0);
|
||||
}
|
||||
} else {
|
||||
subtotal = new Decimal(0);
|
||||
}
|
||||
|
||||
const taxPercent = new Decimal(job.taxPercent.toString());
|
||||
const taxAmount = subtotal.mul(taxPercent.div(100)).toDecimalPlaces(2);
|
||||
const totalAmount = subtotal.add(taxAmount);
|
||||
|
||||
const invoice = await prisma.invoice.create({
|
||||
data: {
|
||||
invoiceNumber,
|
||||
clientId: job.clientId,
|
||||
jobId: job.id,
|
||||
milestoneId: milestone.id,
|
||||
status: "DRAFT",
|
||||
issueDate: new Date(),
|
||||
currency: "ZAR",
|
||||
subtotal,
|
||||
taxPercent,
|
||||
taxAmount,
|
||||
totalAmount,
|
||||
amountPaid: new Decimal(0),
|
||||
amountDue: totalAmount,
|
||||
notes: milestone.description ?? undefined,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.paymentMilestone.update({
|
||||
where: { id: milestoneId },
|
||||
data: { status: "INVOICED" },
|
||||
});
|
||||
|
||||
revalidatePath(`/jobs/${job.id}`);
|
||||
revalidatePath("/invoices");
|
||||
return { success: true, invoice };
|
||||
}
|
||||
|
||||
// ─── Payments ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function recordPayment(invoiceId: string, data: InvoicePaymentFormValues) {
|
||||
const validated = invoicePaymentSchema.parse(data);
|
||||
const payment = await prisma.invoicePayment.create({
|
||||
data: {
|
||||
invoiceId,
|
||||
amount: new Decimal(validated.amount),
|
||||
paymentDate: new Date(validated.paymentDate),
|
||||
paymentMethod: validated.paymentMethod as any,
|
||||
reference: validated.reference,
|
||||
notes: validated.notes,
|
||||
},
|
||||
});
|
||||
|
||||
// Recalculate amountPaid and amountDue
|
||||
const invoice = await prisma.invoice.findUnique({
|
||||
where: { id: invoiceId },
|
||||
include: { payments: true },
|
||||
});
|
||||
if (!invoice) throw new Error("Invoice not found");
|
||||
|
||||
const amountPaid = invoice.payments.reduce((sum, p) => sum.add(p.amount), new Decimal(0));
|
||||
const amountDue = new Decimal(invoice.totalAmount.toString()).sub(amountPaid);
|
||||
const isFullyPaid = amountDue.lte(0);
|
||||
|
||||
await prisma.invoice.update({
|
||||
where: { id: invoiceId },
|
||||
data: {
|
||||
amountPaid,
|
||||
amountDue: amountDue.gt(0) ? amountDue : new Decimal(0),
|
||||
status: isFullyPaid ? "PAID" : amountPaid.gt(0) ? "PARTIALLY_PAID" : invoice.status,
|
||||
},
|
||||
});
|
||||
|
||||
// Update milestone if linked
|
||||
if (invoice.milestoneId) {
|
||||
await prisma.paymentMilestone.update({
|
||||
where: { id: invoice.milestoneId },
|
||||
data: {
|
||||
status: isFullyPaid ? "PAID" : "PARTIALLY_PAID",
|
||||
paymentReceivedDate: isFullyPaid ? new Date() : undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
revalidatePath("/invoices");
|
||||
revalidatePath(`/invoices/${invoiceId}`);
|
||||
return { success: true, payment };
|
||||
}
|
||||
|
||||
export async function deletePayment(invoiceId: string, paymentId: string) {
|
||||
await prisma.invoicePayment.delete({ where: { id: paymentId } });
|
||||
|
||||
// Recalculate
|
||||
const invoice = await prisma.invoice.findUnique({
|
||||
where: { id: invoiceId },
|
||||
include: { payments: true },
|
||||
});
|
||||
if (!invoice) return { success: true };
|
||||
|
||||
const amountPaid = invoice.payments.reduce((sum, p) => sum.add(p.amount), new Decimal(0));
|
||||
const amountDue = new Decimal(invoice.totalAmount.toString()).sub(amountPaid);
|
||||
|
||||
await prisma.invoice.update({
|
||||
where: { id: invoiceId },
|
||||
data: {
|
||||
amountPaid,
|
||||
amountDue: amountDue.gt(0) ? amountDue : new Decimal(0),
|
||||
status: amountPaid.lte(0) ? "SENT" : "PARTIALLY_PAID",
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/invoices/${invoiceId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ─── Financial summary ────────────────────────────────────────────────────────
|
||||
|
||||
export async function getFinancialSummary() {
|
||||
const invoices = await prisma.invoice.findMany({
|
||||
where: { status: { not: "CANCELLED" } },
|
||||
select: {
|
||||
status: true,
|
||||
totalAmount: true,
|
||||
amountPaid: true,
|
||||
amountDue: true,
|
||||
dueDate: true,
|
||||
},
|
||||
});
|
||||
|
||||
const now = new Date();
|
||||
let totalInvoiced = new Decimal(0);
|
||||
let totalPaid = new Decimal(0);
|
||||
let totalOutstanding = new Decimal(0);
|
||||
let totalOverdue = new Decimal(0);
|
||||
|
||||
for (const inv of invoices) {
|
||||
totalInvoiced = totalInvoiced.add(inv.totalAmount.toString());
|
||||
totalPaid = totalPaid.add(inv.amountPaid.toString());
|
||||
const due = new Decimal(inv.amountDue.toString());
|
||||
if (due.gt(0)) {
|
||||
totalOutstanding = totalOutstanding.add(due);
|
||||
if (inv.dueDate && new Date(inv.dueDate) < now) {
|
||||
totalOverdue = totalOverdue.add(due);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
totalInvoiced: totalInvoiced.toNumber(),
|
||||
totalPaid: totalPaid.toNumber(),
|
||||
totalOutstanding: totalOutstanding.toNumber(),
|
||||
totalOverdue: totalOverdue.toNumber(),
|
||||
invoiceCount: invoices.length,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { jobSchema, type JobFormValues } from "@/lib/validations";
|
||||
import { calcLineItem } from "@/lib/calculations";
|
||||
import Decimal from "decimal.js";
|
||||
|
||||
export async function getJobs(filters?: { status?: string; clientId?: string; search?: string }) {
|
||||
return prisma.job.findMany({
|
||||
where: {
|
||||
...(filters?.status && { status: filters.status as any }),
|
||||
...(filters?.clientId && { clientId: filters.clientId }),
|
||||
...(filters?.search && {
|
||||
OR: [
|
||||
{ projectTitle: { contains: filters.search, mode: "insensitive" } },
|
||||
{ projectCode: { contains: filters.search, mode: "insensitive" } },
|
||||
],
|
||||
}),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
client: { select: { companyName: true, contactPerson: true } },
|
||||
_count: { select: { shots: true, assets: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getJob(id: string) {
|
||||
return prisma.job.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
client: true,
|
||||
shots: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: {
|
||||
lineItems: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: { rateCard: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
assets: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: {
|
||||
lineItems: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: { rateCard: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
supervisions: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: {
|
||||
lineItems: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: { rateCard: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
previses: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: {
|
||||
lineItems: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: { rateCard: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
comments: { orderBy: { createdAt: "asc" }, include: { user: true } },
|
||||
history: { orderBy: { changedAt: "desc" }, take: 20 },
|
||||
paymentSchedule: { include: { milestones: { orderBy: { sortOrder: "asc" } } } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createJob(data: JobFormValues) {
|
||||
const validated = jobSchema.parse(data);
|
||||
const { issueDate, expiryDate, startDate, estimatedCompletionDate, ...rest } = validated;
|
||||
const job = await prisma.job.create({
|
||||
data: {
|
||||
...rest,
|
||||
issueDate: new Date(issueDate),
|
||||
expiryDate: expiryDate ? new Date(expiryDate) : null,
|
||||
startDate: startDate ? new Date(startDate) : null,
|
||||
estimatedCompletionDate: estimatedCompletionDate ? new Date(estimatedCompletionDate) : null,
|
||||
},
|
||||
});
|
||||
revalidatePath("/jobs");
|
||||
return { success: true, job };
|
||||
}
|
||||
|
||||
export async function updateJob(id: string, data: Partial<JobFormValues>) {
|
||||
const { issueDate, expiryDate, startDate, estimatedCompletionDate, ...rest } = data;
|
||||
const job = await prisma.job.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...rest,
|
||||
...(issueDate ? { issueDate: new Date(issueDate) } : {}),
|
||||
expiryDate: expiryDate ? new Date(expiryDate) : null,
|
||||
...(startDate !== undefined ? { startDate: startDate ? new Date(startDate) : null } : {}),
|
||||
...(estimatedCompletionDate !== undefined ? { estimatedCompletionDate: estimatedCompletionDate ? new Date(estimatedCompletionDate) : null } : {}),
|
||||
},
|
||||
});
|
||||
revalidatePath("/jobs");
|
||||
revalidatePath(`/jobs/${id}`);
|
||||
return { success: true, job };
|
||||
}
|
||||
|
||||
export async function updateJobStatus(id: string, status: string) {
|
||||
const job = await prisma.job.update({
|
||||
where: { id },
|
||||
data: { status: status as any },
|
||||
});
|
||||
revalidatePath("/jobs");
|
||||
revalidatePath(`/jobs/${id}`);
|
||||
return { success: true, job };
|
||||
}
|
||||
|
||||
export async function deleteJob(id: string) {
|
||||
await prisma.job.delete({ where: { id } });
|
||||
revalidatePath("/jobs");
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function duplicateJob(id: string) {
|
||||
const original = await prisma.job.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
shots: { include: { lineItems: true } },
|
||||
assets: { include: { lineItems: true } },
|
||||
supervisions: { include: { lineItems: true } },
|
||||
previses: { include: { lineItems: true } },
|
||||
},
|
||||
});
|
||||
if (!original) throw new Error("Job not found");
|
||||
|
||||
const { id: _id, createdAt: _ca, updatedAt: _ua, projectCode, version, ...rest } = original;
|
||||
|
||||
const newJob = await prisma.job.create({
|
||||
data: {
|
||||
...rest,
|
||||
projectCode: `${projectCode}-v${version + 1}`,
|
||||
version: version + 1,
|
||||
parentJobId: id,
|
||||
status: "DRAFT",
|
||||
shots: {
|
||||
create: original.shots.map(({ id: _sid, jobId: _jid, createdAt: _sca, updatedAt: _sua, ...shot }) => ({
|
||||
...shot,
|
||||
lineItems: {
|
||||
create: shot.lineItems.map(({ id: _lid, shotId: _shid, assetId: _aid, supervisionId: _svid, previsId: _pvid, createdAt: _lca, updatedAt: _lua, ...li }) => li),
|
||||
},
|
||||
})),
|
||||
},
|
||||
assets: {
|
||||
create: original.assets.map(({ id: _aid, jobId: _jid, createdAt: _aca, updatedAt: _aua, ...asset }) => ({
|
||||
...asset,
|
||||
lineItems: {
|
||||
create: asset.lineItems.map(({ id: _lid, shotId: _shid, assetId: _aid2, supervisionId: _svid, previsId: _pvid, createdAt: _lca, updatedAt: _lua, ...li }) => li),
|
||||
},
|
||||
})),
|
||||
},
|
||||
supervisions: {
|
||||
create: original.supervisions.map(({ id: _svid, jobId: _jid, createdAt: _svca, updatedAt: _svua, ...supervision }) => ({
|
||||
...supervision,
|
||||
lineItems: {
|
||||
create: supervision.lineItems.map(({ id: _lid, shotId: _shid, assetId: _aid, supervisionId: _svid2, previsId: _pvid, createdAt: _lca, updatedAt: _lua, ...li }) => li),
|
||||
},
|
||||
})),
|
||||
},
|
||||
previses: {
|
||||
create: original.previses.map(({ id: _pvid, jobId: _jid, createdAt: _pvca, updatedAt: _pvua, ...previs }) => ({
|
||||
...previs,
|
||||
lineItems: {
|
||||
create: previs.lineItems.map(({ id: _lid, shotId: _shid, assetId: _aid, supervisionId: _svid, previsId: _pvid2, createdAt: _lca, updatedAt: _lua, ...li }) => li),
|
||||
},
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/jobs");
|
||||
return { success: true, job: newJob };
|
||||
}
|
||||
|
||||
/**
|
||||
* Recalculate all line item totals server-side before PDF generation.
|
||||
* This prevents floating-point drift in stored values.
|
||||
*/
|
||||
export async function recalculateJobTotals(jobId: string) {
|
||||
const job = await prisma.job.findUnique({
|
||||
where: { id: jobId },
|
||||
include: {
|
||||
shots: { include: { lineItems: true } },
|
||||
assets: { include: { lineItems: true } },
|
||||
supervisions: { include: { lineItems: true } },
|
||||
previses: { include: { lineItems: true } },
|
||||
},
|
||||
});
|
||||
if (!job) throw new Error("Job not found");
|
||||
|
||||
const updates: Promise<unknown>[] = [];
|
||||
|
||||
const allLineItems = [
|
||||
...job.shots.flatMap((s) => s.lineItems.map((li) => ({ ...li, complexityMultiplier: s.complexityMultiplier }))),
|
||||
...job.assets.flatMap((a) => a.lineItems.map((li) => ({ ...li, complexityMultiplier: a.complexityMultiplier }))),
|
||||
...job.supervisions.flatMap((sv) => sv.lineItems.map((li) => ({ ...li, complexityMultiplier: sv.complexityMultiplier }))),
|
||||
...job.previses.flatMap((pv) => pv.lineItems.map((li) => ({ ...li, complexityMultiplier: pv.complexityMultiplier }))),
|
||||
];
|
||||
|
||||
for (const li of allLineItems) {
|
||||
const result = calcLineItem(
|
||||
{
|
||||
quantityHours: li.quantityHours.toString(),
|
||||
dailyRate: li.dailyRate.toString(),
|
||||
hoursPerDay: li.hoursPerDay.toString(),
|
||||
numArtists: li.numArtists.toString(),
|
||||
numDays: li.numDays.toString(),
|
||||
manualHourlyRate: li.manualHourlyRate?.toString(),
|
||||
manualSubtotal: li.manualSubtotal?.toString(),
|
||||
markupPercent: li.markupPercent.toString(),
|
||||
discountPercent: li.discountPercent.toString(),
|
||||
taxPercent: li.taxPercent.toString(),
|
||||
},
|
||||
li.complexityMultiplier.toString()
|
||||
);
|
||||
|
||||
updates.push(
|
||||
prisma.lineItem.update({
|
||||
where: { id: li.id },
|
||||
data: {
|
||||
hourlyRate: result.hourlyRate.toFixed(4),
|
||||
subtotal: result.subtotal.toFixed(4),
|
||||
markupAmount: result.markupAmount.toFixed(4),
|
||||
discountAmount: result.discountAmount.toFixed(4),
|
||||
taxAmount: result.taxAmount.toFixed(4),
|
||||
total: result.total.toFixed(4),
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.all(updates);
|
||||
return { success: true };
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { milestoneSchema, type MilestoneFormValues } from "@/lib/validations";
|
||||
import Decimal from "decimal.js";
|
||||
|
||||
// ─── Schedule CRUD ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getPaymentSchedule(jobId: string) {
|
||||
return prisma.paymentSchedule.findUnique({
|
||||
where: { jobId },
|
||||
include: {
|
||||
milestones: { orderBy: { sortOrder: "asc" } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createOrUpdateSchedule(
|
||||
jobId: string,
|
||||
template: string,
|
||||
notes?: string
|
||||
) {
|
||||
const schedule = await prisma.paymentSchedule.upsert({
|
||||
where: { jobId },
|
||||
create: { jobId, template: template as any, notes },
|
||||
update: { template: template as any, notes },
|
||||
include: { milestones: { orderBy: { sortOrder: "asc" } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, schedule };
|
||||
}
|
||||
|
||||
// ─── Milestone CRUD ───────────────────────────────────────────────────────────
|
||||
|
||||
export async function addMilestone(jobId: string, scheduleId: string, data: MilestoneFormValues) {
|
||||
const validated = milestoneSchema.parse(data);
|
||||
const count = await prisma.paymentMilestone.count({ where: { scheduleId } });
|
||||
const milestone = await prisma.paymentMilestone.create({
|
||||
data: {
|
||||
scheduleId,
|
||||
title: validated.title,
|
||||
description: validated.description,
|
||||
dueDate: validated.dueDate ? new Date(validated.dueDate) : undefined,
|
||||
percentOfTotal: new Decimal(validated.percentOfTotal),
|
||||
fixedAmount: validated.fixedAmount != null ? new Decimal(validated.fixedAmount) : undefined,
|
||||
status: validated.status as any,
|
||||
paymentReceivedDate: validated.paymentReceivedDate
|
||||
? new Date(validated.paymentReceivedDate)
|
||||
: undefined,
|
||||
notes: validated.notes,
|
||||
sortOrder: count,
|
||||
},
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, milestone };
|
||||
}
|
||||
|
||||
export async function updateMilestone(jobId: string, milestoneId: string, data: MilestoneFormValues) {
|
||||
const validated = milestoneSchema.parse(data);
|
||||
const milestone = await prisma.paymentMilestone.update({
|
||||
where: { id: milestoneId },
|
||||
data: {
|
||||
title: validated.title,
|
||||
description: validated.description,
|
||||
dueDate: validated.dueDate ? new Date(validated.dueDate) : null,
|
||||
percentOfTotal: new Decimal(validated.percentOfTotal),
|
||||
fixedAmount: validated.fixedAmount != null ? new Decimal(validated.fixedAmount) : null,
|
||||
status: validated.status as any,
|
||||
paymentReceivedDate: validated.paymentReceivedDate
|
||||
? new Date(validated.paymentReceivedDate)
|
||||
: null,
|
||||
notes: validated.notes,
|
||||
},
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, milestone };
|
||||
}
|
||||
|
||||
export async function deleteMilestone(jobId: string, milestoneId: string) {
|
||||
await prisma.paymentMilestone.delete({ where: { id: milestoneId } });
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function reorderMilestones(jobId: string, orderedIds: string[]) {
|
||||
await Promise.all(
|
||||
orderedIds.map((id, index) =>
|
||||
prisma.paymentMilestone.update({ where: { id }, data: { sortOrder: index } })
|
||||
)
|
||||
);
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ─── Schedule Generator ───────────────────────────────────────────────────────
|
||||
|
||||
type GeneratorOptions = {
|
||||
template: "STANDARD_FILM" | "SMALL_COMMERCIAL" | "EPISODIC" | "CUSTOM";
|
||||
jobTotal: number;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
depositPercent?: number;
|
||||
finalPercent?: number;
|
||||
monthlyCount?: number;
|
||||
};
|
||||
|
||||
export async function generateScheduleFromTemplate(jobId: string, opts: GeneratorOptions) {
|
||||
// Ensure schedule exists
|
||||
const schedule = await prisma.paymentSchedule.upsert({
|
||||
where: { jobId },
|
||||
create: { jobId, template: opts.template },
|
||||
update: { template: opts.template },
|
||||
});
|
||||
|
||||
// Delete existing milestones
|
||||
await prisma.paymentMilestone.deleteMany({ where: { scheduleId: schedule.id } });
|
||||
|
||||
const milestones: { title: string; percentOfTotal: number; description?: string; dueDate?: Date }[] = [];
|
||||
|
||||
const start = opts.startDate ? new Date(opts.startDate) : new Date();
|
||||
const end = opts.endDate ? new Date(opts.endDate) : null;
|
||||
|
||||
// Calculate number of months between start and end
|
||||
const monthsBetween =
|
||||
end
|
||||
? Math.max(1, Math.round((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24 * 30)))
|
||||
: opts.monthlyCount ?? 3;
|
||||
|
||||
const addMonths = (date: Date, n: number): Date => {
|
||||
const d = new Date(date);
|
||||
d.setMonth(d.getMonth() + n);
|
||||
return d;
|
||||
};
|
||||
|
||||
if (opts.template === "STANDARD_FILM") {
|
||||
const deposit = opts.depositPercent ?? 50;
|
||||
const final = opts.finalPercent ?? 10;
|
||||
const monthly = 100 - deposit - final;
|
||||
const monthlyEach = monthsBetween > 0 ? monthly / monthsBetween : monthly;
|
||||
|
||||
milestones.push({ title: "Deposit", percentOfTotal: deposit, description: "Upfront deposit on project commencement", dueDate: start });
|
||||
for (let i = 1; i <= monthsBetween; i++) {
|
||||
milestones.push({
|
||||
title: `Month ${i} Progress`,
|
||||
percentOfTotal: Math.round(monthlyEach * 100) / 100,
|
||||
description: `Monthly progress payment`,
|
||||
dueDate: addMonths(start, i),
|
||||
});
|
||||
}
|
||||
milestones.push({ title: "Final Delivery Settlement", percentOfTotal: final, description: "Final payment on project delivery", dueDate: end ?? addMonths(start, monthsBetween + 1) });
|
||||
} else if (opts.template === "SMALL_COMMERCIAL") {
|
||||
const deposit = opts.depositPercent ?? 70;
|
||||
milestones.push({ title: "Deposit", percentOfTotal: deposit, description: "Upfront deposit", dueDate: start });
|
||||
milestones.push({ title: "Final Delivery", percentOfTotal: 100 - deposit, description: "Payment on final delivery", dueDate: end ?? addMonths(start, 2) });
|
||||
} else if (opts.template === "EPISODIC") {
|
||||
const deposit = opts.depositPercent ?? 25;
|
||||
const final = opts.finalPercent ?? 10;
|
||||
const monthly = 100 - deposit - final;
|
||||
const monthlyEach = monthsBetween > 0 ? monthly / monthsBetween : monthly;
|
||||
|
||||
milestones.push({ title: "Initial Deposit", percentOfTotal: deposit, description: "Project commencement deposit", dueDate: start });
|
||||
for (let i = 1; i <= monthsBetween; i++) {
|
||||
milestones.push({
|
||||
title: `Episode Batch ${i}`,
|
||||
percentOfTotal: Math.round(monthlyEach * 100) / 100,
|
||||
description: `Monthly billing`,
|
||||
dueDate: addMonths(start, i),
|
||||
});
|
||||
}
|
||||
milestones.push({ title: "Final Completion", percentOfTotal: final, description: "Series completion payment", dueDate: end ?? addMonths(start, monthsBetween + 1) });
|
||||
}
|
||||
|
||||
if (milestones.length > 0) {
|
||||
await prisma.paymentMilestone.createMany({
|
||||
data: milestones.map((m, i) => ({
|
||||
scheduleId: schedule.id,
|
||||
title: m.title,
|
||||
description: m.description,
|
||||
percentOfTotal: new Decimal(m.percentOfTotal),
|
||||
dueDate: m.dueDate,
|
||||
status: "PENDING",
|
||||
sortOrder: i,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
const result = await prisma.paymentSchedule.findUnique({
|
||||
where: { jobId },
|
||||
include: { milestones: { orderBy: { sortOrder: "asc" } } },
|
||||
});
|
||||
return { success: true, schedule: result };
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { rateCardSchema, type RateCardFormValues } from "@/lib/validations";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function serializeRateCard(rc: any) {
|
||||
return {
|
||||
...rc,
|
||||
defaultDailyRate: Number(rc.defaultDailyRate),
|
||||
hoursPerDay: Number(rc.hoursPerDay),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getRateCards() {
|
||||
const cards = await prisma.rateCard.findMany({
|
||||
orderBy: [{ department: "asc" }, { name: "asc" }],
|
||||
where: { isActive: true },
|
||||
});
|
||||
return cards.map(serializeRateCard);
|
||||
}
|
||||
|
||||
export async function getAllRateCards() {
|
||||
const cards = await prisma.rateCard.findMany({ orderBy: [{ department: "asc" }, { name: "asc" }] });
|
||||
return cards.map(serializeRateCard);
|
||||
}
|
||||
|
||||
export async function createRateCard(data: RateCardFormValues) {
|
||||
const validated = rateCardSchema.parse(data);
|
||||
const rateCard = await prisma.rateCard.create({ data: validated });
|
||||
revalidatePath("/rate-cards");
|
||||
return { success: true, rateCard };
|
||||
}
|
||||
|
||||
export async function updateRateCard(id: string, data: RateCardFormValues) {
|
||||
const validated = rateCardSchema.parse(data);
|
||||
const rateCard = await prisma.rateCard.update({ where: { id }, data: validated });
|
||||
revalidatePath("/rate-cards");
|
||||
return { success: true, rateCard };
|
||||
}
|
||||
|
||||
export async function deleteRateCard(id: string) {
|
||||
await prisma.rateCard.delete({ where: { id } });
|
||||
revalidatePath("/rate-cards");
|
||||
return { success: true };
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { studioSettingsSchema } from "@/lib/validations";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
export async function getStudioSettings() {
|
||||
let settings = await prisma.studioSettings.findUnique({ where: { id: "default" } });
|
||||
if (!settings) {
|
||||
settings = await prisma.studioSettings.create({ data: { id: "default" } });
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
export async function updateStudioSettings(data: unknown) {
|
||||
const validated = studioSettingsSchema.parse(data);
|
||||
const settings = await prisma.studioSettings.upsert({
|
||||
where: { id: "default" },
|
||||
update: {
|
||||
...validated,
|
||||
studioEmail: validated.studioEmail || null,
|
||||
},
|
||||
create: {
|
||||
id: "default",
|
||||
...validated,
|
||||
studioEmail: validated.studioEmail || null,
|
||||
},
|
||||
});
|
||||
revalidatePath("/settings");
|
||||
revalidatePath("/", "layout");
|
||||
return { success: true, settings };
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { shotSchema, assetSchema, supervisionSchema, previsSchema, lineItemSchema, taskTemplateSchema } from "@/lib/validations";
|
||||
import { calcLineItem } from "@/lib/calculations";
|
||||
|
||||
// ─── External Shots API ──────────────────────────────────────────────────────
|
||||
|
||||
export interface ExternalShot {
|
||||
id: string;
|
||||
shotCode: string;
|
||||
scene: string;
|
||||
episode: string | null;
|
||||
shotNumber: number;
|
||||
description: string | null;
|
||||
status: string;
|
||||
priority: string;
|
||||
frameStart: number | null;
|
||||
frameEnd: number | null;
|
||||
fps: number | null;
|
||||
dueDate: string | null;
|
||||
artist: { id: string; name: string; email: string } | null;
|
||||
_count: { versions: number; tasks: number };
|
||||
}
|
||||
|
||||
export async function fetchExternalShots(projectId: string, episode?: string) {
|
||||
const apiKey = process.env.SHOTS_API_KEY;
|
||||
if (!apiKey) throw new Error("SHOTS_API_KEY is not configured on this server");
|
||||
|
||||
const url = new URL("https://review.twotalesvfx.com/api/ext/shots");
|
||||
url.searchParams.set("projectId", projectId.trim());
|
||||
if (episode) url.searchParams.set("episode", episode.trim());
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (res.status === 401) throw new Error("Invalid API key — check SHOTS_API_KEY");
|
||||
if (res.status === 400) throw new Error("Invalid or missing project ID");
|
||||
if (res.status === 404) throw new Error("Project not found");
|
||||
if (!res.ok) throw new Error(`API error: ${res.status}`);
|
||||
|
||||
const data = await res.json() as { shots: ExternalShot[]; total: number };
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function importShotsFromApi(jobId: string, shots: ExternalShot[]) {
|
||||
if (!shots.length) return { success: true, shots: [] };
|
||||
|
||||
const job = await prisma.job.findUnique({ where: { id: jobId }, select: { showId: true, jobType: true } });
|
||||
if (!job) throw new Error("Job not found");
|
||||
|
||||
// Check for existing shot codes in this job to avoid duplicates
|
||||
const existingCodes = await prisma.shot.findMany({
|
||||
where: { jobId, shotCode: { in: shots.map((s) => s.shotCode) } },
|
||||
select: { shotCode: true },
|
||||
});
|
||||
const existingSet = new Set(existingCodes.map((s) => s.shotCode));
|
||||
const toCreate = shots.filter((s) => !existingSet.has(s.shotCode));
|
||||
|
||||
if (!toCreate.length) return { success: true, shots: [], skipped: shots.length };
|
||||
|
||||
const baseCount = await prisma.shot.count({ where: { jobId } });
|
||||
|
||||
const created = await Promise.all(
|
||||
toCreate.map((s, i) =>
|
||||
prisma.shot.create({
|
||||
data: {
|
||||
jobId,
|
||||
shotCode: s.shotCode,
|
||||
scene: s.scene,
|
||||
episode: s.episode ?? null,
|
||||
description: s.description ?? null,
|
||||
shotNumber: s.shotNumber,
|
||||
sortOrder: baseCount + i,
|
||||
},
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return {
|
||||
success: true,
|
||||
shots: JSON.parse(JSON.stringify(created)),
|
||||
skipped: existingSet.size,
|
||||
};
|
||||
}
|
||||
|
||||
export interface CsvShotRow {
|
||||
shotCode: string;
|
||||
durationSeconds?: number;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export async function importShotsFromCsv(jobId: string, rows: CsvShotRow[]) {
|
||||
if (!rows.length) return { success: true, shots: [], skipped: 0 };
|
||||
|
||||
// Check for existing shot codes to avoid duplicates
|
||||
const existingCodes = await prisma.shot.findMany({
|
||||
where: { jobId, shotCode: { in: rows.map((r) => r.shotCode) } },
|
||||
select: { shotCode: true },
|
||||
});
|
||||
const existingSet = new Set(existingCodes.map((s) => s.shotCode));
|
||||
const toCreate = rows.filter((r) => !existingSet.has(r.shotCode));
|
||||
|
||||
if (!toCreate.length) return { success: true, shots: [], skipped: rows.length };
|
||||
|
||||
const baseCount = await prisma.shot.count({ where: { jobId } });
|
||||
|
||||
const created = await Promise.all(
|
||||
toCreate.map((r, i) =>
|
||||
prisma.shot.create({
|
||||
data: {
|
||||
jobId,
|
||||
shotCode: r.shotCode,
|
||||
scene: "SC",
|
||||
description: r.description ?? null,
|
||||
durationSeconds: r.durationSeconds ?? null,
|
||||
shotNumber: (baseCount + i + 1) * 10,
|
||||
sortOrder: baseCount + i,
|
||||
},
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return {
|
||||
success: true,
|
||||
shots: JSON.parse(JSON.stringify(created)),
|
||||
skipped: existingSet.size,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Shots ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function createShot(jobId: string, data: unknown) {
|
||||
const validated = shotSchema.parse(data);
|
||||
|
||||
// Fetch job to get showId and jobType for shot code generation
|
||||
const job = await prisma.job.findUnique({
|
||||
where: { id: jobId },
|
||||
select: { showId: true, jobType: true },
|
||||
});
|
||||
if (!job) throw new Error("Job not found");
|
||||
|
||||
// Auto-increment shot number scoped to this scene (and episode for episodic)
|
||||
const sceneKey = (validated.scene || "SC").toUpperCase();
|
||||
const episodeKey = validated.episode ? validated.episode.toUpperCase() : null;
|
||||
const agg = await prisma.shot.aggregate({
|
||||
where: {
|
||||
jobId,
|
||||
scene: sceneKey,
|
||||
...(job.jobType === "EPISODIC" ? { episode: episodeKey } : {}),
|
||||
},
|
||||
_max: { shotNumber: true },
|
||||
});
|
||||
const shotNumber = (agg._max.shotNumber ?? 0) + 10;
|
||||
const paddedNumber = String(shotNumber).padStart(4, "0");
|
||||
|
||||
// Build shot code
|
||||
const showId = (job.showId || "UNK").toUpperCase();
|
||||
const scene = (validated.scene || "SC").toUpperCase();
|
||||
const shotCode =
|
||||
job.jobType === "EPISODIC" && validated.episode
|
||||
? `${showId}_${validated.episode.toUpperCase()}_${scene}_${paddedNumber}`
|
||||
: `${showId}_${scene}_${paddedNumber}`;
|
||||
|
||||
const count = await prisma.shot.count({ where: { jobId } });
|
||||
const shot = await prisma.shot.create({
|
||||
data: {
|
||||
...validated,
|
||||
jobId,
|
||||
shotCode,
|
||||
shotNumber,
|
||||
sortOrder: count,
|
||||
},
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, shot: JSON.parse(JSON.stringify(shot)) };
|
||||
}
|
||||
|
||||
export async function updateShot(shotId: string, jobId: string, data: unknown) {
|
||||
const validated = shotSchema.parse(data);
|
||||
const { shotCode: customShotCode, ...rest } = validated;
|
||||
const shot = await prisma.shot.update({
|
||||
where: { id: shotId },
|
||||
data: customShotCode ? { ...rest, shotCode: customShotCode.trim() } : rest,
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, shot: JSON.parse(JSON.stringify(shot)) };
|
||||
}
|
||||
|
||||
export async function deleteShot(shotId: string, jobId: string) {
|
||||
await prisma.shot.delete({ where: { id: shotId } });
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function duplicateShot(shotId: string, jobId: string) {
|
||||
const original = await prisma.shot.findUnique({
|
||||
where: { id: shotId },
|
||||
include: { lineItems: true },
|
||||
});
|
||||
if (!original) throw new Error("Shot not found");
|
||||
|
||||
// Auto-increment shot number scoped to the same scene (and episode)
|
||||
const agg = await prisma.shot.aggregate({
|
||||
where: {
|
||||
jobId,
|
||||
scene: original.scene,
|
||||
...(original.episode != null ? { episode: original.episode } : {}),
|
||||
},
|
||||
_max: { shotNumber: true },
|
||||
});
|
||||
const shotNumber = (agg._max.shotNumber ?? 0) + 10;
|
||||
const paddedNumber = String(shotNumber).padStart(4, "0");
|
||||
// Rebuild shotCode preserving the original structure, just with new number
|
||||
// Replace the last 4-digit segment in the code
|
||||
const shotCode = original.shotCode.replace(/\d{4}$/, paddedNumber);
|
||||
|
||||
const { id: _id, createdAt: _ca, updatedAt: _ua, sortOrder, ...rest } = original;
|
||||
const shot = await prisma.shot.create({
|
||||
data: {
|
||||
...rest,
|
||||
shotCode,
|
||||
shotNumber,
|
||||
sortOrder: sortOrder + 1,
|
||||
lineItems: {
|
||||
create: original.lineItems.map(
|
||||
({ id: _lid, shotId: _sid, assetId: _aid, createdAt: _lca, updatedAt: _lua, ...li }) => li
|
||||
),
|
||||
},
|
||||
},
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, shot: JSON.parse(JSON.stringify(shot)) };
|
||||
}
|
||||
|
||||
export async function reorderShots(jobId: string, orderedIds: string[]) {
|
||||
await Promise.all(
|
||||
orderedIds.map((id, index) => prisma.shot.update({ where: { id }, data: { sortOrder: index } }))
|
||||
);
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ─── Assets ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function createAsset(jobId: string, data: unknown) {
|
||||
const validated = assetSchema.parse(data);
|
||||
const count = await prisma.asset.count({ where: { jobId } });
|
||||
const asset = await prisma.asset.create({
|
||||
data: { ...validated, jobId, sortOrder: count },
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, asset };
|
||||
}
|
||||
|
||||
export async function updateAsset(assetId: string, jobId: string, data: unknown) {
|
||||
const validated = assetSchema.parse(data);
|
||||
const asset = await prisma.asset.update({
|
||||
where: { id: assetId },
|
||||
data: validated,
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, asset };
|
||||
}
|
||||
|
||||
export async function deleteAsset(assetId: string, jobId: string) {
|
||||
await prisma.asset.delete({ where: { id: assetId } });
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function reorderAssets(jobId: string, orderedIds: string[]) {
|
||||
await Promise.all(
|
||||
orderedIds.map((id, index) => prisma.asset.update({ where: { id }, data: { sortOrder: index } }))
|
||||
);
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ─── Supervision ──────────────────────────────────────────────────────────────
|
||||
|
||||
export async function createSupervision(jobId: string, data: unknown) {
|
||||
const validated = supervisionSchema.parse(data);
|
||||
const count = await prisma.supervision.count({ where: { jobId } });
|
||||
const supervision = await prisma.supervision.create({
|
||||
data: { ...validated, jobId, sortOrder: count },
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, supervision: JSON.parse(JSON.stringify(supervision)) };
|
||||
}
|
||||
|
||||
export async function updateSupervision(supervisionId: string, jobId: string, data: unknown) {
|
||||
const validated = supervisionSchema.parse(data);
|
||||
const supervision = await prisma.supervision.update({
|
||||
where: { id: supervisionId },
|
||||
data: validated,
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, supervision: JSON.parse(JSON.stringify(supervision)) };
|
||||
}
|
||||
|
||||
export async function deleteSupervision(supervisionId: string, jobId: string) {
|
||||
await prisma.supervision.delete({ where: { id: supervisionId } });
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function reorderSupervisions(jobId: string, orderedIds: string[]) {
|
||||
await Promise.all(
|
||||
orderedIds.map((id, index) => prisma.supervision.update({ where: { id }, data: { sortOrder: index } }))
|
||||
);
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ─── Previs ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function createPrevis(jobId: string, data: unknown) {
|
||||
const validated = previsSchema.parse(data);
|
||||
const count = await prisma.previs.count({ where: { jobId } });
|
||||
const previs = await prisma.previs.create({
|
||||
data: { ...validated, jobId, sortOrder: count },
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, previs: JSON.parse(JSON.stringify(previs)) };
|
||||
}
|
||||
|
||||
export async function updatePrevis(previsId: string, jobId: string, data: unknown) {
|
||||
const validated = previsSchema.parse(data);
|
||||
const previs = await prisma.previs.update({
|
||||
where: { id: previsId },
|
||||
data: validated,
|
||||
include: { lineItems: { include: { rateCard: true } } },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, previs: JSON.parse(JSON.stringify(previs)) };
|
||||
}
|
||||
|
||||
export async function deletePrevis(previsId: string, jobId: string) {
|
||||
await prisma.previs.delete({ where: { id: previsId } });
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function reorderPrevises(jobId: string, orderedIds: string[]) {
|
||||
await Promise.all(
|
||||
orderedIds.map((id, index) => prisma.previs.update({ where: { id }, data: { sortOrder: index } }))
|
||||
);
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ─── Line Items ───────────────────────────────────────────────────────────────
|
||||
|
||||
export async function createLineItem(
|
||||
parentId: string,
|
||||
parentType: "shot" | "asset" | "supervision" | "previs",
|
||||
jobId: string,
|
||||
data: unknown
|
||||
) {
|
||||
const validated = lineItemSchema.parse(data);
|
||||
const count =
|
||||
parentType === "shot"
|
||||
? await prisma.lineItem.count({ where: { shotId: parentId } })
|
||||
: parentType === "asset"
|
||||
? await prisma.lineItem.count({ where: { assetId: parentId } })
|
||||
: parentType === "previs"
|
||||
? await prisma.lineItem.count({ where: { previsId: parentId } })
|
||||
: await prisma.lineItem.count({ where: { supervisionId: parentId } });
|
||||
|
||||
// Get complexity multiplier from parent
|
||||
let complexityMultiplier = "1";
|
||||
if (parentType === "shot") {
|
||||
const shot = await prisma.shot.findUnique({ where: { id: parentId }, select: { complexityMultiplier: true } });
|
||||
complexityMultiplier = shot?.complexityMultiplier.toString() ?? "1";
|
||||
} else if (parentType === "asset") {
|
||||
const asset = await prisma.asset.findUnique({ where: { id: parentId }, select: { complexityMultiplier: true } });
|
||||
complexityMultiplier = asset?.complexityMultiplier.toString() ?? "1";
|
||||
} else if (parentType === "previs") {
|
||||
const previs = await prisma.previs.findUnique({ where: { id: parentId }, select: { complexityMultiplier: true } });
|
||||
complexityMultiplier = previs?.complexityMultiplier.toString() ?? "1";
|
||||
} else {
|
||||
const supervision = await prisma.supervision.findUnique({ where: { id: parentId }, select: { complexityMultiplier: true } });
|
||||
complexityMultiplier = supervision?.complexityMultiplier.toString() ?? "1";
|
||||
}
|
||||
|
||||
const calc = calcLineItem(validated as any, complexityMultiplier);
|
||||
|
||||
const lineItem = await prisma.lineItem.create({
|
||||
data: {
|
||||
...validated,
|
||||
...(parentType === "shot"
|
||||
? { shotId: parentId }
|
||||
: parentType === "asset"
|
||||
? { assetId: parentId }
|
||||
: parentType === "previs"
|
||||
? { previsId: parentId }
|
||||
: { supervisionId: parentId }),
|
||||
sortOrder: count,
|
||||
hourlyRate: calc.hourlyRate.toFixed(4),
|
||||
subtotal: calc.subtotal.toFixed(4),
|
||||
markupAmount: calc.markupAmount.toFixed(4),
|
||||
discountAmount: calc.discountAmount.toFixed(4),
|
||||
taxAmount: calc.taxAmount.toFixed(4),
|
||||
total: calc.total.toFixed(4),
|
||||
},
|
||||
include: { rateCard: true },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, lineItem: JSON.parse(JSON.stringify(lineItem)) };
|
||||
}
|
||||
|
||||
export async function updateLineItem(
|
||||
lineItemId: string,
|
||||
jobId: string,
|
||||
data: unknown,
|
||||
complexityMultiplier?: string
|
||||
) {
|
||||
const validated = lineItemSchema.parse(data);
|
||||
const calc = calcLineItem(validated as any, complexityMultiplier ?? "1");
|
||||
|
||||
const lineItem = await prisma.lineItem.update({
|
||||
where: { id: lineItemId },
|
||||
data: {
|
||||
...validated,
|
||||
hourlyRate: calc.hourlyRate.toFixed(4),
|
||||
subtotal: calc.subtotal.toFixed(4),
|
||||
markupAmount: calc.markupAmount.toFixed(4),
|
||||
discountAmount: calc.discountAmount.toFixed(4),
|
||||
taxAmount: calc.taxAmount.toFixed(4),
|
||||
total: calc.total.toFixed(4),
|
||||
},
|
||||
include: { rateCard: true },
|
||||
});
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true, lineItem: JSON.parse(JSON.stringify(lineItem)) };
|
||||
}
|
||||
|
||||
export async function deleteLineItem(lineItemId: string, jobId: string) {
|
||||
await prisma.lineItem.delete({ where: { id: lineItemId } });
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function reorderLineItems(parentId: string, parentType: "shot" | "asset" | "supervision" | "previs", jobId: string, orderedIds: string[]) {
|
||||
await Promise.all(
|
||||
orderedIds.map((id, index) => prisma.lineItem.update({ where: { id }, data: { sortOrder: index } }))
|
||||
);
|
||||
revalidatePath(`/jobs/${jobId}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ─── Task Templates ───────────────────────────────────────────────────────────
|
||||
|
||||
export async function getTaskTemplates() {
|
||||
const templates = await prisma.taskTemplate.findMany({ orderBy: { name: "asc" } });
|
||||
return JSON.parse(JSON.stringify(templates));
|
||||
}
|
||||
|
||||
export async function createTaskTemplate(data: unknown) {
|
||||
const validated = taskTemplateSchema.parse(data);
|
||||
const template = await prisma.taskTemplate.create({ data: validated });
|
||||
return { success: true, template: JSON.parse(JSON.stringify(template)) };
|
||||
}
|
||||
|
||||
export async function deleteTaskTemplate(id: string) {
|
||||
await prisma.taskTemplate.delete({ where: { id } });
|
||||
return { success: true };
|
||||
}
|
||||
Reference in New Issue
Block a user