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
55 changes: 55 additions & 0 deletions __tests__/api/proposals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
19 changes: 18 additions & 1 deletion app/api/proposals/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ import {
findProposalWithProject,
findUserByWallet,
isEditable,
isUniqueViolation,
ok,
updateProposalContent,
updateProposalStatus,
zodErrors,
type Proposal,
} from "@/lib/proposals";

type RouteContext = { params: Promise<{ id: string }> };
Expand Down Expand Up @@ -78,14 +80,29 @@ export const PATCH = withProposalAuth<RouteContext>(
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,
"INVALID_STATUS_TRANSITION",
`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");
}
Expand Down
48 changes: 32 additions & 16 deletions components/proposals/proposal-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
Expand All @@ -41,28 +45,28 @@ export function ProposalCard({
{initials}
</div>
<div>
<p className="font-medium">{proposal.freelancerName}</p>
<p className="font-medium">{freelancerName}</p>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>{proposal.freelancerRating.toFixed(1)} / 5</span>
<span>{(proposal.freelancerRating ?? 0).toFixed(1)} / 5</span>
<span>·</span>
<span>{proposal.freelancerPastContracts} jobs</span>
<span>{proposal.freelancerPastContracts ?? 0} jobs</span>
</div>
</div>
</div>
<ProposalStatusBadge status={proposal.status} />
</CardHeader>
<CardContent className="space-y-3">
{proposal.freelancerSkills.length > 0 && (
{(proposal.freelancerSkills ?? []).length > 0 && (
<div className="flex flex-wrap gap-1">
{proposal.freelancerSkills.slice(0, 6).map((s) => (
{(proposal.freelancerSkills ?? []).slice(0, 6).map((s) => (
<span key={s} className="rounded bg-muted px-2 py-0.5 text-xs">
{s}
</span>
))}
</div>
)}
<p className="line-clamp-2 text-sm text-muted-foreground">
{proposal.coverLetter}
{proposal.message}
</p>
<div className="grid grid-cols-2 gap-2 text-sm">
<div>
Expand All @@ -71,25 +75,37 @@ export function ProposalCard({
</div>
<div>
<span className="text-muted-foreground">Delivery: </span>
<span className="font-medium">{proposal.estimatedDuration || "-"}</span>
<span className="font-medium">{proposal.deliveryTime} days</span>
</div>
</div>
<div className="flex flex-wrap gap-2 pt-2">
<Button
variant="outline"
size="sm"
disabled={disabled}
onClick={() => onViewProfile?.(proposal)}
>
View profile
</Button>
{!readOnly && proposal.status === "pending" && (
{!readOnly && (
<>
<Button size="sm" onClick={() => onAccept?.(proposal)}>
{proposal.status !== "under_review" && (
<Button
variant="outline"
size="sm"
disabled={disabled}
onClick={() => onShortlist?.(proposal)}
>
Shortlist
</Button>
)}
<Button size="sm" disabled={disabled} onClick={() => onAccept?.(proposal)}>
Accept
</Button>
<Button
size="sm"
variant="destructive"
disabled={disabled}
onClick={() => onReject?.(proposal)}
>
Reject
Expand Down
25 changes: 18 additions & 7 deletions components/proposals/proposal-confirm-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import {

interface Props {
open: boolean;
action: "accept" | "reject" | null;
action: "shortlist" | "accept" | "reject" | null;
freelancerName?: string;
submitting?: boolean;
onCancel: () => void;
onConfirm: () => void;
}
Expand All @@ -23,27 +24,37 @@ export function ProposalConfirmDialog({
open,
action,
freelancerName,
submitting,
onCancel,
onConfirm,
}: Props) {
const isAccept = action === "accept";
const isShortlist = action === "shortlist";
return (
<AlertDialog open={open} onOpenChange={(o) => !o && onCancel()}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{isAccept ? "Accept proposal?" : "Reject proposal?"}
{isShortlist ? "Shortlist proposal?" : isAccept ? "Accept proposal?" : "Reject proposal?"}
</AlertDialogTitle>
<AlertDialogDescription>
{isAccept
? `Accepting ${freelancerName ?? "this freelancer"}'s proposal will notify them and start the project.`
: `Rejecting ${freelancerName ?? "this freelancer"}'s proposal will notify them.`}
{isShortlist
? `Shortlist ${freelancerName ?? "this freelancer"}'s proposal for further review.`
: isAccept
? `Accepting ${freelancerName ?? "this freelancer"}'s proposal will select it for this project. Only one proposal can be accepted.`
: `Reject ${freelancerName ?? "this freelancer"}'s proposal and close it for this project.`}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={onCancel}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={onConfirm}>
{isAccept ? "Accept" : "Reject"}
<AlertDialogAction disabled={submitting} onClick={onConfirm}>
{submitting
? "Saving..."
: isShortlist
? "Shortlist"
: isAccept
? "Accept"
: "Reject"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
Expand Down
16 changes: 12 additions & 4 deletions components/proposals/proposal-filters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import type { ProposalFilters as Filters } from "@/lib/proposals/types";
import type { ProposalStatus } from "@/lib/proposals";

type Filters = {
status: ProposalStatus | "all";
sortBy: "budget" | "delivery" | "rating" | "recent";
sortDir: "asc" | "desc";
search: string;
};

interface Props {
value: Filters;
Expand All @@ -26,22 +33,23 @@ export function ProposalFiltersBar({ value, onChange }: Props) {
/>
<Select
value={value.status ?? "all"}
onValueChange={(v) => onChange({ ...value, status: v as any })}
onValueChange={(v) => onChange({ ...value, status: v as ProposalStatus | "all" })}
>
<SelectTrigger className="md:w-40">
<SelectValue placeholder="Status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All</SelectItem>
<SelectItem value="pending">Pending</SelectItem>
<SelectItem value="submitted">Submitted</SelectItem>
<SelectItem value="under_review">Shortlisted</SelectItem>
<SelectItem value="accepted">Accepted</SelectItem>
<SelectItem value="rejected">Rejected</SelectItem>
<SelectItem value="updated">Updated</SelectItem>
</SelectContent>
</Select>
<Select
value={value.sortBy ?? "recent"}
onValueChange={(v) => onChange({ ...value, sortBy: v as any })}
onValueChange={(v) => onChange({ ...value, sortBy: v as Filters["sortBy"] })}
>
<SelectTrigger className="md:w-44">
<SelectValue placeholder="Sort by" />
Expand Down
Loading
Loading