Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions __tests__/api/proposal-acceptance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { describe, it, expect, vi, beforeEach } from "vitest";

vi.mock("@/lib/auth/session", () => ({
readAccessToken: vi.fn(),
verifyAccessToken: vi.fn(),
}));
vi.mock("@/lib/db", () => ({ sql: vi.fn() }));
vi.mock("@/lib/cache", () => ({
cacheGet: vi.fn().mockReturnValue(undefined),
cacheSet: vi.fn(),
cacheDelete: vi.fn(),
}));

import { sql } from "@/lib/db";
import { acceptProposal, updateProposalStatus } from "@/lib/proposals";

const sqlMock = sql as unknown as ReturnType<typeof vi.fn>;
const current = {
id: "22222222-2222-4222-8222-222222222222",
projectId: "11111111-1111-4111-8111-111111111111",
status: "submitted",
} as never;

function statement(): string {
return (sqlMock.mock.calls[0][0] as string[]).join(" ");
}

describe("proposal acceptance (#217)", () => {
beforeEach(() => sqlMock.mockReset());

it("creates contract, milestones and audit rows in ONE statement", async () => {
sqlMock.mockResolvedValue([]);
await acceptProposal(current);
expect(sqlMock).toHaveBeenCalledTimes(1);
const text = statement();
expect(text).toContain("UPDATE project_proposals");
expect(text).toContain("INSERT INTO contracts");
expect(text).toContain("INSERT INTO milestones");
expect(text).toContain("proposal_acceptance_audit_logs");
expect(text).toContain("'unfunded'::escrow_status");
expect(text).toContain("'pending_funding'::contract_status");
});

it("returns null when the proposal or project is no longer eligible", async () => {
sqlMock.mockResolvedValue([]);
expect(await acceptProposal(current)).toBeNull();
});

it("surfaces the unique-violation when a second proposal is accepted", async () => {
sqlMock.mockRejectedValue({ code: "23505" });
await expect(acceptProposal(current)).rejects.toMatchObject({ code: "23505" });
});

it("status change to accepted goes through the atomic path", async () => {
sqlMock.mockResolvedValue([]);
await updateProposalStatus(current, "accepted");
expect(statement()).toContain("INSERT INTO contracts");
});

it("rejecting does not create a contract", async () => {
sqlMock.mockResolvedValue([]);
await updateProposalStatus(current, "rejected");
expect(statement()).not.toContain("INSERT INTO contracts");
});
});
3 changes: 3 additions & 0 deletions app/api/proposals/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ export const PATCH = withProposalAuth<RouteContext>(
return ok(updated);
} catch (err) {
console.error(`[PATCH /api/proposals/${proposalId}]`, err);
if ((err as { code?: string })?.code === "23505") {
return failOne(409, "PROJECT_ALREADY_HAS_ACCEPTED_PROPOSAL", "This project already has an accepted proposal");
}
return failOne(500, "PROPOSAL_UPDATE_FAILED", "Failed to update proposal");
}
},
Expand Down
23 changes: 23 additions & 0 deletions lib/db/migrations/012_proposal_contract_link.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- Issue #217: proposal -> contract traceability + one accepted proposal per project
ALTER TABLE contracts
ADD COLUMN IF NOT EXISTS proposal_id UUID UNIQUE
REFERENCES project_proposals (id) ON DELETE RESTRICT;

CREATE UNIQUE INDEX IF NOT EXISTS uq_project_proposals_one_accepted
ON project_proposals (project_id) WHERE status = 'accepted';

-- Audit trail: acceptance, contract creation and escrow initialisation,
-- each with actor and timestamp (UUID-based, matches contracts/users).
CREATE TABLE IF NOT EXISTS proposal_acceptance_audit_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event TEXT NOT NULL
CHECK (event IN ('proposal_accepted', 'contract_created', 'escrow_initialized')),
proposal_id UUID NOT NULL REFERENCES project_proposals (id) ON DELETE CASCADE,
contract_id UUID NOT NULL REFERENCES contracts (id) ON DELETE CASCADE,
actor_id UUID NOT NULL REFERENCES users (id),
metadata JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_proposal_acceptance_audit_contract
ON proposal_acceptance_audit_logs (contract_id);
68 changes: 68 additions & 0 deletions lib/proposals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,8 @@ export async function updateProposalStatus(
current: Proposal,
next: ProposalStatus,
): Promise<Proposal | null> {
if (next === "accepted") return acceptProposal(current);

const rows = (await sql`
UPDATE project_proposals
SET status = ${next}::proposal_status,
Expand All @@ -488,3 +490,69 @@ export async function deleteProposal(proposal: Proposal): Promise<boolean> {
if (rows.length) invalidateProjectProposals(proposal.projectId);
return rows.length > 0;
}


/**
* Issue #217 - accepts a proposal and, in ONE atomic statement, creates the
* contract (pending_funding, escrow unfunded), its milestones from the
* proposal breakdown, and an audit row. Any failing step rolls all of it back.
* Returns null if the proposal/project is no longer eligible (409 upstream).
* A concurrent double-accept hits uq_project_proposals_one_accepted (23505).
*/
export async function acceptProposal(
current: Proposal,
): Promise<(Proposal & { contractId: string }) | null> {
const rows = (await sql`
WITH p AS (
UPDATE project_proposals pp
SET status = 'accepted'::proposal_status, updated_at = NOW()
FROM projects pr
WHERE pp.id = ${current.id}
AND pp.status = ${current.status}::proposal_status
AND pr.id = pp.project_id
AND pr.status::text IN ('open', 'active')
AND NOT EXISTS (
SELECT 1 FROM contracts c
WHERE c.project_id = pp.project_id AND c.status::text <> 'cancelled'
)
RETURNING pp.*, pr.client_id AS project_client_id
), c AS (
INSERT INTO contracts
(project_id, client_id, freelancer_id, proposal_id, total_amount, status, escrow_status)
SELECT project_id, project_client_id, freelancer_id, id, budget,
'pending_funding'::contract_status, 'unfunded'::escrow_status
FROM p
RETURNING id, project_id
), m AS (
INSERT INTO milestones
(project_id, contract_id, title, sort_order, amount, due_date)
SELECT c.project_id, c.id, e.value->>'title', (e.ord - 1)::smallint,
(e.value->>'amount')::numeric,
CASE WHEN e.value ? 'dueInDays'
THEN NOW() + ((e.value->>'dueInDays')::int * INTERVAL '1 day') END
FROM c, p, jsonb_array_elements(p.milestones) WITH ORDINALITY AS e(value, ord)
RETURNING id
), a AS (
INSERT INTO contract_state_logs
(contract_id, previous_status, new_status, changed_by_user_id, reason)
SELECT c.id, NULL, 'pending_funding'::contract_status, p.project_client_id,
'Proposal ' || p.id || ' accepted; contract created; escrow initialised (unfunded)'
FROM c, p
RETURNING id
), l AS (
INSERT INTO proposal_acceptance_audit_logs
(event, proposal_id, contract_id, actor_id, metadata)
SELECT ev.event, p.id, c.id, p.project_client_id,
jsonb_build_object('project_id', p.project_id)
FROM p, c,
(VALUES ('proposal_accepted'), ('contract_created'), ('escrow_initialized')) AS ev(event)
RETURNING id
)
SELECT p.*, c.id AS contract_id FROM p, c
`) as Array<Record<string, unknown>>;
if (!rows.length) return null;
invalidateProjectProposals(current.projectId);
return Object.assign(rowToProposal(rows[0]), {
contractId: String(rows[0].contract_id),
});
}
Loading