Skip to content
Open
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
167 changes: 167 additions & 0 deletions __tests__/api/contract-revisions.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof vi.fn>
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')
})
})
100 changes: 100 additions & 0 deletions __tests__/components/contract-revision-history.test.tsx
Original file line number Diff line number Diff line change
@@ -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(<ContractRevisionHistory contractId="c-1" />)

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(<ContractRevisionHistory contractId="c-1" />)

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(<ContractRevisionHistory contractId="c-1" />)
const toggle = await screen.findByText('Revision v2')

fireEvent.click(toggle)
await waitFor(() =>
expect(screen.queryByText('Changes in this revision')).not.toBeInTheDocument(),
)
})
})
117 changes: 117 additions & 0 deletions __tests__/lib/contract-revisions.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): 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> = {}): 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',
})
})
})
Loading
Loading