Registration collected one optional Name, so every greeting had only a whole name to use: "Hi Thom Lamb," rather than "Hi Thom,". Both parts are now captured, and the cart reminder greets by first name. Both are required of anyone new, refused individually rather than as a single "name is required" so a form that filled one and not the other is told which. The columns are nullable even so, and that is deliberate. Marking them NOT NULL would mean backfilling legacy rows with empty strings, which asserts that every customer has a name — untrue of anyone who registered while the field was optional. The table records what is actually the case; the rule that new registrations must supply both lives in the route, where a missing field can produce a message naming it. The backfill splits on the first space, and it is lossy in a way no version of this avoids. "Thom Lamb" becomes Thom and Lamb; "Mary Jane Smith" gets a last name of "Jane Smith"; names that are not two parts fare worse. It was chosen over leaving the columns empty because nothing currently lets a customer correct their own name — PUT /api/customers/me exists but no frontend calls it — so empty would have meant permanently unpersonalised for every existing customer. The migration says so, so nobody later reads backfilled values as data the customer supplied in that shape. Verified against a seeded database rather than reasoned about, because this is the part that cannot be covered by the suite: migrations run in globalSetup before any test, and the old column is gone afterwards. Six representative rows through the real migration gave Thom/Lamb, Mary/"Jane Smith", Cher/null, " Padded Name " trimmed to Padded/Name, and null and whitespace-only names left as null on both. The down migration rejoins the parts and returns all six to their original strings. The old column is dropped rather than kept alongside, so there is one source of truth instead of two that drift. The admin keeps receiving a single composed display name. It only ever shows one — the list cell and the drawer title — and never edits one, so giving it both parts plus the joining logic would be work for no reader. Churn was the bulk of this: 14 backend registrations and 10 end-to-end registration forms. A first attempt at the backend fixtures also added names to login and password-reset payloads, which would still have passed since the server ignores unknown fields, but a login test implying login takes a name is a small lie; that was reverted and redone against register calls only. Verified: 172 unit, 183 integration and 95 end-to-end passing, lint unchanged at 4 backend and 27 frontend warnings. Not covered: the cart reminder itself, which runs from a cron and had no test before this either. The greeting change is a one-line substitution in that query. Refs #106 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
393 lines
15 KiB
TypeScript
393 lines
15 KiB
TypeScript
import request from 'supertest';
|
|
import app from '../../src/app';
|
|
import { pool } from '../../src/db';
|
|
import { resetDb, closeDb } from './setup/testDb';
|
|
|
|
jest.mock('../../src/mailer', () => ({
|
|
sendMail: jest.fn().mockResolvedValue(undefined)
|
|
}));
|
|
import { sendMail } from '../../src/mailer';
|
|
const sentMail = sendMail as jest.MockedFunction<typeof sendMail>;
|
|
|
|
beforeEach(async () => {
|
|
await resetDb();
|
|
sentMail.mockClear();
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await pool.end();
|
|
await closeDb();
|
|
});
|
|
|
|
const PASSWORD = 'supersecret123';
|
|
|
|
async function register(email: string) {
|
|
const agent = request.agent(app);
|
|
expect((await agent.post('/api/customers/register').send({ firstName: 'Test', lastName: 'Customer', email, password: PASSWORD })).status).toBe(200);
|
|
const { rows } = await pool.query(`SELECT id FROM customers WHERE email = $1`, [email]);
|
|
return { agent, id: rows[0].id as number };
|
|
}
|
|
|
|
async function createItem(name: string) {
|
|
const { rows } = await pool.query(
|
|
`INSERT INTO items (name, price_cents, status) VALUES ($1, 1000, 'available') RETURNING id`,
|
|
[name]
|
|
);
|
|
return rows[0].id as number;
|
|
}
|
|
|
|
// Recipients of the "your favorite sold" mail, by address.
|
|
function soldNotificationsTo(): string[] {
|
|
return sentMail.mock.calls
|
|
.filter(call => String(call[1]).includes('has been sold'))
|
|
.map(call => String(call[0]));
|
|
}
|
|
|
|
// Recipients of the "no longer available" mail sent when an item is withdrawn.
|
|
function removalNotificationsTo(): string[] {
|
|
return sentMail.mock.calls
|
|
.filter(call => String(call[1]).includes('no longer available'))
|
|
.map(call => String(call[0]));
|
|
}
|
|
|
|
describe('favoriting items', () => {
|
|
it('records a favorite and lists it back', async () => {
|
|
const itemId = await createItem('Oak table');
|
|
const { agent } = await register('fav@example.com');
|
|
|
|
expect((await agent.post(`/api/customers/me/favorites/${itemId}`)).status).toBe(201);
|
|
|
|
const res = await agent.get('/api/customers/me/favorites');
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.map((f: { item_id: number }) => f.item_id)).toEqual([itemId]);
|
|
});
|
|
|
|
it('is idempotent, so a double click does not error', async () => {
|
|
const itemId = await createItem('Oak table');
|
|
const { agent } = await register('twice@example.com');
|
|
|
|
expect((await agent.post(`/api/customers/me/favorites/${itemId}`)).status).toBe(201);
|
|
expect((await agent.post(`/api/customers/me/favorites/${itemId}`)).status).toBe(201);
|
|
|
|
const { rows } = await pool.query(`SELECT COUNT(*)::int AS n FROM favorites`);
|
|
expect(rows[0].n).toBe(1);
|
|
});
|
|
|
|
it('unfavorites', async () => {
|
|
const itemId = await createItem('Oak table');
|
|
const { agent } = await register('unfav@example.com');
|
|
await agent.post(`/api/customers/me/favorites/${itemId}`);
|
|
|
|
expect((await agent.delete(`/api/customers/me/favorites/${itemId}`)).status).toBe(204);
|
|
expect((await agent.get('/api/customers/me/favorites')).body).toEqual([]);
|
|
});
|
|
|
|
it('requires a signed-in customer', async () => {
|
|
const itemId = await createItem('Oak table');
|
|
expect((await request(app).post(`/api/customers/me/favorites/${itemId}`)).status).toBe(401);
|
|
expect((await request(app).get('/api/customers/me/favorites')).status).toBe(401);
|
|
});
|
|
|
|
it('refuses to favorite an item that does not exist', async () => {
|
|
const { agent } = await register('ghost@example.com');
|
|
expect((await agent.post('/api/customers/me/favorites/999999')).status).toBe(404);
|
|
});
|
|
|
|
it('keeps each customer\'s favorites separate', async () => {
|
|
const itemId = await createItem('Oak table');
|
|
const { agent: mine } = await register('mine@example.com');
|
|
const { agent: theirs } = await register('theirs@example.com');
|
|
|
|
await mine.post(`/api/customers/me/favorites/${itemId}`);
|
|
|
|
expect((await theirs.get('/api/customers/me/favorites')).body).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('favorite alert consent', () => {
|
|
it('is off for a new customer', async () => {
|
|
const { agent } = await register('default@example.com');
|
|
const res = await agent.get('/api/customers/me');
|
|
expect(res.body.favorite_alerts).toBe(false);
|
|
});
|
|
|
|
it('records when it was given and the wording shown', async () => {
|
|
const { agent, id } = await register('optin@example.com');
|
|
|
|
expect((await agent.put('/api/customers/me/favorite-alerts').send({ enabled: true })).status).toBe(200);
|
|
|
|
const { rows } = await pool.query(
|
|
`SELECT favorite_alerts, favorite_alerts_at, favorite_alerts_text FROM customers WHERE id = $1`,
|
|
[id]
|
|
);
|
|
expect(rows[0].favorite_alerts).toBe(true);
|
|
expect(rows[0].favorite_alerts_at).toBeTruthy();
|
|
expect(rows[0].favorite_alerts_text).toMatch(/favorited/i);
|
|
});
|
|
|
|
it('can be turned back off', async () => {
|
|
const { agent, id } = await register('optout@example.com');
|
|
await agent.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
await agent.put('/api/customers/me/favorite-alerts').send({ enabled: false });
|
|
|
|
const { rows } = await pool.query(`SELECT favorite_alerts FROM customers WHERE id = $1`, [id]);
|
|
expect(rows[0].favorite_alerts).toBe(false);
|
|
});
|
|
|
|
it('is independent of the marketing consent', async () => {
|
|
const { agent, id } = await register('separate@example.com');
|
|
await agent.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
|
|
// Opting into item alerts must not quietly sign anyone up for marketing.
|
|
const { rows } = await pool.query(
|
|
`SELECT marketing_consent, favorite_alerts FROM customers WHERE id = $1`,
|
|
[id]
|
|
);
|
|
expect(rows[0].favorite_alerts).toBe(true);
|
|
expect(rows[0].marketing_consent).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('notifying when a favorited item sells', () => {
|
|
async function buyViaDemo(agent: ReturnType<typeof request.agent>, itemId: number) {
|
|
expect((await agent.post(`/api/cart/items/${itemId}`)).status).toBe(201);
|
|
|
|
// Demo checkout needs a shipping address like any other.
|
|
const address = await agent.post('/api/customers/me/addresses').send({
|
|
fullName: 'Test Buyer',
|
|
addressLine1: '1 Test Street',
|
|
city: 'Austin',
|
|
state: 'TX',
|
|
postalCode: '78701'
|
|
});
|
|
expect(address.status).toBeLessThan(400);
|
|
|
|
const purchase = await agent
|
|
.post('/api/checkout/cart/demo/purchase')
|
|
.send({ shippingAddressId: address.body.address.id });
|
|
expect(purchase.status).toBeLessThan(400);
|
|
}
|
|
|
|
it('emails a favoriter who opted in', async () => {
|
|
const itemId = await createItem('Wanted item');
|
|
const { agent: watcher } = await register('watcher@example.com');
|
|
await watcher.post(`/api/customers/me/favorites/${itemId}`);
|
|
await watcher.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
|
|
const { agent: buyer } = await register('buyer@example.com');
|
|
await buyViaDemo(buyer, itemId);
|
|
|
|
expect(soldNotificationsTo()).toEqual(['watcher@example.com']);
|
|
});
|
|
|
|
it('does not email a favoriter who never opted in', async () => {
|
|
const itemId = await createItem('Wanted item');
|
|
const { agent: watcher } = await register('silent@example.com');
|
|
await watcher.post(`/api/customers/me/favorites/${itemId}`);
|
|
|
|
const { agent: buyer } = await register('buyer2@example.com');
|
|
await buyViaDemo(buyer, itemId);
|
|
|
|
expect(soldNotificationsTo()).toEqual([]);
|
|
});
|
|
|
|
it('does not tell the buyer their own purchase is unavailable', async () => {
|
|
const itemId = await createItem('Self bought');
|
|
const { agent: buyer } = await register('selfbuy@example.com');
|
|
await buyer.post(`/api/customers/me/favorites/${itemId}`);
|
|
await buyer.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
|
|
await buyViaDemo(buyer, itemId);
|
|
|
|
expect(soldNotificationsTo()).toEqual([]);
|
|
});
|
|
|
|
it('emails every opted-in favoriter except the buyer', async () => {
|
|
const itemId = await createItem('Popular item');
|
|
for (const email of ['a@example.com', 'b@example.com']) {
|
|
const { agent } = await register(email);
|
|
await agent.post(`/api/customers/me/favorites/${itemId}`);
|
|
await agent.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
}
|
|
|
|
const { agent: buyer } = await register('c@example.com');
|
|
await buyer.post(`/api/customers/me/favorites/${itemId}`);
|
|
await buyer.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
await buyViaDemo(buyer, itemId);
|
|
|
|
expect(soldNotificationsTo().sort()).toEqual(['a@example.com', 'b@example.com']);
|
|
});
|
|
|
|
it('notifies when an admin marks the item sold', async () => {
|
|
const itemId = await createItem('Marked sold');
|
|
const { agent: watcher } = await register('marked@example.com');
|
|
await watcher.post(`/api/customers/me/favorites/${itemId}`);
|
|
await watcher.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
|
|
expect((await request(app).post(`/api/admin/items/${itemId}/mark-sold`)).status).toBe(200);
|
|
|
|
expect(soldNotificationsTo()).toEqual(['marked@example.com']);
|
|
});
|
|
|
|
it('does not notify a disabled customer', async () => {
|
|
const itemId = await createItem('Disabled watcher');
|
|
const { agent: watcher, id } = await register('disabled@example.com');
|
|
await watcher.post(`/api/customers/me/favorites/${itemId}`);
|
|
await watcher.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
await request(app).post(`/api/admin/customers/${id}/disable`).expect(204);
|
|
|
|
await request(app).post(`/api/admin/items/${itemId}/mark-sold`);
|
|
|
|
expect(soldNotificationsTo()).toEqual([]);
|
|
});
|
|
|
|
it('does not notify about an item nobody favorited', async () => {
|
|
const itemId = await createItem('Unloved');
|
|
await request(app).post(`/api/admin/items/${itemId}/mark-sold`);
|
|
expect(soldNotificationsTo()).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('notifying when a favorited item is deleted', () => {
|
|
it('emails opted-in favoriters that it is no longer available', async () => {
|
|
const itemId = await createItem('Withdrawn item');
|
|
const { agent } = await register('withdrawn@example.com');
|
|
await agent.post(`/api/customers/me/favorites/${itemId}`);
|
|
await agent.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
|
|
expect((await request(app).delete(`/api/admin/items/${itemId}`)).status).toBe(204);
|
|
|
|
expect(removalNotificationsTo()).toEqual(['withdrawn@example.com']);
|
|
});
|
|
|
|
it('does not email a favoriter who never opted in', async () => {
|
|
const itemId = await createItem('Withdrawn item');
|
|
const { agent } = await register('quiet@example.com');
|
|
await agent.post(`/api/customers/me/favorites/${itemId}`);
|
|
|
|
await request(app).delete(`/api/admin/items/${itemId}`);
|
|
|
|
expect(removalNotificationsTo()).toEqual([]);
|
|
});
|
|
|
|
it('does not tell them twice when the item had already sold', async () => {
|
|
const itemId = await createItem('Already sold');
|
|
const { agent } = await register('twice-told@example.com');
|
|
await agent.post(`/api/customers/me/favorites/${itemId}`);
|
|
await agent.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
|
|
await request(app).post(`/api/admin/items/${itemId}/mark-sold`);
|
|
expect(soldNotificationsTo()).toEqual(['twice-told@example.com']);
|
|
|
|
// They already know it has gone; deleting the record should not say so again.
|
|
await request(app).delete(`/api/admin/items/${itemId}`);
|
|
expect(removalNotificationsTo()).toEqual([]);
|
|
});
|
|
|
|
it('does not notify a disabled customer', async () => {
|
|
const itemId = await createItem('Withdrawn item');
|
|
const { agent, id } = await register('disabled-del@example.com');
|
|
await agent.post(`/api/customers/me/favorites/${itemId}`);
|
|
await agent.put('/api/customers/me/favorite-alerts').send({ enabled: true });
|
|
await request(app).post(`/api/admin/customers/${id}/disable`).expect(204);
|
|
|
|
await request(app).delete(`/api/admin/items/${itemId}`);
|
|
|
|
expect(removalNotificationsTo()).toEqual([]);
|
|
});
|
|
|
|
it('still deletes the item when nobody favorited it', async () => {
|
|
const itemId = await createItem('Unloved');
|
|
expect((await request(app).delete(`/api/admin/items/${itemId}`)).status).toBe(204);
|
|
|
|
const { rows } = await pool.query(`SELECT COUNT(*)::int AS n FROM items WHERE id = $1`, [itemId]);
|
|
expect(rows[0].n).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe('filtering the storefront by favorites', () => {
|
|
it('returns only the favorited items', async () => {
|
|
const favorited = await createItem('Oak table');
|
|
await createItem('Elm bench');
|
|
const { agent } = await register('filter@example.com');
|
|
await agent.post(`/api/customers/me/favorites/${favorited}`);
|
|
|
|
const res = await agent.get('/api/items?favorites=1');
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.map((item: { name: string }) => item.name)).toEqual(['Oak table']);
|
|
});
|
|
|
|
it('keeps one customer out of another customer\'s favorites', async () => {
|
|
const mine = await createItem('Oak table');
|
|
const theirs = await createItem('Elm bench');
|
|
const { agent: me } = await register('mine@example.com');
|
|
const { agent: them } = await register('theirs@example.com');
|
|
await me.post(`/api/customers/me/favorites/${mine}`);
|
|
await them.post(`/api/customers/me/favorites/${theirs}`);
|
|
|
|
const res = await me.get('/api/items?favorites=1');
|
|
|
|
expect(res.body.map((item: { name: string }) => item.name)).toEqual(['Oak table']);
|
|
});
|
|
|
|
it('still shows a favorite that has sold', async () => {
|
|
const itemId = await createItem('Oak table');
|
|
const { agent } = await register('sold@example.com');
|
|
await agent.post(`/api/customers/me/favorites/${itemId}`);
|
|
await pool.query(`UPDATE items SET status = 'sold' WHERE id = $1`, [itemId]);
|
|
|
|
const res = await agent.get('/api/items?favorites=1');
|
|
|
|
// The storefront shows sold items everywhere else, and a favorite that has
|
|
// just sold is often exactly what the customer came back to look at.
|
|
expect(res.body.map((item: { name: string }) => item.name)).toEqual(['Oak table']);
|
|
});
|
|
|
|
it('combines with the other filters rather than replacing them', async () => {
|
|
const cheap = await createItem('Oak table');
|
|
const dear = await createItem('Elm bench');
|
|
await pool.query(`UPDATE items SET price_cents = 90000 WHERE id = $1`, [dear]);
|
|
const { agent } = await register('combined@example.com');
|
|
await agent.post(`/api/customers/me/favorites/${cheap}`);
|
|
await agent.post(`/api/customers/me/favorites/${dear}`);
|
|
|
|
const res = await agent.get('/api/items?favorites=1&max_price=50000');
|
|
|
|
expect(res.body.map((item: { name: string }) => item.name)).toEqual(['Oak table']);
|
|
});
|
|
|
|
it('answers 401 rather than an empty list when nobody is signed in', async () => {
|
|
await createItem('Oak table');
|
|
|
|
const res = await request(app).get('/api/items?favorites=1');
|
|
|
|
// An empty array would render as "no items match these filters", telling a
|
|
// signed-out visitor they have no favorites instead of that we do not know
|
|
// who they are.
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('rejects a favorites value that is neither on nor off', async () => {
|
|
const { agent } = await register('bogus@example.com');
|
|
|
|
expect((await agent.get('/api/items?favorites=yes')).status).toBe(400);
|
|
});
|
|
|
|
it('leaves the catalogue alone when the flag is off', async () => {
|
|
await createItem('Oak table');
|
|
await createItem('Elm bench');
|
|
const { agent } = await register('off@example.com');
|
|
|
|
const res = await agent.get('/api/items?favorites=0');
|
|
|
|
expect(res.body).toHaveLength(2);
|
|
});
|
|
|
|
it('refuses the favorites filter on the admin inventory', async () => {
|
|
const res = await request(app).get('/api/admin/items?favorites=1');
|
|
|
|
expect(res.status).toBe(400);
|
|
});
|
|
});
|