From 3e40a12a7974fe5ec83b53f618c5da60a1948208 Mon Sep 17 00:00:00 2001 From: olatechy0 Date: Thu, 19 Nov 2026 13:51:29 +0100 Subject: [PATCH] feat: add contract revision history for contract milestones (#240) --- __tests__/api/contract-revisions.test.ts | 167 +++++++++ .../contract-revision-history.test.tsx | 100 +++++ __tests__/lib/contract-revisions.test.ts | 117 ++++++ app/api/contracts/[id]/revisions/route.ts | 40 ++ app/api/milestones/[id]/route.ts | 17 + app/dashboard/contracts/[id]/page.tsx | 4 + .../dashboard/contract-revision-history.tsx | 344 ++++++++++++++++++ lib/contracts/revisions.ts | 248 +++++++++++++ lib/db/migrations/012_contract_revisions.sql | 69 ++++ 9 files changed, 1106 insertions(+) create mode 100644 __tests__/api/contract-revisions.test.ts create mode 100644 __tests__/components/contract-revision-history.test.tsx create mode 100644 __tests__/lib/contract-revisions.test.ts create mode 100644 app/api/contracts/[id]/revisions/route.ts create mode 100644 components/dashboard/contract-revision-history.tsx create mode 100644 lib/contracts/revisions.ts create mode 100644 lib/db/migrations/012_contract_revisions.sql diff --git a/__tests__/api/contract-revisions.test.ts b/__tests__/api/contract-revisions.test.ts new file mode 100644 index 0000000..8163556 --- /dev/null +++ b/__tests__/api/contract-revisions.test.ts @@ -0,0 +1,167 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { NextRequest } from 'next/server' + +vi.mock('@/lib/auth/middleware', () => ({ + withAuth: ( + handler: (request: NextRequest, auth: { walletAddress: string; tokenJti: string }) => unknown, + ) => + (request: NextRequest) => handler(request, { walletAddress: 'GWALLET', tokenJti: 'jti' }), +})) + +vi.mock('@/lib/db', () => ({ + sql: vi.fn(), +})) + +import * as route from '@/app/api/contracts/[id]/revisions/route' +import { sql } from '@/lib/db' + +const sqlMock = sql as unknown as ReturnType +const contractId = '11111111-1111-1111-1111-111111111111' + +function queueSql(responses: unknown[]) { + for (const response of responses) { + sqlMock.mockResolvedValueOnce(response) + } +} + +function makeRequest() { + return new NextRequest(new Request(`http://localhost/api/contracts/${contractId}/revisions`)) +} + +const baselineSnapshot = { + contract: { total_amount: '100.000000', currency: 'USDC', terms: 'Original terms' }, + milestones: [ + { + id: 'm1', + title: 'Design', + description: null, + amount: '100.000000', + currency: 'USDC', + due_date: '2026-01-10T00:00:00.000Z', + status: 'pending', + sort_order: 0, + }, + ], +} + +const updatedSnapshot = { + contract: { total_amount: '200.000000', currency: 'USDC', terms: 'Original terms' }, + milestones: [ + { + ...baselineSnapshot.milestones[0], + amount: '200.000000', + due_date: '2026-02-01T00:00:00.000Z', + }, + ], +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('GET /api/contracts/[id]/revisions', () => { + it('is read-only: only a GET handler is exported', () => { + expect(typeof route.GET).toBe('function') + expect(route).not.toHaveProperty('POST') + expect(route).not.toHaveProperty('PATCH') + expect(route).not.toHaveProperty('PUT') + expect(route).not.toHaveProperty('DELETE') + }) + + it('returns 404 when the authenticated wallet has no user row', async () => { + queueSql([[]]) + + const response = await route.GET(makeRequest()) + expect(response.status).toBe(404) + expect((await response.json()).code).toBe('USER_NOT_FOUND') + }) + + it('returns 404 when the contract does not exist', async () => { + queueSql([[{ id: 'user-1' }], []]) + + const response = await route.GET(makeRequest()) + expect(response.status).toBe(404) + expect((await response.json()).code).toBe('CONTRACT_NOT_FOUND') + }) + + it('forbids users who are not the client or freelancer', async () => { + queueSql([ + [{ id: 'user-1' }], + [{ id: contractId, client_id: 'client', freelancer_id: 'freelancer' }], + ]) + + const response = await route.GET(makeRequest()) + expect(response.status).toBe(403) + expect((await response.json()).code).toBe('ACCESS_DENIED') + }) + + it('returns revisions with author, timestamp and computed changes to a party', async () => { + queueSql([ + [{ id: 'client' }], + [{ id: contractId, client_id: 'client', freelancer_id: 'freelancer' }], + [ + { + id: 'rev-1', + snapshot: baselineSnapshot, + change_type: 'baseline', + author_wallet: null, + created_at: '2026-01-01T00:00:00.000Z', + display_name: null, + username: null, + wallet_address: null, + }, + { + id: 'rev-2', + snapshot: updatedSnapshot, + change_type: 'update', + author_wallet: 'GWALLET', + created_at: '2026-01-05T00:00:00.000Z', + display_name: 'Ola', + username: 'olatechy0', + wallet_address: 'GWALLET', + }, + ], + ]) + + const response = await route.GET(makeRequest()) + expect(response.status).toBe(200) + + const body = await response.json() + expect(body.contractId).toBe(contractId) + expect(body.revisions).toHaveLength(2) + + const [baseline, update] = body.revisions + expect(baseline.revision_number).toBe(1) + expect(baseline.changes).toBeNull() + expect(baseline.author).toBeNull() + + expect(update.revision_number).toBe(2) + expect(update.author).toEqual({ + display_name: 'Ola', + username: 'olatechy0', + wallet_address: 'GWALLET', + }) + expect(update.created_at).toBe('2026-01-05T00:00:00.000Z') + expect(update.changes.contract).toEqual([ + { field: 'budget', from: '100.000000', to: '200.000000' }, + ]) + expect(update.changes.milestones[0].changes).toEqual( + expect.arrayContaining([ + { field: 'budget', from: '100.000000', to: '200.000000' }, + { + field: 'deadline', + from: '2026-01-10T00:00:00.000Z', + to: '2026-02-01T00:00:00.000Z', + }, + ]), + ) + }) + + it('returns 500 when the database fails', async () => { + sqlMock.mockRejectedValueOnce(new Error('db down')) + + const response = await route.GET(makeRequest()) + expect(response.status).toBe(500) + expect((await response.json()).code).toBe('REVISIONS_FETCH_FAILED') + }) +}) diff --git a/__tests__/components/contract-revision-history.test.tsx b/__tests__/components/contract-revision-history.test.tsx new file mode 100644 index 0000000..a931017 --- /dev/null +++ b/__tests__/components/contract-revision-history.test.tsx @@ -0,0 +1,100 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import ContractRevisionHistory from '@/components/dashboard/contract-revision-history' + +const milestone = (amount: string, due: string) => ({ + id: 'm-1', + title: 'Design phase', + description: 'Wireframes', + amount, + currency: 'USD', + due_date: due, + status: 'pending', + sort_order: 0, +}) + +const revisions = [ + { + id: 'r-1', + revision_number: 1, + change_type: 'baseline', + created_at: '2026-01-01T10:00:00.000Z', + author: null, + snapshot: { contract: { total_amount: '1000', currency: 'USD', terms: null }, milestones: [milestone('1000', '2026-02-01T00:00:00.000Z')] }, + changes: null, + }, + { + id: 'r-2', + revision_number: 2, + change_type: 'update', + created_at: '2026-01-05T10:00:00.000Z', + author: { display_name: 'Ada Client', username: 'ada', wallet_address: 'GWALLET' }, + snapshot: { contract: { total_amount: '1500', currency: 'USD', terms: null }, milestones: [milestone('1500', '2026-03-01T00:00:00.000Z')] }, + changes: { + contract: [{ field: 'budget', from: '1000', to: '1500' }], + milestones: [ + { + id: 'm-1', + title: 'Design phase', + kind: 'changed', + changes: [ + { field: 'budget', from: '1000', to: '1500' }, + { field: 'deadline', from: '2026-02-01T00:00:00.000Z', to: '2026-03-01T00:00:00.000Z' }, + ], + }, + ], + }, + }, +] + +describe('ContractRevisionHistory', () => { + afterEach(() => { + vi.restoreAllMocks() + localStorage.clear() + }) + + it('shows author, timestamp and highlighted changes, newest first', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ ok: true, json: async () => ({ revisions }) }), + ) + + render() + + expect(await screen.findByText('Ada Client')).toBeInTheDocument() + expect(screen.getByText('Revision v2')).toBeInTheDocument() + expect(screen.getByText('Initial snapshot')).toBeInTheDocument() + expect(document.querySelector('time[datetime="2026-01-05T10:00:00.000Z"]')).toBeInTheDocument() + + // Newest revision is expanded by default and lists the diff. + expect(await screen.findByText('Changes in this revision')).toBeInTheDocument() + expect(screen.getAllByText('1,500').length).toBeGreaterThan(0) + expect(screen.getAllByText('Budget').length).toBeGreaterThan(0) + }) + + it('shows a read-only empty state', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ ok: true, json: async () => ({ revisions: [] }) }), + ) + + render() + + expect(await screen.findByText(/No revisions yet/)).toBeInTheDocument() + }) + + it('toggles a revision open and closed', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ ok: true, json: async () => ({ revisions }) }), + ) + + render() + const toggle = await screen.findByText('Revision v2') + + fireEvent.click(toggle) + await waitFor(() => + expect(screen.queryByText('Changes in this revision')).not.toBeInTheDocument(), + ) + }) +}) diff --git a/__tests__/lib/contract-revisions.test.ts b/__tests__/lib/contract-revisions.test.ts new file mode 100644 index 0000000..61ee15d --- /dev/null +++ b/__tests__/lib/contract-revisions.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'vitest' +import { + diffSnapshots, + type ContractSnapshot, + type MilestoneSnapshot, +} from '@/lib/contracts/revisions' + +function milestone(overrides: Partial = {}): MilestoneSnapshot { + return { + id: 'm1', + title: 'Design', + description: 'Landing page', + amount: '100.000000', + currency: 'USDC', + due_date: '2026-01-10T00:00:00.000Z', + status: 'pending', + sort_order: 0, + ...overrides, + } +} + +function snapshot(overrides: Partial = {}): ContractSnapshot { + return { + contract: { total_amount: '100.000000', currency: 'USDC', terms: 'Original terms' }, + milestones: [milestone()], + ...overrides, + } +} + +describe('diffSnapshots', () => { + it('returns no changes for identical snapshots', () => { + const diff = diffSnapshots(snapshot(), snapshot()) + expect(diff.contract).toEqual([]) + expect(diff.milestones).toEqual([]) + }) + + it('highlights budget changes on the contract and a milestone', () => { + const current = snapshot({ + contract: { total_amount: '250.000000', currency: 'USDC', terms: 'Original terms' }, + milestones: [milestone({ amount: '250.000000' })], + }) + const diff = diffSnapshots(snapshot(), current) + + expect(diff.contract).toEqual([ + { field: 'budget', from: '100.000000', to: '250.000000' }, + ]) + expect(diff.milestones[0].kind).toBe('changed') + expect(diff.milestones[0].changes).toContainEqual({ + field: 'budget', + from: '100.000000', + to: '250.000000', + }) + }) + + it('treats numeric formatting differences as unchanged', () => { + const diff = diffSnapshots( + snapshot(), + snapshot({ contract: { total_amount: '100', currency: 'USDC', terms: 'Original terms' } }), + ) + expect(diff.contract).toEqual([]) + }) + + it('highlights deadline changes', () => { + const current = snapshot({ + milestones: [milestone({ due_date: '2026-02-01T00:00:00.000Z' })], + }) + const diff = diffSnapshots(snapshot(), current) + + expect(diff.milestones[0].changes).toContainEqual({ + field: 'deadline', + from: '2026-01-10T00:00:00.000Z', + to: '2026-02-01T00:00:00.000Z', + }) + }) + + it('highlights scope changes in title, description and contract terms', () => { + const current = snapshot({ + contract: { total_amount: '100.000000', currency: 'USDC', terms: 'New terms' }, + milestones: [milestone({ title: 'Design & build', description: 'Full site' })], + }) + const diff = diffSnapshots(snapshot(), current) + + expect(diff.contract).toContainEqual({ field: 'scope', from: 'Original terms', to: 'New terms' }) + expect(diff.milestones[0].changes).toEqual([ + { field: 'scope', from: 'Design', to: 'Design & build' }, + { field: 'scope', from: 'Landing page', to: 'Full site' }, + ]) + }) + + it('detects added and removed milestones', () => { + const current = snapshot({ + milestones: [ + milestone({ id: 'm2', title: 'New milestone', sort_order: 1 }), + ], + }) + const diff = diffSnapshots(snapshot(), current) + + expect(diff.milestones).toEqual( + expect.arrayContaining([ + { id: 'm2', title: 'New milestone', kind: 'added', changes: [] }, + { id: 'm1', title: 'Design', kind: 'removed', changes: [] }, + ]), + ) + }) + + it('highlights status changes', () => { + const diff = diffSnapshots( + snapshot(), + snapshot({ milestones: [milestone({ status: 'approved' })] }), + ) + expect(diff.milestones[0].changes).toContainEqual({ + field: 'status', + from: 'pending', + to: 'approved', + }) + }) +}) diff --git a/app/api/contracts/[id]/revisions/route.ts b/app/api/contracts/[id]/revisions/route.ts new file mode 100644 index 0000000..8f1482e --- /dev/null +++ b/app/api/contracts/[id]/revisions/route.ts @@ -0,0 +1,40 @@ +export const dynamic = 'force-dynamic' + +import { NextRequest, NextResponse } from 'next/server' +import { withAuth } from '@/lib/auth/middleware' +import { sql } from '@/lib/db' +import { listContractRevisions } from '@/lib/contracts/revisions' + +// GET /api/contracts/:id/revisions - Read-only contract change history +export const GET = withAuth(async (request: NextRequest, auth) => { + const contractId = request.nextUrl.pathname.split('/').at(-2) + + try { + const [user] = (await sql` + SELECT id FROM users WHERE wallet_address = ${auth.walletAddress} LIMIT 1 + `) as Array<{ id: string }> + if (!user) { + return NextResponse.json({ error: 'User not found', code: 'USER_NOT_FOUND' }, { status: 404 }) + } + + const [contract] = (await sql` + SELECT id, client_id, freelancer_id FROM contracts WHERE id = ${contractId} LIMIT 1 + `) as Array<{ id: string; client_id: string; freelancer_id: string }> + if (!contract) { + return NextResponse.json({ error: 'Contract not found', code: 'CONTRACT_NOT_FOUND' }, { status: 404 }) + } + + if (user.id !== contract.client_id && user.id !== contract.freelancer_id) { + return NextResponse.json({ error: 'Access denied', code: 'ACCESS_DENIED' }, { status: 403 }) + } + + const revisions = await listContractRevisions(String(contract.id)) + return NextResponse.json({ contractId: String(contract.id), revisions }) + } catch (error) { + console.error('[GET /api/contracts/[id]/revisions]', error) + return NextResponse.json( + { error: 'Failed to load contract revisions', code: 'REVISIONS_FETCH_FAILED' }, + { status: 500 }, + ) + } +}) diff --git a/app/api/milestones/[id]/route.ts b/app/api/milestones/[id]/route.ts index f53085c..f33cf92 100644 --- a/app/api/milestones/[id]/route.ts +++ b/app/api/milestones/[id]/route.ts @@ -5,6 +5,7 @@ import { withAuth } from '@/lib/auth/middleware' import { sql } from '@/lib/db' import { UpdateMilestoneSchema, IMMUTABLE_MILESTONE_STATUS_VALUES } from '@/lib/validations' import { activityService } from '@/lib/activity' +import { ensureBaselineRevision, recordContractRevision } from '@/lib/contracts/revisions' export const GET = withAuth(async (request: NextRequest, auth) => { const id = request.nextUrl.pathname.split('/').at(-1) @@ -83,6 +84,13 @@ export const PATCH = withAuth(async (request: NextRequest, auth) => { ) } + // Capture the pre-update state so the revision history has something to diff against. + if (milestone.contract_id) { + await ensureBaselineRevision(milestone.contract_id).catch((err: unknown) => + console.error('[revisions] Failed to record baseline revision:', err), + ) + } + const [updated] = await sql` UPDATE milestones SET title = COALESCE(${title ?? null}, title), @@ -106,6 +114,15 @@ export const PATCH = withAuth(async (request: NextRequest, auth) => { metadata: { previousTitle: milestone.title }, }).catch((err: unknown) => console.error('[activity] Failed to log milestone_updated:', err)) + if (milestone.contract_id) { + await recordContractRevision(milestone.contract_id, { + id: user.id, + walletAddress: auth.walletAddress, + }).catch((err: unknown) => + console.error('[revisions] Failed to record contract revision:', err), + ) + } + return NextResponse.json({ milestone: updated }) } catch { return NextResponse.json({ error: 'Failed to update milestone', code: 'MILESTONE_UPDATE_FAILED' }, { status: 500 }) diff --git a/app/dashboard/contracts/[id]/page.tsx b/app/dashboard/contracts/[id]/page.tsx index 947c0da..873cde0 100644 --- a/app/dashboard/contracts/[id]/page.tsx +++ b/app/dashboard/contracts/[id]/page.tsx @@ -13,6 +13,7 @@ import { ContractEscrowSummary } from "@/components/dashboard/contract-escrow-su import { EscrowStatusTracker, type EscrowStage } from "@/components/dashboard/escrow-status-tracker"; import { EscrowFundingDialog } from "@/components/dashboard/escrow-funding-dialog"; import { ActivityTimeline } from "@/components/ActivityTimeline"; +import { ContractRevisionHistory } from "@/components/dashboard/contract-revision-history"; interface ProfileInfo { display_name: string | null; @@ -229,6 +230,9 @@ export default function ContractDetailPage() { {/* Contract Activity Timeline */} + + {/* Contract Revision & Change History */} + {/* Escrow Funding Dialog */} diff --git a/components/dashboard/contract-revision-history.tsx b/components/dashboard/contract-revision-history.tsx new file mode 100644 index 0000000..8b4efdf --- /dev/null +++ b/components/dashboard/contract-revision-history.tsx @@ -0,0 +1,344 @@ +'use client' + +import { useEffect, useState } from 'react' +import { + AlertCircle, + ArrowRight, + ChevronDown, + ChevronUp, + History, + Loader2, + RefreshCw, +} from 'lucide-react' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' +import { formatEventTimestamp } from '@/components/ActivityTimeline' + +type ChangeField = 'budget' | 'deadline' | 'scope' | 'status' | 'currency' + +interface FieldChange { + field: ChangeField + from: string | null + to: string | null +} + +interface MilestoneChange { + id: string + title: string + kind: 'added' | 'removed' | 'changed' + changes: FieldChange[] +} + +interface RevisionSnapshot { + contract: { total_amount: string; currency: string; terms: string | null } + milestones: Array<{ + id: string + title: string + description: string | null + amount: string + currency: string + due_date: string | null + status: string + sort_order: number + }> +} + +interface ContractRevision { + id: string + revision_number: number + change_type: 'baseline' | 'update' + created_at: string + author: { + display_name: string | null + username: string | null + wallet_address: string | null + } | null + snapshot: RevisionSnapshot + changes: { + contract: FieldChange[] + milestones: MilestoneChange[] + } | null +} + +interface ContractRevisionHistoryProps { + contractId: string + className?: string +} + +const fieldConfig: Record = { + budget: { label: 'Budget', className: 'border-amber-500/40 bg-amber-500/10 text-amber-600' }, + deadline: { label: 'Deadline', className: 'border-blue-500/40 bg-blue-500/10 text-blue-600' }, + scope: { label: 'Scope', className: 'border-purple-500/40 bg-purple-500/10 text-purple-600' }, + status: { label: 'Status', className: 'border-border bg-muted/40 text-muted-foreground' }, + currency: { label: 'Currency', className: 'border-border bg-muted/40 text-muted-foreground' }, +} + +function getAuthHeaders(): Record { + const token = + typeof window !== 'undefined' ? localStorage.getItem('tc_dev_access_token') : null + return token ? { Authorization: `Bearer ${token}` } : {} +} + +function formatValue(field: ChangeField, value: string | null): string { + if (value === null || value === '') return '—' + if (field === 'budget') { + const amount = Number(value) + return Number.isFinite(amount) ? amount.toLocaleString() : value + } + if (field === 'deadline') { + const date = new Date(value) + return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString() + } + return value +} + +function FieldChangeRow({ change }: { change: FieldChange }) { + const config = fieldConfig[change.field] ?? fieldConfig.status + return ( +
+ + {config.label} + +
+ + {formatValue(change.field, change.from)} + + + {formatValue(change.field, change.to)} +
+
+ ) +} + +export function ContractRevisionHistory({ + contractId, + className, +}: ContractRevisionHistoryProps) { + const [revisions, setRevisions] = useState([]) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + const [expandedId, setExpandedId] = useState(null) + + const load = async () => { + setLoading(true) + setError(null) + try { + const res = await fetch(`/api/contracts/${contractId}/revisions`, { + headers: getAuthHeaders(), + credentials: 'include', + }) + if (!res.ok) { + setError('Failed to load revision history.') + return + } + const data = (await res.json()) as { revisions?: ContractRevision[] } + const list = data.revisions ?? [] + setRevisions(list) + setExpandedId(list.length > 0 ? list[list.length - 1].id : null) + } catch { + setError('Failed to load revision history.') + } finally { + setLoading(false) + } + } + + useEffect(() => { + if (!contractId) return + void load() + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [contractId]) + + // Newest first, like a change log. + const ordered = [...revisions].reverse() + + return ( +
+
+
+

+ + Revision History +

+

+ Read-only record of every change, who made it, and when. +

+
+ +
+ + {loading && revisions.length === 0 ? ( +
+ + Loading revisions… +
+ ) : error ? ( +
+ +

{error}

+ +
+ ) : ordered.length === 0 ? ( +
+ +

+ No revisions yet. Changes to milestones will appear here. +

+
+ ) : ( +
    + {ordered.map((revision) => { + const isOpen = expandedId === revision.id + const author = + revision.author?.display_name || + revision.author?.username || + revision.author?.wallet_address || + 'Unknown' + const changeCount = + (revision.changes?.contract.length ?? 0) + (revision.changes?.milestones.length ?? 0) + + return ( +
  1. + + + {isOpen && ( +
    + {revision.changes && changeCount > 0 && ( +
    +

    Changes in this revision

    + {revision.changes.contract.map((change, index) => ( + + ))} + {revision.changes.milestones.map((milestone) => ( +
    +
    + {milestone.title} + {milestone.kind !== 'changed' && ( + + {milestone.kind === 'added' ? 'Milestone added' : 'Milestone removed'} + + )} +
    +
    + {milestone.changes.map((change, index) => ( + + ))} +
    +
    + ))} +
    + )} + + {revision.changes && changeCount === 0 && ( +

    + No tracked changes between this revision and the previous one. +

    + )} + +
    +

    + Milestones at v{revision.revision_number} +

    + {revision.snapshot.milestones.length === 0 ? ( +

    No milestones in this snapshot.

    + ) : ( +
      + {revision.snapshot.milestones.map((milestone) => ( +
    • + {milestone.title} + + + {formatValue('budget', milestone.amount)} {milestone.currency} + + · + Due {formatValue('deadline', milestone.due_date)} + + {milestone.status} + + +
    • + ))} +
    + )} +
    +
    + )} +
  2. + ) + })} +
+ )} +
+ ) +} + +export default ContractRevisionHistory diff --git a/lib/contracts/revisions.ts b/lib/contracts/revisions.ts new file mode 100644 index 0000000..b8597c3 --- /dev/null +++ b/lib/contracts/revisions.ts @@ -0,0 +1,248 @@ +import { sql } from '@/lib/db' + +export interface MilestoneSnapshot { + id: string + title: string + description: string | null + amount: string + currency: string + due_date: string | null + status: string + sort_order: number +} + +export interface ContractSnapshot { + contract: { + total_amount: string + currency: string + terms: string | null + } + milestones: MilestoneSnapshot[] +} + +export type ChangeField = 'budget' | 'deadline' | 'scope' | 'status' | 'currency' + +export interface FieldChange { + field: ChangeField + from: string | null + to: string | null +} + +export interface MilestoneChange { + id: string + title: string + kind: 'added' | 'removed' | 'changed' + changes: FieldChange[] +} + +export interface RevisionDiff { + contract: FieldChange[] + milestones: MilestoneChange[] +} + +export interface ContractRevision { + id: string + revision_number: number + change_type: 'baseline' | 'update' + created_at: string + author: { + display_name: string | null + username: string | null + wallet_address: string | null + } | null + snapshot: ContractSnapshot + /** Null for the first (baseline) revision, which has nothing before it. */ + changes: RevisionDiff | null +} + +function toIso(value: unknown): string | null { + if (!value) return null + const date = new Date(value as string) + return Number.isNaN(date.getTime()) ? String(value) : date.toISOString() +} + +function sameAmount(a: string | null, b: string | null): boolean { + if (a === null || b === null) return a === b + return Number(a) === Number(b) +} + +function sameText(a: string | null, b: string | null): boolean { + return (a ?? '') === (b ?? '') +} + +export function diffSnapshots( + previous: ContractSnapshot, + current: ContractSnapshot, +): RevisionDiff { + const contract: FieldChange[] = [] + + if (!sameAmount(previous.contract.total_amount, current.contract.total_amount)) { + contract.push({ + field: 'budget', + from: previous.contract.total_amount, + to: current.contract.total_amount, + }) + } + if (!sameText(previous.contract.currency, current.contract.currency)) { + contract.push({ field: 'currency', from: previous.contract.currency, to: current.contract.currency }) + } + if (!sameText(previous.contract.terms, current.contract.terms)) { + contract.push({ field: 'scope', from: previous.contract.terms, to: current.contract.terms }) + } + + const before = new Map(previous.milestones.map((m) => [m.id, m])) + const after = new Map(current.milestones.map((m) => [m.id, m])) + const milestones: MilestoneChange[] = [] + + for (const [id, next] of after) { + const prev = before.get(id) + if (!prev) { + milestones.push({ id, title: next.title, kind: 'added', changes: [] }) + continue + } + + const changes: FieldChange[] = [] + if (!sameAmount(prev.amount, next.amount)) { + changes.push({ field: 'budget', from: prev.amount, to: next.amount }) + } + if ((toIso(prev.due_date) ?? '') !== (toIso(next.due_date) ?? '')) { + changes.push({ field: 'deadline', from: toIso(prev.due_date), to: toIso(next.due_date) }) + } + if (!sameText(prev.title, next.title)) { + changes.push({ field: 'scope', from: prev.title, to: next.title }) + } + if (!sameText(prev.description, next.description)) { + changes.push({ field: 'scope', from: prev.description, to: next.description }) + } + if (prev.status !== next.status) { + changes.push({ field: 'status', from: prev.status, to: next.status }) + } + + if (changes.length > 0) { + milestones.push({ id, title: next.title, kind: 'changed', changes }) + } + } + + for (const [id, prev] of before) { + if (!after.has(id)) { + milestones.push({ id, title: prev.title, kind: 'removed', changes: [] }) + } + } + + return { contract, milestones } +} + +async function loadSnapshot(contractId: string): Promise { + const [contract] = (await sql` + SELECT total_amount, currency, terms + FROM contracts + WHERE id = ${contractId} + LIMIT 1 + `) as Array<{ total_amount: string; currency: string; terms: string | null }> + if (!contract) return null + + const milestones = (await sql` + SELECT id, title, description, amount, currency, due_date, status, sort_order + FROM milestones + WHERE contract_id = ${contractId} + ORDER BY sort_order ASC, due_date ASC + `) as Array<{ + id: string + title: string + description: string | null + amount: string + currency: string + due_date: string | Date | null + status: string + sort_order: number + }> + + return { + contract: { + total_amount: contract.total_amount, + currency: contract.currency, + terms: contract.terms, + }, + milestones: milestones.map((m) => ({ + id: String(m.id), + title: m.title, + description: m.description, + amount: String(m.amount), + currency: m.currency, + due_date: toIso(m.due_date), + status: m.status, + sort_order: m.sort_order, + })), + } +} + +/** + * Guarantees a first revision exists so the update that follows has a + * previous state to diff against. No-op once any revision is recorded. + */ +export async function ensureBaselineRevision(contractId: string): Promise { + const [existing] = (await sql` + SELECT id FROM contract_revisions WHERE contract_id = ${contractId} LIMIT 1 + `) as Array<{ id: string }> + if (existing) return + + const snapshot = await loadSnapshot(contractId) + if (!snapshot) return + + await sql` + INSERT INTO contract_revisions (contract_id, snapshot, change_type) + VALUES (${contractId}, ${JSON.stringify(snapshot)}::jsonb, 'baseline') + ` +} + +export async function recordContractRevision( + contractId: string, + author: { id: string; walletAddress: string }, +): Promise { + const snapshot = await loadSnapshot(contractId) + if (!snapshot) return + + await sql` + INSERT INTO contract_revisions (contract_id, snapshot, change_type, author_id, author_wallet) + VALUES (${contractId}, ${JSON.stringify(snapshot)}::jsonb, 'update', ${author.id}, ${author.walletAddress}) + ` +} + +export async function listContractRevisions(contractId: string): Promise { + const rows = (await sql` + SELECT r.id, r.snapshot, r.change_type, r.author_wallet, r.created_at, + u.display_name, u.username, u.wallet_address + FROM contract_revisions r + LEFT JOIN users u ON u.id = r.author_id + WHERE r.contract_id = ${contractId} + ORDER BY r.created_at ASC, r.id ASC + `) as Array<{ + id: string + snapshot: ContractSnapshot + change_type: 'baseline' | 'update' + author_wallet: string | null + created_at: string | Date + display_name: string | null + username: string | null + wallet_address: string | null + }> + + return rows.map((row, index) => { + const previous = index > 0 ? rows[index - 1].snapshot : null + return { + id: String(row.id), + revision_number: index + 1, + change_type: row.change_type, + created_at: toIso(row.created_at) ?? String(row.created_at), + author: row.display_name || row.username || row.wallet_address || row.author_wallet + ? { + display_name: row.display_name ?? null, + username: row.username ?? null, + wallet_address: row.wallet_address ?? row.author_wallet ?? null, + } + : null, + snapshot: row.snapshot, + changes: previous ? diffSnapshots(previous, row.snapshot) : null, + } + }) +} diff --git a/lib/db/migrations/012_contract_revisions.sql b/lib/db/migrations/012_contract_revisions.sql new file mode 100644 index 0000000..9725530 --- /dev/null +++ b/lib/db/migrations/012_contract_revisions.sql @@ -0,0 +1,69 @@ +-- Migration: Contract revision history +-- Append-only snapshots of a contract and its milestones. Each row is a +-- point-in-time record; diffs are computed at read time between consecutive +-- snapshots so the history stays cheap to write and impossible to rewrite. + +CREATE TABLE IF NOT EXISTS contract_revisions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + contract_id UUID NOT NULL REFERENCES contracts (id) ON DELETE CASCADE, + snapshot JSONB NOT NULL, + change_type VARCHAR(20) NOT NULL DEFAULT 'update' + CHECK (change_type IN ('baseline', 'update')), + author_id UUID REFERENCES users (id) ON DELETE SET NULL, + author_wallet TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_contract_revisions_contract + ON contract_revisions (contract_id, created_at); + +-- Read-only history: existing rows may never be changed or removed. +CREATE OR REPLACE FUNCTION prevent_contract_revision_mutation() +RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'contract_revisions is append-only; % is not allowed', TG_OP; +END; +$$ LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS contract_revisions_immutable ON contract_revisions; +CREATE TRIGGER contract_revisions_immutable + BEFORE UPDATE OR DELETE ON contract_revisions + FOR EACH ROW EXECUTE FUNCTION prevent_contract_revision_mutation(); + +-- Baseline snapshot for contracts that already exist. +INSERT INTO contract_revisions (contract_id, snapshot, change_type, created_at) +SELECT + c.id, + jsonb_build_object( + 'contract', jsonb_build_object( + 'total_amount', c.total_amount, + 'currency', c.currency, + 'terms', c.terms + ), + 'milestones', COALESCE(( + SELECT jsonb_agg( + jsonb_build_object( + 'id', m.id, + 'title', m.title, + 'description', m.description, + 'amount', m.amount, + 'currency', m.currency, + 'due_date', m.due_date, + 'status', m.status, + 'sort_order', m.sort_order + ) + ORDER BY m.sort_order, m.due_date + ) + FROM milestones m + WHERE m.contract_id = c.id + ), '[]'::jsonb) + ), + 'baseline', + c.created_at +FROM contracts c +WHERE NOT EXISTS ( + SELECT 1 FROM contract_revisions r WHERE r.contract_id = c.id +); + +COMMENT ON TABLE contract_revisions IS + 'Append-only contract snapshots; used to render revision and change history';