M2: the full job lifecycle — chat, hiring, geocoding, quotes, bookings, reviews

Closes the funnel. Before this the product could match two people and then
stopped: `quotes`, `bookings` and `reviews` had tables and state machines and
nothing that wrote a row, the entry deck's right swipe was wired to an empty
handler, and every address resolved to the city centre.

Jobs tab and chat
- message router: thread, send, markRead, unreadTotal. A thread is a MATCH, not
  a job — one job with three interested pros is three private conversations.
- Current/Past segments derived from ACTIVE_JOB_STATUSES, job detail listing the
  pros who accepted, and the conversation itself with attachments.

Hiring from the deck
- A right swipe on the entry deck opened nothing. It now resolves "which job?"
  through a sheet — sign in, pick an open job, or post one — and calls the same
  deck.swipe the per-job deck does, so the open-request cap and row lock apply
  exactly once. Swipes are vetoable so closing the sheet returns the card.

Geocoding
- ST_Distance and ST_DWithin rank and filter every deck, and both operands were
  placeholders. Addresses now resolve through Mapbox (permanent=true, which is
  what licenses storing the coordinates), the server resolves points rather than
  trusting client-supplied lat/lng, and every stored point records how it was
  obtained. A `city`-precision base cannot reach the verification queue.

Quote -> booking -> review
- The commercial chain, minus payments. Accepting a quote is the only place a
  booking is created; confirming completion is what unlocks reviews and moves
  the pro's completed_jobs.
- Reviews publish double-blind with no sweeper: each is written with
  published_at already set to its embargo deadline and every read filters
  published_at <= now(), so it publishes itself. The second review pulls both
  forward. A silent counterparty cannot bury a bad review by never replying.

State machine changes, both deliberate
- booked -> matched: a cancelled booking is not a cancelled job.
- scheduled -> awaiting_confirmation: in_progress is optional, so a pro who
  never tapped Start can still say the work is done.

Test suite
- api tests ran files in parallel against one database and failed roughly one
  run in three on whichever file lost the race. Serialised, and three fixtures
  that grabbed "the first client" pinned to the seeded accounts.

Also includes work from a parallel session: admin verification queue, pro
public profile and reviews read path, notification sending, denormalised stats
recompute, search, and observability.

318 tests passing; typecheck and lint clean across 7 packages.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
serfa
2026-08-21 06:29:59 -04:00
co-authored by Claude Opus 5
parent 8f3509d1dd
commit 974e312534
115 changed files with 19994 additions and 569 deletions
+13 -1
View File
@@ -22,8 +22,20 @@ let jobId: string;
let clientId: string;
beforeAll(async () => {
/*
* The fixture job, selected by what makes it the fixture rather than by
* position. It used to be "the oldest job", which held only while it was the
* only job: the seed now backdates hundreds of completed ones to give pros a
* real record, and the oldest row became somebody else's finished electrical
* job — so a deck of plumbers was asserted against a deck of electricians.
*
* It is also the only OPEN job at the centre, and open is the only state a
* deck is ever built for.
*/
const rows = await db.execute<{ id: string; client_id: string }>(
sql`SELECT id, client_id FROM jobs ORDER BY created_at LIMIT 1`,
sql`SELECT id, client_id FROM jobs
WHERE urgency = 'now' AND status = 'open'
ORDER BY created_at LIMIT 1`,
);
const row = rows[0];
if (!row) throw new Error('No seeded job found — run `pnpm db:seed` first');
+146
View File
@@ -0,0 +1,146 @@
/**
* Integration test — runs against a live seeded database.
*
* pnpm services:up && pnpm db:migrate && pnpm db:seed
* pnpm --filter @linkder/db test
*
* Search is a second door onto the same supply as the deck, so the test that
* matters most is the parity one: a pro who can be found here must be a pro who
* could be swiped there. That invariant is why `eligiblePro()` exists.
*/
import { config } from 'dotenv';
import { sql } from 'drizzle-orm';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
config({ path: '../../.env' });
const { closePool, db } = await import('../src/client');
const { searchPros } = await import('../src/queries/search');
const { getShowcaseDeck } = await import('../src/queries/deck');
/** The seed places every pro relative to this point. */
const CENTRE = { lat: 41.3874, lng: 2.1686 };
let plumberId: string;
beforeAll(async () => {
const [plumber] = await db.execute<{ id: string }>(
sql`SELECT id FROM categories WHERE slug = 'plumber' LIMIT 1`,
);
if (!plumber) throw new Error('plumber category missing from seed');
plumberId = plumber.id;
// Seeded skills are empty, so text search has nothing to match until we give
// one pro something to find. Marc Oliveras is 800 m from the centre.
await db.execute(sql`
UPDATE pro_profiles SET skills = ARRAY['Underfloor heating', 'Emergency callouts']
WHERE user_id = (SELECT id FROM users WHERE name = 'Marc Oliveras')
`);
});
afterAll(async () => {
await db.execute(sql`
UPDATE pro_profiles SET skills = '{}'::text[]
WHERE user_id = (SELECT id FROM users WHERE name = 'Marc Oliveras')
`);
await closePool();
});
describe('searchPros', () => {
it('returns eligible pros with no query at all', async () => {
const results = await searchPros(db, { ...CENTRE, limit: 50 });
expect(results.length).toBeGreaterThan(0);
});
it('never returns anyone the shop window would not show', async () => {
// The parity invariant. If these two ever disagree, one surface has become
// the way around the other.
const found = await searchPros(db, { ...CENTRE, limit: 50 });
const showcase = await getShowcaseDeck(db, { ...CENTRE, limit: 100 });
const shownIds = new Set(showcase.map((c) => c.proId));
for (const pro of found) {
expect(shownIds.has(pro.proId)).toBe(true);
}
});
it('excludes the unverified, the away and the too-far', async () => {
const names = (await searchPros(db, { ...CENTRE, limit: 50 })).map((p) => p.name);
expect(names).not.toContain('Unverified Ulla');
expect(names).not.toContain('Away Arnau');
expect(names).not.toContain('Pau Ribas'); // 22 km out, 5 km radius
});
it('matches a skill', async () => {
const names = (await searchPros(db, { ...CENTRE, q: 'underfloor', limit: 50 })).map(
(p) => p.name,
);
expect(names).toContain('Marc Oliveras');
expect(names).not.toContain('Laia Mestre'); // an electrician with no such skill
});
it('matches a trade name', async () => {
const results = await searchPros(db, { ...CENTRE, q: 'electrician', limit: 50 });
expect(results.length).toBeGreaterThan(0);
expect(results.every((p) => p.categories.includes('Electrician'))).toBe(true);
});
it('matches a pro by name', async () => {
const names = (await searchPros(db, { ...CENTRE, q: 'oliveras', limit: 50 })).map((p) => p.name);
expect(names).toEqual(['Marc Oliveras']);
});
it('treats wildcards as literal characters', async () => {
// Without escaping, '%' matches everyone and the filter looks broken.
const results = await searchPros(db, { ...CENTRE, q: '%', limit: 50 });
expect(results).toHaveLength(0);
});
it('narrows to one trade', async () => {
const results = await searchPros(db, { ...CENTRE, categoryId: plumberId, limit: 50 });
expect(results.length).toBeGreaterThan(0);
expect(results.every((p) => p.categories.includes('Plumber'))).toBe(true);
});
it("honours the searcher's own distance limit", async () => {
const near = await searchPros(db, { ...CENTRE, maxDistanceM: 3_000, limit: 50 });
expect(near.every((p) => p.distanceM <= 3_000)).toBe(true);
expect(near.map((p) => p.name)).not.toContain('Marta Vidal'); // 9.1 km out
});
it('sorts by distance, price and rating', async () => {
const nearest = await searchPros(db, { ...CENTRE, sort: 'nearest', limit: 50 });
for (let i = 1; i < nearest.length; i++) {
expect(nearest[i]!.distanceM).toBeGreaterThanOrEqual(nearest[i - 1]!.distanceM);
}
const cheapest = await searchPros(db, { ...CENTRE, sort: 'price', limit: 50 });
for (let i = 1; i < cheapest.length; i++) {
expect(cheapest[i]!.hourlyRateCents).toBeGreaterThanOrEqual(cheapest[i - 1]!.hourlyRateCents);
}
const rated = await searchPros(db, { ...CENTRE, sort: 'rating', limit: 50 });
const scored = rated.filter((p) => p.ratingAvg !== null);
for (let i = 1; i < scored.length; i++) {
expect(scored[i]!.ratingAvg!).toBeLessThanOrEqual(scored[i - 1]!.ratingAvg!);
}
// Unrated pros sort last rather than being read as zero.
const firstUnrated = rated.findIndex((p) => p.ratingAvg === null);
if (firstUnrated !== -1) {
expect(rated.slice(firstUnrated).every((p) => p.ratingAvg === null)).toBe(true);
}
});
it('excludes the unrated from a rating floor', async () => {
const results = await searchPros(db, { ...CENTRE, minRating: 4.5, limit: 50 });
expect(results.every((p) => p.ratingAvg !== null && p.ratingAvg >= 4.5)).toBe(true);
});
it('honours a price ceiling and the limit', async () => {
const cheap = await searchPros(db, { ...CENTRE, maxHourlyRateCents: 3_000, limit: 50 });
expect(cheap.every((p) => p.hourlyRateCents <= 3_000)).toBe(true);
const two = await searchPros(db, { ...CENTRE, limit: 2 });
expect(two).toHaveLength(2);
});
});
+218
View File
@@ -0,0 +1,218 @@
/**
* Integration test — runs against a live seeded database.
*
* pnpm services:up && pnpm db:migrate && pnpm db:seed
*
* `recomputeProStats` is the only thing that ever writes the five denormalised
* ranking counters, and `score()` reads all five. If it drifts from the rows it
* claims to summarise, the deck ranks on fiction and nothing fails — which is
* the situation this function was written to end, so it needs a test that
* checks the arithmetic rather than that it ran.
*/
import { config } from 'dotenv';
import { sql } from 'drizzle-orm';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
config({ path: '../../.env' });
const { closePool, db } = await import('../src/client');
const { recomputeProStats } = await import('../src/queries/stats');
const RUN = Math.random().toString(36).slice(2, 8);
interface Counters {
rating_avg: string | null;
rating_count: number;
completed_jobs: number;
response_rate: string | null;
avg_response_minutes: number | null;
}
/** This file's own pro and client, so a parallel test file never sees them. */
let pro: string;
let client: string;
let categoryId: string;
async function counters(): Promise<Counters> {
const [row] = await db.execute<Counters>(sql`
SELECT rating_avg, rating_count, completed_jobs, response_rate, avg_response_minutes
FROM pro_profiles WHERE user_id = ${pro}
`);
return row!;
}
/**
* One finished, reviewed job.
*
* The whole chain, because that is what the counters read: a review hangs off a
* booking, which hangs off a quote, a match and a request.
*/
async function completedJob(opts: {
rating: number;
published: boolean;
replyMinutes: number;
}): Promise<void> {
const [job] = await db.execute<{ id: string }>(sql`
INSERT INTO jobs (client_id, category_id, title, description, urgency, location, address_text, status)
VALUES (${client}, ${categoryId}, 'Stats probe', 'Probe job for the stats tests.', 'flexible',
ST_SetSRID(ST_MakePoint(0.7, 0.7), 4326)::geography, 'Nowhere', 'completed')
RETURNING id
`);
const [request] = await db.execute<{ id: string }>(sql`
INSERT INTO requests (job_id, pro_id, status, created_at, responded_at, expires_at)
VALUES (${job!.id}, ${pro}, 'accepted',
now() - interval '10 days',
now() - interval '10 days' + ${`${opts.replyMinutes} minutes`}::interval,
now() - interval '8 days')
RETURNING id
`);
const [match] = await db.execute<{ id: string }>(sql`
INSERT INTO matches (request_id, job_id, pro_id, client_id)
VALUES (${request!.id}, ${job!.id}, ${pro}, ${client}) RETURNING id
`);
const [quote] = await db.execute<{ id: string }>(sql`
INSERT INTO quotes (match_id, kind, amount_cents, scope, status, valid_until)
VALUES (${match!.id}, 'fixed', 10000, 'Probe', 'accepted', now() - interval '7 days')
RETURNING id
`);
const [booking] = await db.execute<{ id: string }>(sql`
INSERT INTO bookings (match_id, quote_id, scheduled_start, scheduled_end, status)
VALUES (${match!.id}, ${quote!.id}, now() - interval '6 days',
now() - interval '6 days' + interval '2 hours', 'completed')
RETURNING id
`);
await db.execute(sql`
INSERT INTO reviews (booking_id, author_id, subject_id, rating, body, published_at)
VALUES (${booking!.id}, ${client}, ${pro}, ${opts.rating}, 'Probe review.',
${opts.published ? sql`now() - interval '5 days'` : sql`NULL`})
`);
}
/** A request the pro let run out. Counts against responseRate, nothing else. */
async function ignoredRequest(): Promise<void> {
const [job] = await db.execute<{ id: string }>(sql`
INSERT INTO jobs (client_id, category_id, title, description, urgency, location, address_text, status)
VALUES (${client}, ${categoryId}, 'Stats probe (ignored)', 'Probe job.', 'flexible',
ST_SetSRID(ST_MakePoint(0.7, 0.7), 4326)::geography, 'Nowhere', 'cancelled')
RETURNING id
`);
await db.execute(sql`
INSERT INTO requests (job_id, pro_id, status, created_at, expires_at)
VALUES (${job!.id}, ${pro}, 'expired', now() - interval '10 days', now() - interval '8 days')
`);
}
beforeAll(async () => {
const [cat] = await db.execute<{ id: string }>(
sql`SELECT id FROM categories ORDER BY position LIMIT 1`,
);
categoryId = cat!.id;
const [p] = await db.execute<{ id: string }>(sql`
INSERT INTO users (name, email, role) VALUES ('Stats Probe', ${`stats-pro-${RUN}@example.com`}, 'pro')
RETURNING id
`);
pro = p!.id;
const [c] = await db.execute<{ id: string }>(sql`
INSERT INTO users (name, email, role) VALUES ('Stats Client', ${`stats-client-${RUN}@example.com`}, 'client')
RETURNING id
`);
client = c!.id;
await db.execute(sql`
INSERT INTO pro_profiles (
user_id, headline, bio, hourly_rate_cents, base_location, service_radius_m,
verification_status, verified_at, rating_avg, rating_count, completed_jobs,
response_rate, avg_response_minutes
)
VALUES (
${pro}, 'Stats probe', 'Exists only for the stats tests.', 3000,
ST_SetSRID(ST_MakePoint(0.7, 0.7), 4326)::geography, 15000, 'verified', now(),
-- Deliberate nonsense, so a test that passes proves the recompute WROTE
-- rather than that the seeded value happened to be right.
'1.00', 999, 999, '0.001', 999
)
`);
});
afterAll(async () => {
await db.execute(sql`DELETE FROM users WHERE id IN (${pro}, ${client})`);
await closePool();
});
describe('recomputeProStats', () => {
it('zeroes a pro with no history instead of leaving stale numbers', async () => {
await recomputeProStats(db, pro);
const c = await counters();
expect(c.rating_count).toBe(0);
expect(c.completed_jobs).toBe(0);
// Not 0.0 — an unrated pro has no rating, and "0.0 ★" reads as a bad score
// everywhere it is rendered.
expect(c.rating_avg).toBeNull();
// Likewise: nobody has asked them anything, so there is no rate to report.
expect(c.response_rate).toBeNull();
expect(c.avg_response_minutes).toBeNull();
});
it('averages the published reviews and counts them', async () => {
await completedJob({ rating: 5, published: true, replyMinutes: 10 });
await completedJob({ rating: 4, published: true, replyMinutes: 30 });
await recomputeProStats(db, pro);
const c = await counters();
expect(c.rating_count).toBe(2);
expect(Number(c.rating_avg)).toBeCloseTo(4.5, 2);
expect(c.completed_jobs).toBe(2);
expect(c.avg_response_minutes).toBe(20);
});
it('ignores an embargoed review, so the count matches what pro.reviews lists', async () => {
// Published_at is the moderation gate. A rating counted in the header but
// absent from the list underneath is the exact mismatch the seed used to
// have, and the reason both read the same predicate.
await completedJob({ rating: 1, published: false, replyMinutes: 10 });
await recomputeProStats(db, pro);
const c = await counters();
expect(c.rating_count).toBe(2);
expect(Number(c.rating_avg)).toBeCloseTo(4.5, 2);
// The booking behind it still happened, though — that is not moderated.
expect(c.completed_jobs).toBe(3);
});
it('scores response rate over decided requests, not over sent ones', async () => {
await ignoredRequest();
await recomputeProStats(db, pro);
// Three answered, one expired unanswered.
expect(Number((await counters()).response_rate)).toBeCloseTo(0.75, 3);
});
it('does not count a request that is still inside its window', async () => {
const [job] = await db.execute<{ id: string }>(sql`
INSERT INTO jobs (client_id, category_id, title, description, urgency, location, address_text)
VALUES (${client}, ${categoryId}, 'Stats probe (live)', 'Probe job.', 'flexible',
ST_SetSRID(ST_MakePoint(0.7, 0.7), 4326)::geography, 'Nowhere')
RETURNING id
`);
await db.execute(sql`
INSERT INTO requests (job_id, pro_id, status, created_at, expires_at)
VALUES (${job!.id}, ${pro}, 'pending', now(), now() + interval '12 hours')
`);
await recomputeProStats(db, pro);
// Still 0.75: a request that arrived an hour ago has not been ignored, and
// counting it as a miss would punish a pro for work that just came in.
expect(Number((await counters()).response_rate)).toBeCloseTo(0.75, 3);
});
it('is idempotent — it derives rather than increments', async () => {
await recomputeProStats(db, pro);
const once = await counters();
await recomputeProStats(db, pro);
await recomputeProStats(db, pro);
expect(await counters()).toEqual(once);
});
});