From 2f137f8ba1cb50dc1b34b10617d648231704b51f Mon Sep 17 00:00:00 2001 From: joannaomotunde Date: Fri, 20 Nov 2026 06:19:46 +0000 Subject: [PATCH] Fix concurrent proposal decisions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- __tests__/api/proposals.test.ts | 55 ++++++++ app/api/proposals/[id]/route.ts | 19 ++- components/proposals/proposal-card.tsx | 48 ++++--- .../proposals/proposal-confirm-dialog.tsx | 25 +++- components/proposals/proposal-filters.tsx | 16 ++- components/proposals/proposal-list.tsx | 125 +++++++++++++----- .../proposals/proposal-status-badge.tsx | 15 ++- .../012_proposal_award_concurrency.sql | 21 +++ lib/proposals.ts | 70 ++++++++-- 9 files changed, 320 insertions(+), 74 deletions(-) create mode 100644 lib/db/migrations/012_proposal_award_concurrency.sql diff --git a/__tests__/api/proposals.test.ts b/__tests__/api/proposals.test.ts index db3e13a..19bb94f 100644 --- a/__tests__/api/proposals.test.ts +++ b/__tests__/api/proposals.test.ts @@ -274,6 +274,61 @@ describe("PATCH /api/proposals/[id]", () => { const res = await updateProposal(jsonRequest(proposalUrl, "PATCH", { status: "accepted" }), ctx(PROPOSAL_ID)); expect(res.status).toBe(200); expect((await res.json()).data.status).toBe("accepted"); + const statusUpdate = (sql as unknown as SqlMock).mock.calls[2][0].join(""); + expect(statusUpdate).toContain("project_proposal_audit_logs"); + expect(statusUpdate).toContain("AND p.client_id ="); + }); + + it("shortlists a proposal and records the action", async () => { + queueSql([[client], [proposalRow()], [proposalRow({ status: "under_review" })]]); + const res = await updateProposal( + jsonRequest(proposalUrl, "PATCH", { status: "under_review" }), + ctx(PROPOSAL_ID), + ); + expect(res.status).toBe(200); + expect((await res.json()).data.status).toBe("under_review"); + const statusUpdate = (sql as unknown as SqlMock).mock.calls[2][0].join(""); + expect(statusUpdate).toContain("'shortlist'"); + }); + + it("returns success without another write for a repeated decision", async () => { + queueSql([[client], [proposalRow({ status: "accepted" })]]); + const res = await updateProposal( + jsonRequest(proposalUrl, "PATCH", { status: "accepted" }), + ctx(PROPOSAL_ID), + ); + expect(res.status).toBe(200); + expect((await res.json()).data.status).toBe("accepted"); + expect(sql).toHaveBeenCalledTimes(2); + }); + + it("treats a concurrent identical decision as an idempotent success", async () => { + queueSql([ + [client], + [proposalRow({ status: "under_review" })], + [], + [proposalRow({ status: "accepted" })], + ]); + const res = await updateProposal( + jsonRequest(proposalUrl, "PATCH", { status: "accepted" }), + ctx(PROPOSAL_ID), + ); + expect(res.status).toBe(200); + expect((await res.json()).data.status).toBe("accepted"); + expect(sql).toHaveBeenCalledTimes(4); + }); + + it("returns a conflict when another proposal already won the project award", async () => { + queueSql([[client], [proposalRow({ status: "under_review" })]]); + (sql as unknown as SqlMock).mockRejectedValueOnce( + Object.assign(new Error("unique violation"), { code: "23505" }), + ); + const res = await updateProposal( + jsonRequest(proposalUrl, "PATCH", { status: "accepted" }), + ctx(PROPOSAL_ID), + ); + expect(res.status).toBe(409); + expect((await res.json()).errors[0].code).toBe("PROJECT_ALREADY_AWARDED"); }); it("blocks invalid status transitions", async () => { diff --git a/app/api/proposals/[id]/route.ts b/app/api/proposals/[id]/route.ts index 60363e7..2508a24 100644 --- a/app/api/proposals/[id]/route.ts +++ b/app/api/proposals/[id]/route.ts @@ -31,10 +31,12 @@ import { findProposalWithProject, findUserByWallet, isEditable, + isUniqueViolation, ok, updateProposalContent, updateProposalStatus, zodErrors, + type Proposal, } from "@/lib/proposals"; type RouteContext = { params: Promise<{ id: string }> }; @@ -78,6 +80,9 @@ export const PATCH = withProposalAuth( if (clientId !== user.id) { return failOne(403, "FORBIDDEN", "Only the project's client can change a proposal's status"); } + if (proposal.status === nextStatus) { + return ok(proposal); + } if (!canTransition(proposal.status, nextStatus)) { return failOne( 409, @@ -85,7 +90,19 @@ export const PATCH = withProposalAuth( `Cannot move a proposal from '${proposal.status}' to '${nextStatus}'`, ); } - const updated = await updateProposalStatus(proposal, nextStatus); + let updated: Proposal | null; + try { + updated = await updateProposalStatus(proposal, nextStatus, user.id); + } catch (err) { + if (isUniqueViolation(err)) { + return failOne( + 409, + "PROJECT_ALREADY_AWARDED", + "Another proposal has already been accepted for this project", + ); + } + throw err; + } if (!updated) { return failOne(409, "PROPOSAL_CHANGED", "The proposal was modified concurrently; reload and retry"); } diff --git a/components/proposals/proposal-card.tsx b/components/proposals/proposal-card.tsx index 52d8120..d209173 100644 --- a/components/proposals/proposal-card.tsx +++ b/components/proposals/proposal-card.tsx @@ -3,11 +3,13 @@ import { Card, CardContent, CardHeader } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { ProposalStatusBadge } from "./proposal-status-badge"; -import type { Proposal } from "@/lib/proposals/types"; +import type { Proposal } from "@/lib/proposals"; interface Props { proposal: Proposal; readOnly?: boolean; + disabled?: boolean; + onShortlist?: (p: Proposal) => void; onAccept?: (p: Proposal) => void; onReject?: (p: Proposal) => void; onViewProfile?: (p: Proposal) => void; @@ -16,17 +18,19 @@ interface Props { export function ProposalCard({ proposal, readOnly, + disabled, + onShortlist, onAccept, onReject, onViewProfile, }: Props) { - const ISO = /^[A-Z]{3}$/; - const code = (proposal.currency || "").toUpperCase(); - const budget = ISO.test(code) - ? new Intl.NumberFormat("en-US", { style: "currency", currency: code }).format(proposal.proposedBudget) - : `${proposal.proposedBudget.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} ${code}`; + const budget = `${proposal.budget.toLocaleString("en-US", { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + })} USDC`; - const initials = proposal.freelancerName + const freelancerName = proposal.freelancerName ?? "Freelancer"; + const initials = freelancerName .split(" ") .map((s) => s[0]) .slice(0, 2) @@ -41,20 +45,20 @@ export function ProposalCard({ {initials}
-

{proposal.freelancerName}

+

{freelancerName}

- {proposal.freelancerRating.toFixed(1)} / 5 + {(proposal.freelancerRating ?? 0).toFixed(1)} / 5 · - {proposal.freelancerPastContracts} jobs + {proposal.freelancerPastContracts ?? 0} jobs
- {proposal.freelancerSkills.length > 0 && ( + {(proposal.freelancerSkills ?? []).length > 0 && (
- {proposal.freelancerSkills.slice(0, 6).map((s) => ( + {(proposal.freelancerSkills ?? []).slice(0, 6).map((s) => ( {s} @@ -62,7 +66,7 @@ export function ProposalCard({
)}

- {proposal.coverLetter} + {proposal.message}

@@ -71,25 +75,37 @@ export function ProposalCard({
Delivery: - {proposal.estimatedDuration || "-"} + {proposal.deliveryTime} days
- {!readOnly && proposal.status === "pending" && ( + {!readOnly && ( <> - + )} +