@mccaskie-labs/workbench-fundraising 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @mccaskie-labs/workbench-fundraising
2
+
3
+ ## 0.1.0
4
+
5
+ - First version (`docs/capabilities/31-fundraising.md`, block B12; the law in `docs/raffles.md`): `createFundraising` over the app's own database with `fundraisingMigration`. Campaigns with a goal, dates, a story and a picture; gifts of an amount the giver chooses, once or monthly, paid through workbench-payments (`startGift` gives the `source` for `payChosen` or `subscribe({ gift: true })`, `handlePayment` records each confirmed payment once); cash the owner adds; a total that counts confirmed payments only, less refunds; names on the supporters' list only when the giver ticks the box. Raffles: `checkRaffle` refuses what the place's law plainly doesn't allow (a missing permit for the size of the raffle, cash prizes in Victoria, prizes worth too little against the tickets, sales too long, banned prizes, under-18 buyers where they're barred) and warns about the rest, for every Australian state and territory and the Philippines (where a PCSO authority and a DSWD permit are always needed); tickets held, paid and numbered under one lock; a random draw recorded with its seed so `verifyDraw` gives the same winners again; results by ticket number, never name; redraws of unclaimed prizes after the place's holding period; cancelling answers the payments to refund. The thank-you says a gift is tax-deductible only for a deductible gift recipient with its ABN. Pages in `./ui` (`wb-fund-*`, `FUND_STYLES`, words in English, Tagalog and Taglish, money to 2 decimal places), and `npx workbench-fundraising init|generate|migration`.
package/README.md CHANGED
@@ -1,3 +1,64 @@
1
- # Temporary Holding Version
1
+ # @mccaskie-labs/workbench-fundraising
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Fundraising for apps built on Workbench, a private platform: appeals with a goal, gifts of an amount the giver chooses (once or monthly, through `@mccaskie-labs/workbench-payments`), cash the owner counts in, and raffles checked against the raffle law of the Australian state or territory, or the Philippines, they run in. Spec: `docs/capabilities/31-fundraising.md`; the law: `docs/raffles.md`. Published publicly so Workbench projects can install it with no token; it is not supported for other uses.
4
+
5
+ ```sh
6
+ npm install @mccaskie-labs/workbench-fundraising
7
+ ```
8
+
9
+ ## Set up
10
+
11
+ 1. `npx workbench-fundraising init` writes `workbench/fundraising.json` with the Australian starter (`STARTER_FUNDRAISING`); the client questions in `capabilities/fundraising.json` then fill it:
12
+
13
+ ```json
14
+ {
15
+ "format": 1,
16
+ "country": "AU",
17
+ "currency": "AUD",
18
+ "time_zone": "Australia/Sydney",
19
+ "organisation": { "name": "St Mary's P&F", "abn": "12345678901", "dgr": true },
20
+ "gifts": { "amounts": [20, 50, 100], "min": 5, "max": 5000, "monthly": true, "show_names": "ask" },
21
+ "raffles": { "place": "AU-NSW", "adults_only": true, "max_per_order": 50, "hold_minutes": 30 }
22
+ }
23
+ ```
24
+
25
+ Leave out a part you don't want. Set `dgr` only if the ATO endorses the organisation as a deductible gift recipient. Keep `gifts.min` and `gifts.max` inside `workbench/payments.json` `chosen`, and switch on payments' `repeating` for monthly gifts.
26
+
27
+ 2. `npx workbench-fundraising generate` checks it, prints what givers and buyers will be told and what the raffle law asks, and writes `src/fundraising.generated.ts` (`FUNDRAISING`). Checks can run `npx workbench-fundraising generate --check`.
28
+ 3. `npx workbench-fundraising migration` writes `fundraisingMigration` and its down file into `supabase/migrations` and `supabase/rollback`. It is a tool's own migration (new tables and functions only), so Control applies it on staging without asking.
29
+
30
+ ## Use
31
+
32
+ ```ts
33
+ import { createFundraising } from '@mccaskie-labs/workbench-fundraising'
34
+ import { readGiveForm, renderCampaign, renderGiveForm, renderThanks } from '@mccaskie-labs/workbench-fundraising/ui'
35
+ import { FUNDRAISING } from './fundraising.generated'
36
+
37
+ const fundraising = createFundraising({ db: serviceClient, config: FUNDRAISING })
38
+
39
+ // A gift: the giver's choice, then payments' page.
40
+ const g = await fundraising.startGift(campaign.id, { amountCents: 5000, monthly: false, showName: true, name: 'The Nguyens' })
41
+ if (g.ok) await payments.payChosen({ account, label: g.label, amountCents: 5000, billTo, source: g.source, successUrl, cancelUrl })
42
+ // monthly: payments.subscribe({ ..., unitCents, interval: 'month', gift: true, source: g.source })
43
+
44
+ // Every payments webhook outcome:
45
+ const done = await fundraising.handlePayment(await payments.handleWebhook(request))
46
+ // { kind: 'gift', gift, first } · { kind: 'tickets', order } · { kind: 'refund_tickets', payment_ref, ... } · { kind: 'tickets_released' } · { kind: 'gift_ended' }
47
+
48
+ // A raffle: saved as a draft, checked against the law, opened only when it passes.
49
+ const { raffle, check } = await fundraising.saveRaffle(input, admin.email) // show renderRaffleCheck(check)
50
+ await fundraising.openRaffle(raffle.id, admin.email) // throws not_allowed while check.ok is false
51
+ const held = await fundraising.holdTickets(raffle.id, { orderRef, count: 3, buyer: { name, email }, adult: true })
52
+ // payments.createInvoice(... lines: [held.line], source: held.source ...), then pay
53
+ const { results, record } = await fundraising.draw(raffle.id, { by: admin.email, witnesses: ['P&F president'] })
54
+ ```
55
+
56
+ - The total (`totals`) counts confirmed payments, cash the owner adds and paid raffle tickets, less refunds. A payment counts once, however often its webhook comes.
57
+ - `checkRaffle` refuses a raffle that needs a permit nobody has entered (NSW over A$30,000 of prizes, Victoria over A$23,060, Queensland over A$50,000 of ticket sales, and so on; always PCSO and DSWD in the Philippines), a prize the place bans, prizes worth too little or too much against the tickets, sales or a draw outside the dates allowed, and under-18 buyers where they're barred. Everything else is a warning, starting with "not legal advice" and the regulator's page.
58
+ - Tickets are held, paid and numbered under one lock: the last ticket can't go twice, and paid tickets are numbered 1, 2, 3 … in payment order. A hold lapses after `hold_minutes`.
59
+ - The draw is random (a seed from `crypto.getRandomValues`) and recorded: `verifyDraw(record)` gives the same winners again. Refunded tickets are left out; first prize is drawn first and no ticket wins twice. Results show ticket numbers, never names; `winnersToTell` is for telling winners privately. `redraw` an unclaimed prize after the place's holding period. `cancelRaffle` answers the payments to refund.
60
+ - Call `tick()` and `cleanup()` from the app's cron.
61
+
62
+ ## Look
63
+
64
+ Every element `./ui` draws has a `wb-fund-*` class with a default rule in `FUND_STYLES` (`./styles`); `npx workbench-ui styles` puts them in the project's `public/styles/workbench.css`, and the project restyles them in `project.css`. The words are in `FUND_WORDS` (English, Tagalog, Taglish) under `ui.wbfund.*`.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import type { FundraisingConfig } from "./types.ts";
3
+ export declare const FUNDRAISING_FILE = "workbench/fundraising.json";
4
+ export declare const FUNDRAISING_MODULE = "src/fundraising.generated.ts";
5
+ /** What the settings mean, in lines for the owner. */
6
+ export declare function summaryLines(c: FundraisingConfig): string[];
7
+ /** The generated module for a checked config. */
8
+ export declare function moduleText(c: FundraisingConfig): string;
9
+ /** Reads and checks the project's fundraising.json. Throws naming every problem. */
10
+ export declare function readFundraising(dir: string): FundraisingConfig;
11
+ /** Runs one command; returns the exit code. */
12
+ export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void): number;
package/dist/cli.js ADDED
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env node
2
+ // `npx workbench-fundraising init [dir]`, run in a project's folder, writes
3
+ // workbench/fundraising.json with the Australian starter
4
+ // (STARTER_FUNDRAISING) unless the file is already there.
5
+ //
6
+ // `npx workbench-fundraising generate [--check] [dir]` reads
7
+ // workbench/fundraising.json, checks it, prints what givers and ticket
8
+ // buyers will be told and what the raffle law asks of the owner, and writes
9
+ // src/fundraising.generated.ts: FUNDRAISING for createFundraising. --check
10
+ // writes nothing and fails when the file is out of date or wrong.
11
+ //
12
+ // `npx workbench-fundraising migration [dir]` writes fundraisingMigration
13
+ // into supabase/migrations/<timestamp>_workbench_fundraising.sql with its
14
+ // down file in supabase/rollback/, unless a fundraising migration is already
15
+ // there.
16
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
17
+ import { dirname, join, resolve } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import { fundraisingProblems, fundraisingWarnings } from "./config.js";
20
+ import { raffleLaw } from "./law.js";
21
+ import { fundraisingMigration } from "./migration.js";
22
+ import { formatMoney, toCents } from "./money.js";
23
+ import { STARTER_FUNDRAISING } from "./starters.js";
24
+ const USAGE = "usage: workbench-fundraising init [dir]\n workbench-fundraising generate [--check] [dir]\n workbench-fundraising migration [dir]";
25
+ export const FUNDRAISING_FILE = "workbench/fundraising.json";
26
+ export const FUNDRAISING_MODULE = "src/fundraising.generated.ts";
27
+ const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
28
+ /** What the settings mean, in lines for the owner. */
29
+ export function summaryLines(c) {
30
+ const money = (n) => formatMoney(toCents(n), c.currency, c.country);
31
+ const lines = [`Fundraising for ${c.organisation.name}.`];
32
+ if (c.gifts) {
33
+ const g = c.gifts;
34
+ lines.push(`Gifts: ${g.amounts.map(money).join(", ")}, or any amount from ${money(g.min)} to ${money(g.max)}${g.monthly ? ", once or every month" : ", once"}.`);
35
+ lines.push(` ${g.show_names === "ask" ? "A giver's name shows on the supporters' list only if they tick the box." : "No names are ever shown."} Only confirmed payments count towards the total.`);
36
+ lines.push(` ${c.organisation.dgr ? `Thank-yous say gifts of ${formatMoney(200, c.currency, c.country)} or more are tax deductible (ABN ${c.organisation.abn}).` : "Thank-yous don't mention tax: set organisation \"dgr\" only if the ATO endorses you as a deductible gift recipient."}`);
37
+ }
38
+ if (c.raffles) {
39
+ const law = raffleLaw(c.raffles.place);
40
+ const first = law.bands[0];
41
+ lines.push(`Raffles in ${law.name}, under the ${law.law} (${law.regulator}).`);
42
+ if (law.always.length)
43
+ lines.push(` Every raffle needs: ${law.always.map((p) => p.name).join("; ")}.`);
44
+ else if (first.up_to_cents !== null) {
45
+ lines.push(` No permit needed up to ${formatMoney(first.up_to_cents, "AUD", "AU")} of ${law.measure === "prizes" ? "prizes" : "ticket sales"}; above that: ${law.bands.filter((b) => b.permit).map((b) => b.permit.name).join(", then ")}.`);
46
+ }
47
+ lines.push(` ${c.raffles.adults_only === false && !law.adults_only ? "Anyone may buy tickets." : "Buyers confirm they are 18 or over."} Each raffle is checked against this law when it's saved and again before it opens.`);
48
+ lines.push(` This is a summary, not legal advice: read ${law.url} before you sell tickets.`);
49
+ }
50
+ for (const w of fundraisingWarnings(c))
51
+ lines.push(`WARNING: ${w}`);
52
+ return lines;
53
+ }
54
+ /** The generated module for a checked config. */
55
+ export function moduleText(c) {
56
+ return [
57
+ `// Generated by \`npx workbench-fundraising generate\` from ${FUNDRAISING_FILE}. Don't edit: change the`,
58
+ "// JSON and generate again (Checks runs `npx workbench-fundraising generate --check`).",
59
+ "",
60
+ 'import type { FundraisingConfig } from "@mccaskie-labs/workbench-fundraising";',
61
+ "",
62
+ `export const FUNDRAISING = ${JSON.stringify(c, null, 2)} as const satisfies FundraisingConfig;`,
63
+ "",
64
+ ].join("\n");
65
+ }
66
+ /** Reads and checks the project's fundraising.json. Throws naming every problem. */
67
+ export function readFundraising(dir) {
68
+ const path = join(dir, FUNDRAISING_FILE);
69
+ if (!existsSync(path))
70
+ throw new Error(`${FUNDRAISING_FILE} is missing: answer the fundraising questions first (capabilities/fundraising.json, offer)`);
71
+ let parsed;
72
+ try {
73
+ parsed = JSON.parse(read(path));
74
+ }
75
+ catch (e) {
76
+ throw new Error(`${FUNDRAISING_FILE}: not valid JSON (${e.message})`);
77
+ }
78
+ const problems = fundraisingProblems(parsed, FUNDRAISING_FILE);
79
+ if (problems.length)
80
+ throw new Error(problems.join("\n"));
81
+ const { $schema: _, ...rest } = parsed;
82
+ return rest;
83
+ }
84
+ function migrationStamp(at) {
85
+ return at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
86
+ }
87
+ /** Runs one command; returns the exit code. */
88
+ export function run(argv, log = console.log, err = console.error) {
89
+ const [command, ...rest] = argv;
90
+ const check = rest.includes("--check");
91
+ const bad = rest.find((a) => a.startsWith("--") && a !== "--check");
92
+ if (bad || !["init", "generate", "migration"].includes(command ?? "") || (command !== "generate" && check)) {
93
+ err(bad ? `${bad} isn't an option\n${USAGE}` : USAGE);
94
+ return 2;
95
+ }
96
+ const dir = resolve(rest.find((a) => !a.startsWith("--")) ?? ".");
97
+ try {
98
+ if (command === "init") {
99
+ const at = join(dir, FUNDRAISING_FILE);
100
+ if (existsSync(at)) {
101
+ log(`${FUNDRAISING_FILE} is already there; left as it is`);
102
+ return 0;
103
+ }
104
+ mkdirSync(dirname(at), { recursive: true });
105
+ writeFileSync(at, `${JSON.stringify(STARTER_FUNDRAISING, null, 2)}\n`);
106
+ log(`wrote ${FUNDRAISING_FILE}`);
107
+ log("Now set country, currency and time_zone from workbench/country.json, the organisation's name, answer the fundraising questions, and run `npx workbench-fundraising generate`.");
108
+ return 0;
109
+ }
110
+ if (command === "migration") {
111
+ const folder = join(dir, "supabase/migrations");
112
+ if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_fundraising.sql"))) {
113
+ log("supabase/migrations already has the fundraising migration; nothing written");
114
+ return 0;
115
+ }
116
+ const name = `${migrationStamp(new Date())}_workbench_fundraising.sql`;
117
+ mkdirSync(folder, { recursive: true });
118
+ mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
119
+ writeFileSync(join(folder, name), `-- workbench-fundraising: campaigns, gifts and raffles (docs/capabilities/31-fundraising.md)\n${fundraisingMigration.up}`);
120
+ writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${fundraisingMigration.down}`);
121
+ log(`wrote supabase/migrations/${name} and its down file`);
122
+ return 0;
123
+ }
124
+ const c = readFundraising(dir);
125
+ for (const line of summaryLines(c))
126
+ log(line);
127
+ const out = join(dir, FUNDRAISING_MODULE);
128
+ const text = moduleText(c);
129
+ const current = existsSync(out) ? read(out) : null;
130
+ if (check) {
131
+ if (current !== text) {
132
+ err(`${FUNDRAISING_MODULE} is out of date: run \`npx workbench-fundraising generate\` and commit it`);
133
+ return 1;
134
+ }
135
+ log(`${FUNDRAISING_MODULE} is current`);
136
+ return 0;
137
+ }
138
+ if (current !== text) {
139
+ mkdirSync(dirname(out), { recursive: true });
140
+ writeFileSync(out, text);
141
+ log(`wrote ${FUNDRAISING_MODULE}`);
142
+ }
143
+ else
144
+ log(`${FUNDRAISING_MODULE} is current`);
145
+ return 0;
146
+ }
147
+ catch (e) {
148
+ err(e.message);
149
+ return 1;
150
+ }
151
+ }
152
+ const isMain = (() => {
153
+ try {
154
+ return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
155
+ }
156
+ catch {
157
+ return false;
158
+ }
159
+ })();
160
+ if (isMain)
161
+ process.exitCode = run(process.argv.slice(2));
@@ -0,0 +1,7 @@
1
+ import type { FundraisingConfig } from "./types.ts";
2
+ /** Every problem with the file, or none. */
3
+ export declare function fundraisingProblems(input: unknown, where?: string): string[];
4
+ /** Warnings that don't stop the file. */
5
+ export declare function fundraisingWarnings(c: FundraisingConfig): string[];
6
+ /** The config, checked; throws naming every problem. */
7
+ export declare function checkFundraising<C extends FundraisingConfig>(c: C): C;
package/dist/config.js ADDED
@@ -0,0 +1,137 @@
1
+ // Checks workbench/fundraising.json. The generator runs these before it
2
+ // writes src/fundraising.generated.ts, and createFundraising runs them again
3
+ // at startup. Each raffle is checked against its place's law on its own
4
+ // (checkRaffle, law.ts), since prizes and dates belong to the raffle.
5
+ import { FundraisingError } from "./errors.js";
6
+ import { PLACES, raffleLaw } from "./law.js";
7
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8
+ /** Currencies with no minor unit (the same list workbench-payments refuses): amounts in them aren't cents. */
9
+ const ZERO_DECIMAL = ["BIF", "CLP", "DJF", "GNF", "JPY", "KMF", "KRW", "MGA", "PYG", "RWF", "UGX", "VND", "VUV", "XAF", "XOF", "XPF", "ISK", "HUF", "TWD"];
10
+ const isMoney = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 && Math.abs(Math.round(v * 100) - v * 100) < 1e-6;
11
+ const isWhole = (v, min, max) => typeof v === "number" && Number.isInteger(v) && v >= min && v <= max;
12
+ function validTimeZone(tz) {
13
+ try {
14
+ new Intl.DateTimeFormat("en", { timeZone: tz });
15
+ return true;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
21
+ /** Every problem with the file, or none. */
22
+ export function fundraisingProblems(input, where = "workbench/fundraising.json") {
23
+ const p = [];
24
+ if (!isObject(input))
25
+ return [`${where}: not a JSON object`];
26
+ const c = input;
27
+ if (c.format !== 1)
28
+ p.push(`${where}: "format" must be 1`);
29
+ if (typeof c.country !== "string" || !/^[A-Z]{2}$/.test(c.country))
30
+ p.push(`${where}: "country" must be a two-letter code in capitals, such as "AU"`);
31
+ if (typeof c.currency !== "string" || !/^[A-Z]{3}$/.test(c.currency))
32
+ p.push(`${where}: "currency" must be a three-letter code in capitals, such as "AUD"`);
33
+ else if (ZERO_DECIMAL.includes(c.currency))
34
+ p.push(`${where}: ${c.currency} has no cents; only currencies with two decimals (AUD, PHP, USD, GBP …) are supported`);
35
+ if (typeof c.time_zone !== "string" || !validTimeZone(c.time_zone))
36
+ p.push(`${where}: "time_zone" must be a time zone name, such as "Australia/Sydney"`);
37
+ if (c.gifts === undefined && c.raffles === undefined)
38
+ p.push(`${where}: switch on at least one of "gifts" and "raffles"`);
39
+ for (const k of Object.keys(c)) {
40
+ if (!["$schema", "format", "country", "currency", "time_zone", "organisation", "gifts", "raffles", "retention_months"].includes(k))
41
+ p.push(`${where}: unknown setting "${k}"`);
42
+ }
43
+ const o = c.organisation;
44
+ if (!isObject(o))
45
+ p.push(`${where}: "organisation" must be { "name", "abn"?, "dgr"?, "solicitation_permit"? }`);
46
+ else {
47
+ if (typeof o.name !== "string" || !o.name.trim() || o.name.length > 120)
48
+ p.push(`${where}: organisation "name" is needed, 1 to 120 characters`);
49
+ if (o.abn !== undefined && (typeof o.abn !== "string" || !/^\d{11}$/.test(o.abn.replace(/\s/g, ""))))
50
+ p.push(`${where}: organisation "abn" must be 11 digits`);
51
+ if (o.dgr !== undefined && typeof o.dgr !== "boolean")
52
+ p.push(`${where}: organisation "dgr" must be true or false`);
53
+ if (o.dgr === true && c.country !== "AU")
54
+ p.push(`${where}: organisation "dgr" is Australian (an ATO deductible gift recipient); leave it out in ${String(c.country)}`);
55
+ if (o.dgr === true && o.abn === undefined)
56
+ p.push(`${where}: a deductible gift recipient's receipts need its ABN: add organisation "abn"`);
57
+ if (o.solicitation_permit !== undefined && (typeof o.solicitation_permit !== "string" || !o.solicitation_permit.trim()))
58
+ p.push(`${where}: organisation "solicitation_permit" must be the permit's number`);
59
+ for (const k of Object.keys(o))
60
+ if (!["name", "abn", "dgr", "solicitation_permit"].includes(k))
61
+ p.push(`${where}: unknown organisation setting "${k}"`);
62
+ }
63
+ if (c.gifts !== undefined) {
64
+ const g = c.gifts;
65
+ if (!isObject(g))
66
+ p.push(`${where}: "gifts" must be an object`);
67
+ else {
68
+ const amounts = Array.isArray(g.amounts) ? g.amounts : [];
69
+ if (!Array.isArray(g.amounts) || amounts.length < 1 || amounts.length > 6)
70
+ p.push(`${where}: gifts "amounts" must be 1 to 6 amounts, such as [20, 50, 100]`);
71
+ for (const a of amounts)
72
+ if (!isMoney(a))
73
+ p.push(`${where}: gift amount ${JSON.stringify(a)} must be more than 0, with at most 2 decimal places`);
74
+ if (!isMoney(g.min) || !isMoney(g.max) || g.max < g.min)
75
+ p.push(`${where}: gifts "min" and "max" must be amounts with 0 < min <= max`);
76
+ else
77
+ for (const a of amounts)
78
+ if (isMoney(a) && (a < g.min || a > g.max))
79
+ p.push(`${where}: gift amount ${a} must be between "min" and "max"`);
80
+ if (typeof g.monthly !== "boolean")
81
+ p.push(`${where}: gifts "monthly" must be true or false`);
82
+ if (g.show_names !== "ask" && g.show_names !== "never")
83
+ p.push(`${where}: gifts "show_names" must be "ask" or "never"`);
84
+ for (const k of Object.keys(g))
85
+ if (!["amounts", "min", "max", "monthly", "show_names"].includes(k))
86
+ p.push(`${where}: unknown gifts setting "${k}"`);
87
+ }
88
+ }
89
+ if (c.raffles !== undefined) {
90
+ const r = c.raffles;
91
+ if (!isObject(r))
92
+ p.push(`${where}: "raffles" must be an object`);
93
+ else {
94
+ if (typeof r.place !== "string" || !PLACES.includes(r.place))
95
+ p.push(`${where}: raffles "place" must be one of ${PLACES.join(", ")}`);
96
+ else {
97
+ const country = r.place === "PH" ? "PH" : "AU";
98
+ if (typeof c.country === "string" && c.country !== country)
99
+ p.push(`${where}: raffles "place" ${r.place} isn't in ${c.country}`);
100
+ const law = raffleLaw(r.place);
101
+ if (law.adults_only && r.adults_only === false)
102
+ p.push(`${where}: raffles "adults_only" can't be false in ${law.name}: buyers must be 18 or over`);
103
+ }
104
+ if (r.adults_only !== undefined && typeof r.adults_only !== "boolean")
105
+ p.push(`${where}: raffles "adults_only" must be true or false`);
106
+ if (r.max_per_order !== undefined && !isWhole(r.max_per_order, 1, 500))
107
+ p.push(`${where}: raffles "max_per_order" must be 1 to 500`);
108
+ if (r.hold_minutes !== undefined && !isWhole(r.hold_minutes, 5, 1440))
109
+ p.push(`${where}: raffles "hold_minutes" must be 5 to 1440`);
110
+ for (const k of Object.keys(r))
111
+ if (!["place", "adults_only", "max_per_order", "hold_minutes"].includes(k))
112
+ p.push(`${where}: unknown raffles setting "${k}"`);
113
+ }
114
+ }
115
+ if (c.retention_months !== undefined && !isWhole(c.retention_months, 1, 120))
116
+ p.push(`${where}: "retention_months" must be 1 to 120`);
117
+ return p;
118
+ }
119
+ /** Warnings that don't stop the file. */
120
+ export function fundraisingWarnings(c) {
121
+ const w = [];
122
+ if (c.country === "PH" && c.gifts && !c.organisation.solicitation_permit) {
123
+ w.push("Asking the public for donations in the Philippines usually needs a DSWD public solicitation permit (PD 1564). Add its number as organisation \"solicitation_permit\" once you have it.");
124
+ }
125
+ if (c.organisation.dgr)
126
+ w.push(`Thank-you emails will say gifts are tax-deductible, with ABN ${c.organisation.abn}. Only keep "dgr" on while the ATO endorses ${c.organisation.name} as a deductible gift recipient.`);
127
+ if (c.country !== "AU" && c.country !== "PH")
128
+ w.push(`No fundraising or raffle law is written down for ${c.country}: check the local rules before you take gifts or sell tickets.`);
129
+ return w;
130
+ }
131
+ /** The config, checked; throws naming every problem. */
132
+ export function checkFundraising(c) {
133
+ const problems = fundraisingProblems(c, "fundraising config");
134
+ if (problems.length)
135
+ throw new FundraisingError("bad_config", problems.join("\n"));
136
+ return c;
137
+ }
package/dist/draw.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import type { DrawRecord, DrawWinner } from "./types.ts";
2
+ /** 64 hex characters of fresh randomness. */
3
+ export declare function newSeed(): string;
4
+ /** SHA-256 of "1,2,…,N" less the void numbers: what the draw drew from. */
5
+ export declare function ticketsHash(issued: number, voidNumbers?: readonly number[]): Promise<string>;
6
+ /** The first draw: one winner for each rank, in rank order. */
7
+ export declare function drawWinners(o: {
8
+ seed: string;
9
+ raffleId: string;
10
+ issued: number;
11
+ voidNumbers: readonly number[];
12
+ ranks: readonly number[];
13
+ at: string;
14
+ }): Promise<DrawWinner[]>;
15
+ /** A redraw of one unclaimed prize: every ticket that has already won, including the one that didn't claim, is left out. */
16
+ export declare function redrawWinner(o: {
17
+ seed: string;
18
+ raffleId: string;
19
+ issued: number;
20
+ voidNumbers: readonly number[];
21
+ rank: number;
22
+ previous: readonly DrawWinner[];
23
+ at: string;
24
+ }): Promise<DrawWinner>;
25
+ /** True when the record's winners are exactly what its seed gives. Anyone can run it. */
26
+ export declare function verifyDraw(r: Pick<DrawRecord, "raffle_id" | "seed" | "issued" | "void_numbers" | "tickets_hash" | "winners">): Promise<boolean>;
package/dist/draw.js ADDED
@@ -0,0 +1,86 @@
1
+ // The raffle draw: random, and recorded so anyone can check it afterwards.
2
+ //
3
+ // At the draw a 32-byte seed comes from crypto.getRandomValues. Each prize's
4
+ // winner is then worked out from the seed, the raffle's id and the prize's
5
+ // rank with HMAC-SHA256, from the paid tickets (numbered 1 to N in the order
6
+ // they were paid for, less any refunded before the draw) that haven't won yet: first prize is drawn first, and no ticket wins twice.
7
+ // Rejection sampling keeps every ticket's chance equal. The seed, N, the
8
+ // refunded numbers and a hash of the ticket list are kept, so verifyDraw() gives the same winners again.
9
+ const enc = new TextEncoder();
10
+ const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
11
+ /** 64 hex characters of fresh randomness. */
12
+ export function newSeed() {
13
+ return hex(crypto.getRandomValues(new Uint8Array(32)));
14
+ }
15
+ /** SHA-256 of "1,2,…,N" less the void numbers: what the draw drew from. */
16
+ export async function ticketsHash(issued, voidNumbers = []) {
17
+ const list = poolWithout(issued, new Set(voidNumbers)).join(",");
18
+ return hex(await crypto.subtle.digest("SHA-256", enc.encode(list)));
19
+ }
20
+ async function keyFor(seed) {
21
+ if (!/^[0-9a-f]{64}$/.test(seed))
22
+ throw new Error("seed must be 64 hex characters");
23
+ const bytes = new Uint8Array(seed.match(/../g).map((h) => parseInt(h, 16)));
24
+ return crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
25
+ }
26
+ const SPAN = 2 ** 48;
27
+ /** One winner from the pool (ascending numbers), equally likely. */
28
+ async function pickOne(key, raffleId, rank, redraw, pool) {
29
+ if (pool.length === 0)
30
+ throw new Error("no tickets left to draw from");
31
+ const limit = Math.floor(SPAN / pool.length) * pool.length;
32
+ for (let attempt = 0; attempt < 1000; attempt++) {
33
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`${raffleId}|${rank}|${redraw}|${attempt}`)));
34
+ let x = 0;
35
+ for (let i = 0; i < 6; i++)
36
+ x = x * 256 + mac[i];
37
+ if (x < limit)
38
+ return pool[x % pool.length];
39
+ }
40
+ throw new Error("draw didn't settle"); // 1000 rejections in a row: not going to happen
41
+ }
42
+ function poolWithout(count, taken) {
43
+ const pool = [];
44
+ for (let n = 1; n <= count; n++)
45
+ if (!taken.has(n))
46
+ pool.push(n);
47
+ return pool;
48
+ }
49
+ /** The first draw: one winner for each rank, in rank order. */
50
+ export async function drawWinners(o) {
51
+ const key = await keyFor(o.seed);
52
+ const pool = poolWithout(o.issued, new Set(o.voidNumbers));
53
+ if (pool.length < o.ranks.length)
54
+ throw new Error("fewer tickets sold than prizes");
55
+ const winners = [];
56
+ for (const rank of [...o.ranks].sort((a, b) => a - b)) {
57
+ const number = await pickOne(key, o.raffleId, rank, 0, pool);
58
+ pool.splice(pool.indexOf(number), 1);
59
+ winners.push({ rank, number, redraw: 0, at: o.at });
60
+ }
61
+ return winners;
62
+ }
63
+ /** A redraw of one unclaimed prize: every ticket that has already won, including the one that didn't claim, is left out. */
64
+ export async function redrawWinner(o) {
65
+ const key = await keyFor(o.seed);
66
+ const redraw = 1 + o.previous.filter((w) => w.rank === o.rank).reduce((m, w) => Math.max(m, w.redraw), 0);
67
+ const pool = poolWithout(o.issued, new Set([...o.voidNumbers, ...o.previous.map((w) => w.number)]));
68
+ return { rank: o.rank, number: await pickOne(key, o.raffleId, o.rank, redraw, pool), redraw, at: o.at };
69
+ }
70
+ /** True when the record's winners are exactly what its seed gives. Anyone can run it. */
71
+ export async function verifyDraw(r) {
72
+ if (!/^[0-9a-f]{64}$/.test(r.seed) || (await ticketsHash(r.issued, r.void_numbers)) !== r.tickets_hash)
73
+ return false;
74
+ const first = [...r.winners.filter((w) => w.redraw === 0)].sort((a, b) => a.rank - b.rank);
75
+ const again = await drawWinners({ seed: r.seed, raffleId: r.raffle_id, issued: r.issued, voidNumbers: r.void_numbers, ranks: first.map((w) => w.rank), at: "" });
76
+ if (again.some((w, i) => w.number !== first[i].number))
77
+ return false;
78
+ const seen = [...first];
79
+ for (const w of r.winners.filter((x) => x.redraw > 0)) {
80
+ const re = await redrawWinner({ seed: r.seed, raffleId: r.raffle_id, issued: r.issued, voidNumbers: r.void_numbers, rank: w.rank, previous: seen, at: "" });
81
+ if (re.number !== w.number || re.redraw !== w.redraw)
82
+ return false;
83
+ seen.push(w);
84
+ }
85
+ return true;
86
+ }
@@ -0,0 +1,5 @@
1
+ export type FundraisingErrorCode = "bad_input" | "bad_config" | "store_failed" | "not_found" | "ref_reused" | "not_allowed" | "wrong_state";
2
+ export declare class FundraisingError extends Error {
3
+ readonly code: FundraisingErrorCode;
4
+ constructor(code: FundraisingErrorCode, message: string);
5
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,12 @@
1
+ // The one error the package throws. A refusal a buyer or giver can cause (a
2
+ // sold-out raffle, an amount out of range) is an answer, never a throw; this
3
+ // is for a mistake in the app's own call, a raffle the law doesn't allow, or
4
+ // a database failure.
5
+ export class FundraisingError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.name = "FundraisingError";
10
+ this.code = code;
11
+ }
12
+ }