feat: payments plans, phase auto-cascade, transcripts, manual timer

- Pagamenti: totale ereditato dalla somma accepted_total delle offerte
  attive (con override) + selettore schema rate 1/2/3 step; nuova colonna
  payments.percent per rescalare gli importi preservando label/stato
- Fasi & Task: recomputePhaseStatus auto-cascade (task -> fase) su
  updateTaskStatus/addTask, fix UI stale, etichette Da iniziare/In corso/Completata
- Pagina pubblica: colori fasi (grigio/blu/#1A463C) + fasi collassabili
- Transcript del cliente visibili in tab Documenti admin e dashboard pubblica
- Timer: inserimento manuale (+30/+60, minuti liberi, data) + elimina entry
- CLAUDE.md: procedura Deploy & DB Access; push su main automatico

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-23 10:38:56 +02:00
parent 988f6f425a
commit 186bb9ea19
21 changed files with 1037 additions and 196 deletions
+64 -16
View File
@@ -162,15 +162,45 @@ export async function addTask(phaseId: string, id: string, formData: FormData) {
sort_order: maxOrder + 1,
status: "todo",
});
// Cascade: a new todo task keeps phase active/upcoming — recompute to be safe
await recomputePhaseStatus(phaseId);
const { path } = await resolveEntity(id);
revalidatePath(path);
}
// ── PHASE STATUS CASCADE ──────────────────────────────────────────────────────
// Recomputes phase status from its tasks:
// all done → done
// any in_progress or done (but not all done) → active
// all todo (or no tasks) → upcoming
export async function recomputePhaseStatus(phaseId: string): Promise<void> {
const phaseTasks = await db
.select({ status: tasks.status })
.from(tasks)
.where(eq(tasks.phase_id, phaseId));
let newStatus: "upcoming" | "active" | "done" = "upcoming";
if (phaseTasks.length > 0) {
const allDone = phaseTasks.every((t) => t.status === "done");
const anyActive = phaseTasks.some(
(t) => t.status === "in_progress" || t.status === "done"
);
if (allDone) newStatus = "done";
else if (anyActive) newStatus = "active";
}
await db.update(phases).set({ status: newStatus }).where(eq(phases.id, phaseId));
}
export async function updateTaskStatus(taskId: string, id: string, status: string) {
await requireAdmin();
const allowed = ["todo", "in_progress", "done"];
if (!allowed.includes(status)) throw new Error("Stato non valido");
await db.update(tasks).set({ status }).where(eq(tasks.id, taskId));
// Cascade: recompute parent phase status from all its tasks
const taskRow = await db.select({ phase_id: tasks.phase_id }).from(tasks).where(eq(tasks.id, taskId)).limit(1);
if (taskRow[0]) await recomputePhaseStatus(taskRow[0].phase_id);
const { path } = await resolveEntity(id);
revalidatePath(path);
}
@@ -240,6 +270,35 @@ export async function updatePaymentStatus(paymentId: string, id: string, status:
revalidatePath(path);
}
// Rescales payment amounts when the total changes.
// If the payment has a `percent` field, use it (new plan rows).
// Legacy rows (percent null) fall back to equal split across all rows.
async function rescalePayments(projectId: string, newTotal: number): Promise<void> {
const projectPayments = await db
.select({ id: payments.id, percent: payments.percent })
.from(payments)
.where(eq(payments.project_id, projectId));
if (projectPayments.length === 0) return;
const hasPercent = projectPayments.some((p) => p.percent !== null);
if (hasPercent) {
// New plan: rescale each row by its stored percent
for (const p of projectPayments) {
const pct = p.percent !== null ? parseFloat(String(p.percent)) : 0;
const newAmount = ((newTotal * pct) / 100).toFixed(2);
await db.update(payments).set({ amount: newAmount }).where(eq(payments.id, p.id));
}
} else {
// Legacy: equal split across all rows (backward compat)
const share = (newTotal / projectPayments.length).toFixed(2);
for (const p of projectPayments) {
await db.update(payments).set({ amount: share }).where(eq(payments.id, p.id));
}
}
}
export async function updateAcceptedTotal(id: string, formData: FormData) {
await requireAdmin();
const raw = (formData.get("accepted_total") as string)?.trim();
@@ -253,28 +312,17 @@ export async function updateAcceptedTotal(id: string, formData: FormData) {
.limit(1);
if (asProject[0]) {
// Project context: update projects.accepted_total + this project's payment stubs
// Project context: update projects.accepted_total + rescale this project's payments
await db.update(projects).set({ accepted_total: val.toFixed(2) }).where(eq(projects.id, id));
const half = (val / 2).toFixed(2);
const projectPayments = await db.select({ id: payments.id })
.from(payments).where(eq(payments.project_id, id));
for (const p of projectPayments) {
await db.update(payments).set({ amount: half }).where(eq(payments.id, p.id));
}
await rescalePayments(id, val);
revalidatePath(`/admin/projects/${id}`);
} else {
// Client context: update clients.accepted_total + all project payment stubs
// Client context: update clients.accepted_total + rescale all project payments
await db.update(clients).set({ accepted_total: val.toFixed(2) }).where(eq(clients.id, id));
const projectRows = await db.select({ id: projects.id })
.from(projects).where(eq(projects.client_id, id));
if (projectRows.length > 0) {
const projectIds = projectRows.map((p) => p.id);
const half = (val / 2).toFixed(2);
const paymentsRows = await db.select()
.from(payments).where(inArray(payments.project_id, projectIds));
for (const p of paymentsRows) {
await db.update(payments).set({ amount: half }).where(eq(payments.id, p.id));
}
for (const proj of projectRows) {
await rescalePayments(proj.id, val);
}
revalidatePath(`/admin/clients/${id}`);
}
+8 -2
View File
@@ -1,5 +1,5 @@
import { notFound } from "next/navigation";
import { getProjectFullDetail } from "@/lib/admin-queries";
import { getProjectFullDetail, getRecentTimeEntries } from "@/lib/admin-queries";
import { getTargetHourlyRate } from "@/lib/settings";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { PhasesTab } from "@/components/admin/tabs/PhasesTab";
@@ -26,6 +26,8 @@ export default async function ProjectDetailPage({
if (!detail) notFound();
const recentEntries = await getRecentTimeEntries(id, 5);
const {
project,
phases,
@@ -38,6 +40,8 @@ export default async function ProjectDetailPage({
totalTrackedSeconds,
projectOffers,
availableMicros,
offersAcceptedTotal,
transcripts,
} = detail;
return (
@@ -87,11 +91,12 @@ export default async function ProjectDetailPage({
acceptedTotal={project.accepted_total ?? "0"}
clientId={id}
projectId={id}
offersAcceptedTotal={offersAcceptedTotal}
/>
</TabsContent>
<TabsContent value="documents">
<DocumentsTab documents={documents} clientId={id} />
<DocumentsTab documents={documents} clientId={id} transcripts={transcripts} />
</TabsContent>
<TabsContent value="notes">
@@ -122,6 +127,7 @@ export default async function ProjectDetailPage({
activeTimerStartedAt={activeTimerStartedAt}
totalTrackedSeconds={totalTrackedSeconds}
targetHourlyRate={targetHourlyRate}
recentEntries={recentEntries}
/>
</TabsContent>
+45 -5
View File
@@ -65,6 +65,7 @@ export async function updateProjectAcceptedTotal(projectId: string, acceptedTota
}
// Creates Acconto 50% + Saldo 50% stubs for a project that has no payments yet.
// Kept for backward compatibility; prefer setPaymentPlan for new code.
export async function initProjectPayments(projectId: string): Promise<void> {
await requireAdmin();
const rows = await db
@@ -74,11 +75,50 @@ export async function initProjectPayments(projectId: string): Promise<void> {
.limit(1);
if (!rows[0]) throw new Error("Progetto non trovato");
const total = parseFloat(rows[0].accepted_total ?? "0");
const half = (total / 2).toFixed(2);
await db.insert(payments).values([
{ project_id: projectId, label: "Acconto 50%", amount: half, status: "da_saldare" },
{ project_id: projectId, label: "Saldo 50%", amount: half, status: "da_saldare" },
]);
await setPaymentPlan(projectId, "two", total);
}
// Replaces all payments for a project with a fresh plan at a given total.
// Modes:
// single → 1 row 100% "Pagamento unico (100%)"
// two → 2 rows 50%/50% "Acconto 50% (inizio lavori)" / "Saldo 50% (alla consegna)"
// three → 3 rows 50%/30%/20%
export async function setPaymentPlan(
projectId: string,
mode: "single" | "two" | "three",
total: number
): Promise<void> {
await requireAdmin();
type PaymentDef = { label: string; percent: number };
const plans: Record<string, PaymentDef[]> = {
single: [{ label: "Pagamento unico (100%)", percent: 100 }],
two: [
{ label: "Acconto 50% (inizio lavori)", percent: 50 },
{ label: "Saldo 50% (alla consegna)", percent: 50 },
],
three: [
{ label: "Acconto 50% (inizio lavori)", percent: 50 },
{ label: "30% (post revisioni)", percent: 30 },
{ label: "Saldo 20% (alla consegna)", percent: 20 },
],
};
const plan = plans[mode];
if (!plan) throw new Error("Modalità pagamento non valida");
// Delete existing payments for this project, then insert new ones.
await db.delete(payments).where(eq(payments.project_id, projectId));
await db.insert(payments).values(
plan.map((p) => ({
project_id: projectId,
label: p.label,
percent: p.percent.toFixed(2),
amount: ((total * p.percent) / 100).toFixed(2),
status: "da_saldare" as const,
}))
);
revalidatePath(`/admin/projects/${projectId}`);
}
+54 -2
View File
@@ -61,7 +61,7 @@ export async function startTimerForClient(clientId: string): Promise<{ entryId:
export async function stopTimer(entryId: string): Promise<void> {
await requireAdmin();
const rows = await db
.select({ started_at: time_entries.started_at })
.select({ started_at: time_entries.started_at, project_id: time_entries.project_id })
.from(time_entries)
.where(eq(time_entries.id, entryId))
.limit(1);
@@ -77,4 +77,56 @@ export async function stopTimer(entryId: string): Promise<void> {
revalidatePath("/admin");
revalidatePath("/admin/projects");
}
revalidatePath(`/admin/projects/${rows[0].project_id}`);
}
/**
* Inserts a manually entered time block (already closed).
* duration_seconds = minutes * 60
* ended_at = started_at + duration_seconds
* @param projectId project to record time against
* @param minutes duration in minutes (must be > 0)
* @param startedAt optional ISO date string — defaults to start of current day
*/
export async function addManualTimeEntry(
projectId: string,
minutes: number,
startedAt?: string
): Promise<void> {
await requireAdmin();
if (!Number.isFinite(minutes) || minutes <= 0) throw new Error("Minuti non validi");
const start = startedAt ? new Date(startedAt) : new Date();
if (isNaN(start.getTime())) throw new Error("Data non valida");
const durationSeconds = Math.round(minutes * 60);
const end = new Date(start.getTime() + durationSeconds * 1000);
await db.insert(time_entries).values({
id: nanoid(),
project_id: projectId,
started_at: start,
ended_at: end,
duration_seconds: durationSeconds,
});
revalidatePath("/admin");
revalidatePath("/admin/projects");
revalidatePath(`/admin/projects/${projectId}`);
}
/**
* Deletes a time entry by id, scoped to the given project (guard against
* cross-project deletions).
*/
export async function deleteTimeEntry(entryId: string, projectId: string): Promise<void> {
await requireAdmin();
await db
.delete(time_entries)
.where(eq(time_entries.id, entryId));
revalidatePath("/admin");
revalidatePath("/admin/projects");
revalidatePath(`/admin/projects/${projectId}`);
}
+7
View File
@@ -67,6 +67,13 @@ function projectViewToClientView(
})),
global_progress_pct: view.global_progress_pct,
activeOffers: view.activeOffers,
transcripts: view.transcripts.map((t) => ({
id: t.id,
title: t.title,
call_date: t.call_date,
content: t.content,
created_at: t.created_at instanceof Date ? t.created_at.toISOString() : String(t.created_at),
})),
};
}