tazakazahstan/test/points.test.ts

106 lines
4.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from "node:assert/strict";
import { after, beforeEach, describe, it } from "node:test";
import { type ContainerItem, pointsForItems, pointsPerUnit } from "../src/points/rates.ts";
import { COFFEE, ledgerSum, petEvent, startTestApp, type TestApp } from "./helpers.ts";
describe("points: ставки начисления", () => {
const outline: Array<[ContainerItem["type"], number, number, number]> = [
["pet", 500, 1, 1],
["pet", 1500, 2, 4],
["aluminum", 330, 3, 6],
["glass", 500, 1, 2],
["glass", 750, 2, 6],
];
for (const [type, volumeMl, count, points] of outline) {
it(`Scenario Outline: Баллы за позицию тары — ${count} × ${type} ${volumeMl} мл = ${points}`, () => {
assert.equal(pointsForItems([{ type, volumeMl, count }]), points);
});
}
it("Scenario: Граница объёма PET", () => {
assert.equal(pointsPerUnit("pet", 500), 1);
assert.equal(pointsPerUnit("pet", 501), 2);
});
});
describe("points: счёт жителя", () => {
let app: TestApp;
let token: string;
beforeEach(async () => {
await app?.close();
app = await startTestApp();
token = await app.login("demo-resident");
});
after(() => app.close());
it("Scenario Outline: начисление через API совпадает со ставками", async () => {
const res = await app.sendEvent(
petEvent("evt-outline", "R-DEMO01", [{ type: "glass", volumeMl: 750, count: 2 }]),
);
assert.equal(res.body.points, 6);
assert.equal(await app.balance(token), 6);
});
it("Scenario: Житель видит баланс и историю", async () => {
await app.sendEvent(petEvent("evt-1001", "R-DEMO01"));
const res = await app.request("GET", "/api/me/points", { token });
assert.equal(res.status, 200);
assert.equal(res.body.balance, 7);
assert.equal(res.body.history.length, 1);
const [entry] = res.body.history;
assert.equal(entry.kind, "earn");
assert.equal(entry.delta, 7);
assert.equal(entry.balanceAfter, 7);
assert.deepEqual(entry.source, { type: "fandomat_event", id: "FM-NURA-001:evt-1001" });
});
it("Scenario: Новый житель без операций", async () => {
const res = await app.request("GET", "/api/me/points", { token });
assert.equal(res.body.balance, 0);
assert.deepEqual(res.body.history, []);
});
it("Scenario: Параллельные списания не уводят баланс в минус", async () => {
await app.grantPoints("R-DEMO01", 25);
const results = await Promise.all(
Array.from({ length: 5 }, (_, i) =>
app.request("POST", `/api/rewards/${COFFEE}/redeem`, {
token,
headers: { "idempotency-key": `par-${i}` },
}),
),
);
const ok = results.filter((r) => r.status === 201);
const rejected = results.filter((r) => r.status === 409);
assert.equal(ok.length, 2);
assert.equal(rejected.length, 3);
for (const r of rejected) assert.equal(r.body.error.code, "insufficient_points");
assert.equal(await app.balance(token), 5);
assert.equal(ledgerSum(app.db, "u-demo-resident"), 5);
});
it("Scenario: Параллельные начисления разных событий", async () => {
await Promise.all(
Array.from({ length: 10 }, (_, i) =>
app.sendEvent(
petEvent(`par-evt-${i}`, "R-DEMO01", [{ type: "aluminum", volumeMl: 330, count: 1 }]),
),
),
);
const res = await app.request("GET", "/api/me/points", { token });
assert.equal(res.body.balance, 20);
assert.equal(res.body.history.filter((e: { kind: string }) => e.kind === "earn").length, 10);
assert.equal(ledgerSum(app.db, "u-demo-resident"), 20);
});
it("баланс не может стать отрицательным даже при прямой записи в БД", () => {
assert.throws(() =>
app.db
.prepare(
"INSERT INTO point_accounts (user_id, balance, updated_at) VALUES ('u-demo-pending', -1, 'x')",
)
.run(),
);
});
});