266 lines
11 KiB
TypeScript
266 lines
11 KiB
TypeScript
import assert from "node:assert/strict";
|
||
import { after, beforeEach, describe, it } from "node:test";
|
||
import { COFFEE, ledgerSum, startTestApp, type TestApp } from "./helpers.ts";
|
||
|
||
describe("rewards-partners", () => {
|
||
let app: TestApp;
|
||
let token: string;
|
||
beforeEach(async () => {
|
||
await app?.close();
|
||
app = await startTestApp();
|
||
token = await app.login("demo-resident");
|
||
});
|
||
after(() => app.close());
|
||
|
||
const redeem = (key: string | undefined, rewardId = COFFEE, t = token) =>
|
||
app.request("POST", `/api/rewards/${rewardId}/redeem`, {
|
||
token: t,
|
||
headers: key === undefined ? {} : { "idempotency-key": key },
|
||
});
|
||
|
||
const coffeeIn = (body: { rewards: Array<{ id: string }> }) =>
|
||
body.rewards.find((r) => r.id === COFFEE) as Record<string, unknown>;
|
||
|
||
describe("каталог", () => {
|
||
it("Scenario: Подтверждённый житель видит доступную льготу", async () => {
|
||
await app.grantPoints("R-DEMO01", 12);
|
||
const res = await app.request("GET", "/api/rewards", { token });
|
||
assert.equal(res.status, 200);
|
||
const coffee = coffeeIn(res.body);
|
||
assert.equal(coffee.title, "Кофе в подарок");
|
||
assert.equal(coffee.costPoints, 10);
|
||
assert.equal(coffee.available, true);
|
||
assert.equal(coffee.unavailableReason, undefined);
|
||
});
|
||
|
||
it("Scenario: Неподтверждённый житель видит льготу недоступной", async () => {
|
||
await app.grantPoints("R-PEND01", 50);
|
||
const pending = await app.login("demo-pending");
|
||
const coffee = coffeeIn((await app.request("GET", "/api/rewards", { token: pending })).body);
|
||
assert.equal(coffee.available, false);
|
||
assert.equal(coffee.unavailableReason, "status_not_allowed");
|
||
});
|
||
|
||
it("Scenario: Недостаточно баллов для льготы", async () => {
|
||
await app.grantPoints("R-DEMO01", 3);
|
||
const coffee = coffeeIn((await app.request("GET", "/api/rewards", { token })).body);
|
||
assert.equal(coffee.available, false);
|
||
assert.equal(coffee.unavailableReason, "insufficient_points");
|
||
});
|
||
|
||
it("неактивные льготы не показываются", async () => {
|
||
app.db.prepare("UPDATE rewards SET active = 0").run();
|
||
const res = await app.request("GET", "/api/rewards", { token });
|
||
assert.deepEqual(res.body.rewards, []);
|
||
});
|
||
});
|
||
|
||
describe("обмен", () => {
|
||
it("Scenario: Успешный обмен", async () => {
|
||
await app.grantPoints("R-DEMO01", 12);
|
||
const res = await redeem("k-1");
|
||
assert.equal(res.status, 201);
|
||
assert.match(res.body.redemption.code, /^TZK-[A-Z2-9]{4}-[A-Z2-9]{4}$/);
|
||
assert.equal(res.body.balance, 2);
|
||
assert.equal(res.body.duplicate, false);
|
||
|
||
const points = await app.request("GET", "/api/me/points", { token });
|
||
const [last] = points.body.history;
|
||
assert.equal(last.kind, "redeem");
|
||
assert.equal(last.delta, -10);
|
||
assert.equal(last.balanceAfter, 2);
|
||
|
||
const list = await app.request("GET", "/api/me/redemptions", { token });
|
||
assert.equal(list.body.redemptions.length, 1);
|
||
assert.equal(list.body.redemptions[0].code, res.body.redemption.code);
|
||
assert.equal(list.body.redemptions[0].status, "issued");
|
||
});
|
||
|
||
it("Scenario: Обмен без ключа идемпотентности", async () => {
|
||
await app.grantPoints("R-DEMO01", 12);
|
||
const res = await redeem(undefined);
|
||
assert.equal(res.status, 400);
|
||
assert.equal(res.body.error.code, "idempotency_key_required");
|
||
assert.equal(await app.balance(token), 12);
|
||
});
|
||
|
||
it("неизвестная льгота — 404", async () => {
|
||
const res = await redeem("k-x", "reward-nope");
|
||
assert.equal(res.status, 404);
|
||
assert.equal(res.body.error.code, "reward_not_found");
|
||
});
|
||
|
||
it("Scenario: Недостаточно баллов", async () => {
|
||
await app.grantPoints("R-DEMO01", 3);
|
||
const res = await redeem("k-2");
|
||
assert.equal(res.status, 409);
|
||
assert.equal(res.body.error.code, "insufficient_points");
|
||
assert.equal(res.body.error.balance, 3);
|
||
assert.equal(res.body.error.costPoints, 10);
|
||
const points = await app.request("GET", "/api/me/points", { token });
|
||
assert.equal(points.body.balance, 3);
|
||
assert.equal(points.body.history.length, 1);
|
||
assert.equal(Number(app.db.prepare("SELECT COUNT(*) AS n FROM redemptions").get()?.n), 0);
|
||
});
|
||
|
||
it("после отказа тот же ключ срабатывает, когда баллов стало достаточно", async () => {
|
||
await app.grantPoints("R-DEMO01", 3);
|
||
assert.equal((await redeem("k-retry")).status, 409);
|
||
await app.grantPoints("R-DEMO01", 7);
|
||
assert.equal((await redeem("k-retry")).status, 201);
|
||
assert.equal(await app.balance(token), 0);
|
||
});
|
||
|
||
it("Scenario: Статус жителя не разрешён", async () => {
|
||
await app.grantPoints("R-PEND01", 50);
|
||
const pending = await app.login("demo-pending");
|
||
const res = await redeem("k-3", COFFEE, pending);
|
||
assert.equal(res.status, 403);
|
||
assert.equal(res.body.error.code, "status_not_allowed");
|
||
assert.equal(await app.balance(pending), 50);
|
||
});
|
||
|
||
it("Scenario: Коды льготы закончились", async () => {
|
||
app.db.prepare("UPDATE rewards SET stock = 0 WHERE id = ?").run(COFFEE);
|
||
await app.grantPoints("R-DEMO01", 50);
|
||
const res = await redeem("k-4");
|
||
assert.equal(res.status, 409);
|
||
assert.equal(res.body.error.code, "out_of_stock");
|
||
assert.equal(await app.balance(token), 50);
|
||
});
|
||
|
||
it("остаток кодов уменьшается при обмене и не уходит в минус", async () => {
|
||
app.db.prepare("UPDATE rewards SET stock = 1 WHERE id = ?").run(COFFEE);
|
||
await app.grantPoints("R-DEMO01", 50);
|
||
const results = await Promise.all([redeem("s-1"), redeem("s-2"), redeem("s-3")]);
|
||
assert.equal(results.filter((r) => r.status === 201).length, 1);
|
||
assert.equal(results.filter((r) => r.body.error?.code === "out_of_stock").length, 2);
|
||
assert.equal(app.db.prepare("SELECT stock FROM rewards WHERE id = ?").get(COFFEE)?.stock, 0);
|
||
assert.equal(await app.balance(token), 40);
|
||
});
|
||
});
|
||
|
||
describe("идемпотентность обмена", () => {
|
||
it("Scenario: Повтор обмена с тем же ключом", async () => {
|
||
await app.grantPoints("R-DEMO01", 12);
|
||
const first = await redeem("k-1");
|
||
const second = await redeem("k-1");
|
||
assert.equal(second.status, 200);
|
||
assert.equal(second.body.duplicate, true);
|
||
assert.equal(second.body.redemption.code, first.body.redemption.code);
|
||
const points = await app.request("GET", "/api/me/points", { token });
|
||
assert.equal(points.body.balance, 2);
|
||
assert.equal(
|
||
points.body.history.filter((e: { kind: string }) => e.kind === "redeem").length,
|
||
1,
|
||
);
|
||
});
|
||
|
||
it("тот же ключ для другой льготы — 409 idempotency_conflict", async () => {
|
||
app.db
|
||
.prepare(
|
||
`INSERT INTO rewards (id, partner_id, title, description, cost_points, allowed_statuses, stock, active)
|
||
VALUES ('reward-2', 'partner-demo-cafe', 'Чай', 'Чай', 1, '["verified"]', NULL, 1)`,
|
||
)
|
||
.run();
|
||
await app.grantPoints("R-DEMO01", 12);
|
||
await redeem("k-1");
|
||
const res = await redeem("k-1", "reward-2");
|
||
assert.equal(res.status, 409);
|
||
assert.equal(res.body.error.code, "idempotency_conflict");
|
||
assert.equal(await app.balance(token), 2);
|
||
});
|
||
|
||
it("ключи разных жителей не пересекаются", async () => {
|
||
app.db.prepare("UPDATE users SET status = 'verified' WHERE id = 'u-demo-pending'").run();
|
||
await app.grantPoints("R-DEMO01", 10);
|
||
await app.grantPoints("R-PEND01", 10);
|
||
const other = await app.login("demo-pending");
|
||
assert.equal((await redeem("same-key")).status, 201);
|
||
assert.equal((await redeem("same-key", COFFEE, other)).status, 201);
|
||
});
|
||
|
||
it("Scenario: Параллельные повторы одного обмена", async () => {
|
||
await app.grantPoints("R-DEMO01", 12);
|
||
const results = await Promise.all(Array.from({ length: 5 }, () => redeem("k-9")));
|
||
const codes = new Set(results.map((r) => r.body.redemption.code));
|
||
assert.equal(codes.size, 1);
|
||
assert.equal(results.filter((r) => r.status === 201).length, 1);
|
||
assert.equal(await app.balance(token), 2);
|
||
assert.equal(ledgerSum(app.db, "u-demo-resident"), 2);
|
||
});
|
||
});
|
||
|
||
describe("погашение партнёром", () => {
|
||
const issueCode = async () => {
|
||
await app.grantPoints("R-DEMO01", 10);
|
||
return (await redeem(`issue-${Math.random()}`)).body.redemption.code as string;
|
||
};
|
||
|
||
it("Scenario: Партнёр погашает выданный код", async () => {
|
||
const code = await issueCode();
|
||
const partner = await app.login("demo-partner");
|
||
const res = await app.request("POST", "/api/partner/redemptions/redeem-code", {
|
||
token: partner,
|
||
body: { code },
|
||
});
|
||
assert.equal(res.status, 200);
|
||
assert.equal(res.body.redemption.status, "used");
|
||
const list = await app.request("GET", "/api/me/redemptions", { token });
|
||
assert.equal(list.body.redemptions[0].status, "used");
|
||
});
|
||
|
||
it("код принимается без учёта регистра и пробелов", async () => {
|
||
const code = await issueCode();
|
||
const partner = await app.login("demo-partner");
|
||
const res = await app.request("POST", "/api/partner/redemptions/redeem-code", {
|
||
token: partner,
|
||
body: { code: ` ${code.toLowerCase()} ` },
|
||
});
|
||
assert.equal(res.status, 200);
|
||
});
|
||
|
||
it("Scenario: Повторное погашение кода", async () => {
|
||
const code = await issueCode();
|
||
const partner = await app.login("demo-partner");
|
||
const send = () =>
|
||
app.request("POST", "/api/partner/redemptions/redeem-code", {
|
||
token: partner,
|
||
body: { code },
|
||
});
|
||
await send();
|
||
const res = await send();
|
||
assert.equal(res.status, 409);
|
||
assert.equal(res.body.error.code, "code_already_used");
|
||
});
|
||
|
||
it("Scenario: Неизвестный код", async () => {
|
||
const partner = await app.login("demo-partner");
|
||
const res = await app.request("POST", "/api/partner/redemptions/redeem-code", {
|
||
token: partner,
|
||
body: { code: "TZK-0000-0000" },
|
||
});
|
||
assert.equal(res.status, 404);
|
||
assert.equal(res.body.error.code, "code_not_found");
|
||
});
|
||
|
||
it("код чужого партнёра — 404 code_not_found", async () => {
|
||
const code = await issueCode();
|
||
app.db.prepare("INSERT INTO partners (id, name) VALUES ('partner-other', 'Другой')").run();
|
||
app.db
|
||
.prepare(
|
||
`INSERT INTO users (id, login, role, status, display_name, partner_id, created_at)
|
||
VALUES ('u-other', 'other-partner', 'partner', 'verified', 'X', 'partner-other', 'x')`,
|
||
)
|
||
.run();
|
||
const other = await app.login("other-partner");
|
||
const res = await app.request("POST", "/api/partner/redemptions/redeem-code", {
|
||
token: other,
|
||
body: { code },
|
||
});
|
||
assert.equal(res.status, 404);
|
||
assert.equal(res.body.error.code, "code_not_found");
|
||
});
|
||
});
|
||
});
|