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>
147 lines
5.6 KiB
TypeScript
147 lines
5.6 KiB
TypeScript
/**
|
|
* Integration tests for the notification dispatcher, against the live database.
|
|
*
|
|
* pnpm services:up && pnpm db:migrate && pnpm db:seed
|
|
*
|
|
* Three properties carry this module, and all three fail silently if broken —
|
|
* which is the whole reason `notification_deliveries` exists:
|
|
*
|
|
* 1. It never throws. Every caller runs it after a committed transaction, so a
|
|
* provider outage must not turn an accepted job into a 500.
|
|
* 2. It honours the preference that governs each kind, and ignores preferences
|
|
* for the transactional ones nobody may unsubscribe from.
|
|
* 3. It picks a channel that can actually reach the person — a phone signup has
|
|
* a synthetic email address, and posting that to a provider is a hard bounce
|
|
* against our sending reputation.
|
|
*
|
|
* No provider is configured under test, so `sendSms`/`sendEmail` take their
|
|
* development path and log instead of calling out. That is the behaviour being
|
|
* asserted: in production the same missing config throws, deliberately.
|
|
*/
|
|
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('@linkder/db');
|
|
const { notify } = await import('../src/index');
|
|
|
|
const RUN = Math.random().toString(36).slice(2, 8);
|
|
|
|
/** Verified phone, no real email — a client who signed up by SMS. */
|
|
let phoneUser: string;
|
|
/** Real email, no phone — a pro who signed up with Google. */
|
|
let emailUser: string;
|
|
/** Neither. Nothing can reach them. */
|
|
let unreachable: string;
|
|
|
|
async function deliveries(userId: string) {
|
|
return db.execute<{ kind: string; channel: string; status: string; detail: string | null }>(sql`
|
|
SELECT kind, channel, status, detail FROM notification_deliveries
|
|
WHERE user_id = ${userId} ORDER BY created_at
|
|
`);
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
// A phone signup: real number, and the synthetic address they were given
|
|
// because they never had a mailbox to give us.
|
|
const phone = `+34999${String(Math.floor(Math.random() * 1e6)).padStart(6, '0')}`;
|
|
const [a] = await db.execute<{ id: string }>(sql`
|
|
INSERT INTO users (name, email, phone, phone_verified, role)
|
|
VALUES ('Notify Phone', ${`${phone}@phone.linkder.local`}, ${phone}, true, 'client')
|
|
RETURNING id
|
|
`);
|
|
phoneUser = a!.id;
|
|
|
|
const [b] = await db.execute<{ id: string }>(sql`
|
|
INSERT INTO users (name, email, role)
|
|
VALUES ('Notify Email', ${`notify-${RUN}@example.com`}, 'pro')
|
|
RETURNING id
|
|
`);
|
|
emailUser = b!.id;
|
|
|
|
const [c] = await db.execute<{ id: string }>(sql`
|
|
INSERT INTO users (name, email, role)
|
|
VALUES ('Notify Nobody', ${`+3400000${RUN}@phone.linkder.local`}, 'client')
|
|
RETURNING id
|
|
`);
|
|
unreachable = c!.id;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await db.execute(sql`DELETE FROM users WHERE id IN (${phoneUser}, ${emailUser}, ${unreachable})`);
|
|
await closePool();
|
|
});
|
|
|
|
describe('notify', () => {
|
|
it('sends over SMS when there is a verified number', async () => {
|
|
const result = await notify(db, phoneUser, {
|
|
kind: 'request.received',
|
|
trade: 'Plumber',
|
|
distanceM: 2400,
|
|
expiresInHours: 12,
|
|
});
|
|
|
|
expect(result).toEqual({ status: 'sent', channel: 'sms' });
|
|
const rows = await deliveries(phoneUser);
|
|
expect(rows.at(-1)).toMatchObject({ kind: 'request.received', channel: 'sms', status: 'sent' });
|
|
});
|
|
|
|
it('falls back to email when there is no phone', async () => {
|
|
const result = await notify(db, emailUser, { kind: 'verification.approved' });
|
|
expect(result).toEqual({ status: 'sent', channel: 'email' });
|
|
});
|
|
|
|
it('skips someone nothing can reach, rather than bouncing a synthetic address', async () => {
|
|
// `+34…@phone.linkder.local` is what a phone signup gets when they never
|
|
// give us an address. Mailing it is a hard bounce against our reputation.
|
|
const result = await notify(db, unreachable, { kind: 'verification.approved' });
|
|
|
|
expect(result.status).toBe('skipped');
|
|
const rows = await deliveries(unreachable);
|
|
expect(rows.at(-1)!.detail).toMatch(/no verified phone/i);
|
|
});
|
|
|
|
it('honours the preference that governs a kind', async () => {
|
|
await db.execute(sql`
|
|
INSERT INTO notification_preferences (user_id, sms_new_request)
|
|
VALUES (${phoneUser}, false)
|
|
ON CONFLICT (user_id) DO UPDATE SET sms_new_request = false
|
|
`);
|
|
|
|
const result = await notify(db, phoneUser, {
|
|
kind: 'request.received',
|
|
trade: 'Plumber',
|
|
distanceM: 900,
|
|
expiresInHours: 12,
|
|
});
|
|
|
|
expect(result.status).toBe('skipped');
|
|
expect((await deliveries(phoneUser)).at(-1)!.detail).toMatch(/turned off/i);
|
|
});
|
|
|
|
it('sends a transactional message even with everything switched off', async () => {
|
|
await db.execute(sql`
|
|
UPDATE notification_preferences
|
|
SET sms_new_request = false, push_requests = false, email_receipts = false,
|
|
sms_marketing = false, email_marketing = false
|
|
WHERE user_id = ${phoneUser}
|
|
`);
|
|
|
|
// Being approved is the outcome of something they did. A pro who muted
|
|
// everything must still be told their account went live, or the product
|
|
// has broken its promise to them.
|
|
const result = await notify(db, phoneUser, { kind: 'verification.approved' });
|
|
expect(result.status).toBe('sent');
|
|
});
|
|
|
|
it('records a failure instead of throwing', async () => {
|
|
// A user id that does not exist stands in for any lookup that comes back
|
|
// empty. The contract is that callers never have to catch.
|
|
const missing = '00000000-0000-0000-0000-000000000000';
|
|
const result = await notify(db, missing, { kind: 'verification.approved' });
|
|
expect(result.status).toBe('skipped');
|
|
});
|
|
});
|