@mccaskie-labs/workbench-fundraising 0.0.0-stage → 0.2.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 +11 -0
- package/README.md +63 -2
- package/dist/cli.d.ts +12 -0
- package/dist/cli.js +161 -0
- package/dist/config.d.ts +7 -0
- package/dist/config.js +137 -0
- package/dist/draw.d.ts +26 -0
- package/dist/draw.js +86 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +12 -0
- package/dist/fundraising.d.ts +238 -0
- package/dist/fundraising.js +495 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +15 -0
- package/dist/law.d.ts +81 -0
- package/dist/law.js +406 -0
- package/dist/migration.d.ts +4 -0
- package/dist/migration.js +902 -0
- package/dist/money.d.ts +4 -0
- package/dist/money.js +10 -0
- package/dist/starters.d.ts +22 -0
- package/dist/starters.js +13 -0
- package/dist/styles.d.ts +33 -0
- package/dist/styles.js +108 -0
- package/dist/types.d.ts +278 -0
- package/dist/types.js +5 -0
- package/dist/ui.d.ts +96 -0
- package/dist/ui.js +236 -0
- package/dist/words.d.ts +4 -0
- package/dist/words.js +250 -0
- package/package.json +55 -4
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
// createFundraising: campaigns, gifts of an amount the giver chooses (once
|
|
2
|
+
// or monthly, through workbench-payments), cash the owner adds, and raffles
|
|
3
|
+
// checked against the place's law, with tickets sold through payments and a
|
|
4
|
+
// recorded draw. In the app's own database (fundraisingMigration), checked
|
|
5
|
+
// against the repo's workbench/fundraising.json. Use it with the service
|
|
6
|
+
// client, server side: the functions are the service role's only.
|
|
7
|
+
//
|
|
8
|
+
// The package never calls payments itself (tool packages don't import each
|
|
9
|
+
// other). The app passes startGift()'s `source` to payments.payChosen() or
|
|
10
|
+
// payments.subscribe({ gift: true }), and holdTickets()'s `line` and
|
|
11
|
+
// `source` to payments.createInvoice(), then hands every webhook outcome to
|
|
12
|
+
// handlePayment(). The total counts confirmed payments only.
|
|
13
|
+
import { checkFundraising } from "./config.js";
|
|
14
|
+
import { drawWinners, newSeed, redrawWinner, ticketsHash } from "./draw.js";
|
|
15
|
+
import { FundraisingError } from "./errors.js";
|
|
16
|
+
import { checkRaffle, raffleLaw } from "./law.js";
|
|
17
|
+
import { toCents } from "./money.js";
|
|
18
|
+
function failed(what, error) {
|
|
19
|
+
const m = error?.message ?? "";
|
|
20
|
+
if (m.includes("fundraising_ref_reused"))
|
|
21
|
+
throw new FundraisingError("ref_reused", `${what}: this ref was used for something else`);
|
|
22
|
+
if (m.includes("fundraising_not_found"))
|
|
23
|
+
throw new FundraisingError("not_found", `${what}: not found`);
|
|
24
|
+
if (m.includes("fundraising_amount_differs"))
|
|
25
|
+
throw new FundraisingError("bad_input", `${what}: the amount paid isn't the amount chosen`);
|
|
26
|
+
if (m.includes("fundraising_wrong_state"))
|
|
27
|
+
throw new FundraisingError("wrong_state", `${what}: not possible in its current state`);
|
|
28
|
+
if (m.includes("fundraising_pending"))
|
|
29
|
+
throw new FundraisingError("wrong_state", `${what}: an order is still being paid for; draw once it's paid or its hold lapses`);
|
|
30
|
+
if (m.includes("fundraising_changed"))
|
|
31
|
+
throw new FundraisingError("wrong_state", `${what}: the tickets changed while drawing; draw again`);
|
|
32
|
+
if (m.includes("fundraising_too_soon"))
|
|
33
|
+
throw new FundraisingError("not_allowed", `${what}: the prize's holding period isn't over`);
|
|
34
|
+
if (m.includes("fundraising_drawn"))
|
|
35
|
+
throw new FundraisingError("not_allowed", `${what}: the raffle has been drawn, so its tickets stay in it`);
|
|
36
|
+
// The database's own text stays out of the message (it can name tables); it's in `cause` for the log.
|
|
37
|
+
const err = new FundraisingError("store_failed", `${what}: the database refused it${error?.code ? ` (${error.code})` : ""}`);
|
|
38
|
+
err.cause = error;
|
|
39
|
+
throw err;
|
|
40
|
+
}
|
|
41
|
+
async function call(db, what, fn, args) {
|
|
42
|
+
const { data, error } = await db.rpc(fn, args);
|
|
43
|
+
if (error)
|
|
44
|
+
failed(what, error);
|
|
45
|
+
return data;
|
|
46
|
+
}
|
|
47
|
+
function text(v, what, max = 200) {
|
|
48
|
+
if (typeof v !== "string" || !v.trim() || v.length > max)
|
|
49
|
+
throw new FundraisingError("bad_input", `${what} must be text, 1 to ${max} characters`);
|
|
50
|
+
return v.trim();
|
|
51
|
+
}
|
|
52
|
+
const optText = (v, what, max) => (v === undefined || v === null || (typeof v === "string" && !v.trim()) ? null : text(v, what, max));
|
|
53
|
+
function cents(v, what, min = 1) {
|
|
54
|
+
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < min || v > 100_000_000_000)
|
|
55
|
+
throw new FundraisingError("bad_input", `${what} must be whole cents, ${min} or more`);
|
|
56
|
+
return v;
|
|
57
|
+
}
|
|
58
|
+
const iso = (d) => {
|
|
59
|
+
if (d === null || d === undefined)
|
|
60
|
+
return null;
|
|
61
|
+
const t = new Date(d);
|
|
62
|
+
if (Number.isNaN(t.getTime()))
|
|
63
|
+
throw new FundraisingError("bad_input", `${String(d)} isn't a date`);
|
|
64
|
+
return t.toISOString();
|
|
65
|
+
};
|
|
66
|
+
const refText = (r) => (r === undefined ? null : `${text(r.type, "ref type", 40)}:${text(r.id, "ref id", 150)}`);
|
|
67
|
+
const isUuid = (v) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
|
|
68
|
+
const uuid = (v, what) => {
|
|
69
|
+
if (typeof v !== "string" || !isUuid(v))
|
|
70
|
+
throw new FundraisingError("bad_input", `${what} must be an id`);
|
|
71
|
+
return v;
|
|
72
|
+
};
|
|
73
|
+
const num = (v) => Number(v);
|
|
74
|
+
const date = (v) => (v === null || v === undefined ? null : new Date(v).toISOString());
|
|
75
|
+
function toCampaign(r) {
|
|
76
|
+
return { ...r, goal_cents: r.goal_cents === null ? null : num(r.goal_cents), starts_at: date(r.starts_at), ends_at: date(r.ends_at), created_at: date(r.created_at) };
|
|
77
|
+
}
|
|
78
|
+
function toRaffle(r) {
|
|
79
|
+
return {
|
|
80
|
+
...r,
|
|
81
|
+
ticket_cents: num(r.ticket_cents),
|
|
82
|
+
sales_start: date(r.sales_start),
|
|
83
|
+
sales_end: date(r.sales_end),
|
|
84
|
+
draw_at: date(r.draw_at),
|
|
85
|
+
drawn_at: date(r.drawn_at),
|
|
86
|
+
created_at: date(r.created_at),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function toOrder(r) {
|
|
90
|
+
const first = r.first_number === null || r.first_number === undefined ? null : num(r.first_number);
|
|
91
|
+
const count = num(r.count);
|
|
92
|
+
return {
|
|
93
|
+
ref: r.ref,
|
|
94
|
+
raffle_id: r.raffle_id,
|
|
95
|
+
count,
|
|
96
|
+
amount_cents: num(r.amount_cents),
|
|
97
|
+
currency: r.currency ?? "",
|
|
98
|
+
status: r.status,
|
|
99
|
+
numbers: first === null || r.status === "released" ? [] : Array.from({ length: count }, (_, i) => first + i),
|
|
100
|
+
expires_at: date(r.expires_at),
|
|
101
|
+
payment_ref: r.payment_ref ?? null,
|
|
102
|
+
...(r.repeat ? { repeat: true } : {}),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function toGift(r) {
|
|
106
|
+
return { ...r, amount_cents: num(r.amount_cents), created_at: date(r.created_at), ...(r.repeat ? { repeat: true } : { repeat: false }) };
|
|
107
|
+
}
|
|
108
|
+
export function createFundraising(opts) {
|
|
109
|
+
const config = checkFundraising(opts.config);
|
|
110
|
+
const db = opts.db;
|
|
111
|
+
const now = opts.now ?? (() => new Date());
|
|
112
|
+
const currency = config.currency;
|
|
113
|
+
const gifts = () => {
|
|
114
|
+
if (!config.gifts)
|
|
115
|
+
throw new FundraisingError("bad_config", "gifts aren't switched on in workbench/fundraising.json");
|
|
116
|
+
return config.gifts;
|
|
117
|
+
};
|
|
118
|
+
const raffles = () => {
|
|
119
|
+
if (!config.raffles)
|
|
120
|
+
throw new FundraisingError("bad_config", "raffles aren't switched on in workbench/fundraising.json");
|
|
121
|
+
return config.raffles;
|
|
122
|
+
};
|
|
123
|
+
function raffleRow(r) {
|
|
124
|
+
const law = raffleLaw(r.place);
|
|
125
|
+
const settings = raffles();
|
|
126
|
+
const adults = law?.adults_only ? true : (r.adults_only ?? settings.adults_only ?? true);
|
|
127
|
+
if (!Array.isArray(r.prizes))
|
|
128
|
+
throw new FundraisingError("bad_input", "prizes must be a list");
|
|
129
|
+
return {
|
|
130
|
+
...(r.id ? { id: uuid(r.id, "id") } : {}),
|
|
131
|
+
campaign_id: r.campaign_id ? uuid(r.campaign_id, "campaign_id") : null,
|
|
132
|
+
title: text(r.title, "title"),
|
|
133
|
+
place: text(r.place, "place", 10),
|
|
134
|
+
currency,
|
|
135
|
+
ticket_cents: cents(r.ticket_cents, "ticket_cents", 50),
|
|
136
|
+
max_tickets: r.max_tickets,
|
|
137
|
+
sales_start: iso(r.sales_start),
|
|
138
|
+
sales_end: iso(r.sales_end),
|
|
139
|
+
draw_at: iso(r.draw_at),
|
|
140
|
+
draw_place: text(r.draw_place, "draw_place", 300),
|
|
141
|
+
prizes: r.prizes.map((p) => ({ rank: p.rank, label: text(p.label, "prize label"), value_cents: cents(p.value_cents, "prize value"), kind: p.kind, ...(p.cash_cents ? { cash_cents: cents(p.cash_cents, "prize cash", 0) } : {}) })),
|
|
142
|
+
permits: Object.fromEntries(Object.entries(r.permits ?? {}).filter(([, v]) => typeof v === "string" && v.trim()).map(([k, v]) => [text(k, "permit id", 20), text(v, "permit number", 100)])),
|
|
143
|
+
adults_only: adults,
|
|
144
|
+
terms: optText(r.terms, "terms", 5000),
|
|
145
|
+
unclaimed_months: law?.unclaimed_months ?? 3,
|
|
146
|
+
records_years: Math.max(law?.records_years ?? 7, 1),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function inputOf(r) {
|
|
150
|
+
return { ...r, permits: r.permits ?? {}, terms: r.terms ?? undefined };
|
|
151
|
+
}
|
|
152
|
+
async function getRaffle(id) {
|
|
153
|
+
const r = await call(db, "raffle", "fundraising_raffle_get", { p_id: uuid(id, "raffle id") });
|
|
154
|
+
if (!r)
|
|
155
|
+
throw new FundraisingError("not_found", `raffle ${id}: not found`);
|
|
156
|
+
return toRaffle(r);
|
|
157
|
+
}
|
|
158
|
+
const api = {
|
|
159
|
+
config,
|
|
160
|
+
async saveCampaign(c) {
|
|
161
|
+
const slug = text(c.slug, "slug", 80).toLowerCase();
|
|
162
|
+
if (!/^[a-z0-9]([a-z0-9-]{0,78}[a-z0-9])?$/.test(slug))
|
|
163
|
+
throw new FundraisingError("bad_input", "slug is letters, digits and hyphens, such as roof-appeal");
|
|
164
|
+
const image = optText(c.imageUrl, "imageUrl", 2000);
|
|
165
|
+
if (image && !image.startsWith("https://"))
|
|
166
|
+
throw new FundraisingError("bad_input", "imageUrl must start with https://");
|
|
167
|
+
const starts = iso(c.startsAt);
|
|
168
|
+
const ends = iso(c.endsAt);
|
|
169
|
+
if (starts && ends && ends <= starts)
|
|
170
|
+
throw new FundraisingError("bad_input", "endsAt must be after startsAt");
|
|
171
|
+
const row = await call(db, "save campaign", "fundraising_campaign_save", {
|
|
172
|
+
p: {
|
|
173
|
+
...(c.id ? { id: uuid(c.id, "id") } : {}),
|
|
174
|
+
slug,
|
|
175
|
+
title: text(c.title, "title"),
|
|
176
|
+
story: c.story === undefined ? "" : String(c.story).slice(0, 20000),
|
|
177
|
+
image_url: image,
|
|
178
|
+
goal_cents: c.goalCents === undefined || c.goalCents === null ? null : cents(c.goalCents, "goalCents"),
|
|
179
|
+
currency,
|
|
180
|
+
starts_at: starts,
|
|
181
|
+
ends_at: ends,
|
|
182
|
+
},
|
|
183
|
+
p_by: text(c.by, "by"),
|
|
184
|
+
p_now: now().toISOString(),
|
|
185
|
+
});
|
|
186
|
+
return toCampaign(row);
|
|
187
|
+
},
|
|
188
|
+
async setCampaignStatus(id, status, by) {
|
|
189
|
+
if (!["draft", "live", "closed"].includes(status))
|
|
190
|
+
throw new FundraisingError("bad_input", 'status must be "draft", "live" or "closed"');
|
|
191
|
+
return toCampaign(await call(db, "campaign status", "fundraising_campaign_status", { p_id: uuid(id, "id"), p_status: status, p_by: text(by, "by"), p_now: now().toISOString() }));
|
|
192
|
+
},
|
|
193
|
+
async campaign(key) {
|
|
194
|
+
const r = await call(db, "campaign", "fundraising_campaign_get", { p_key: text(key, "campaign", 80) });
|
|
195
|
+
return r ? toCampaign(r) : null;
|
|
196
|
+
},
|
|
197
|
+
async campaigns(status) {
|
|
198
|
+
return (await call(db, "campaigns", "fundraising_campaigns", { p_status: status ?? null })).map(toCampaign);
|
|
199
|
+
},
|
|
200
|
+
async totals(id) {
|
|
201
|
+
const t = await call(db, "totals", "fundraising_totals", { p_campaign: uuid(id, "campaign id") });
|
|
202
|
+
if (!t)
|
|
203
|
+
throw new FundraisingError("not_found", `campaign ${id}: not found`);
|
|
204
|
+
const giftsC = num(t.gifts_cents), cash = num(t.cash_cents), raffle = num(t.raffle_cents);
|
|
205
|
+
const raised = giftsC + cash + raffle;
|
|
206
|
+
const goal = t.goal_cents === null ? null : num(t.goal_cents);
|
|
207
|
+
return {
|
|
208
|
+
campaign_id: id,
|
|
209
|
+
gifts_cents: giftsC,
|
|
210
|
+
cash_cents: cash,
|
|
211
|
+
raffle_cents: raffle,
|
|
212
|
+
raised_cents: raised,
|
|
213
|
+
goal_cents: goal,
|
|
214
|
+
percent: goal === null ? null : Math.floor((raised * 100) / goal),
|
|
215
|
+
gifts: num(t.gifts),
|
|
216
|
+
monthly_givers: num(t.monthly_givers),
|
|
217
|
+
};
|
|
218
|
+
},
|
|
219
|
+
async supporters(id, limit = 50) {
|
|
220
|
+
const rows = await call(db, "supporters", "fundraising_supporters", { p_campaign: uuid(id, "campaign id"), p_limit: Math.max(1, Math.min(500, Math.floor(limit))) });
|
|
221
|
+
return rows.map((s) => ({ name: s.name, message: s.message ?? null, at: date(s.at) }));
|
|
222
|
+
},
|
|
223
|
+
async startGift(campaignId, o) {
|
|
224
|
+
const g = gifts();
|
|
225
|
+
const amount = cents(o.amountCents, "amountCents");
|
|
226
|
+
const min = toCents(g.min);
|
|
227
|
+
const max = toCents(g.max);
|
|
228
|
+
if (amount < min)
|
|
229
|
+
return { ok: false, reason: "too_small", min_cents: min, max_cents: max };
|
|
230
|
+
if (amount > max)
|
|
231
|
+
return { ok: false, reason: "too_big", min_cents: min, max_cents: max };
|
|
232
|
+
const monthly = o.monthly === true;
|
|
233
|
+
if (monthly && !g.monthly)
|
|
234
|
+
return { ok: false, reason: "no_monthly" };
|
|
235
|
+
const show = g.show_names === "ask" && o.showName === true;
|
|
236
|
+
const name = show ? text(o.name, "name", 100) : null;
|
|
237
|
+
const r = await call(db, "start gift", "fundraising_pledge_start", {
|
|
238
|
+
p_campaign: uuid(campaignId, "campaign id"),
|
|
239
|
+
p_amount: amount,
|
|
240
|
+
p_currency: currency,
|
|
241
|
+
p_monthly: monthly,
|
|
242
|
+
p_show: show,
|
|
243
|
+
p_name: name,
|
|
244
|
+
p_message: show ? optText(o.message, "message", 500) : null,
|
|
245
|
+
p_supporter: refText(o.supporter),
|
|
246
|
+
p_now: now().toISOString(),
|
|
247
|
+
});
|
|
248
|
+
if (!r.ok)
|
|
249
|
+
return { ok: false, reason: "not_live" };
|
|
250
|
+
const pledge = { ...r.pledge, amount_cents: num(r.pledge.amount_cents), created_at: date(r.pledge.created_at) };
|
|
251
|
+
const campaign = await api.campaign(campaignId);
|
|
252
|
+
return { ok: true, pledge, source: { type: "gift", id: pledge.id }, label: `${monthly ? "Monthly gift" : "Gift"} to ${campaign?.title ?? config.organisation.name}` };
|
|
253
|
+
},
|
|
254
|
+
async recordGift(o) {
|
|
255
|
+
return toGift(await call(db, "record gift", "fundraising_gift_record", { p_pledge: uuid(o.pledgeId, "pledgeId"), p_ref: text(o.paymentRef, "paymentRef"), p_amount: cents(o.amountCents, "amountCents"), p_now: now().toISOString() }));
|
|
256
|
+
},
|
|
257
|
+
async refundGift(ref) {
|
|
258
|
+
return call(db, "refund gift", "fundraising_gift_refund", { p_ref: text(ref, "paymentRef"), p_now: now().toISOString() });
|
|
259
|
+
},
|
|
260
|
+
async endMonthlyGift(id) {
|
|
261
|
+
return call(db, "end monthly gift", "fundraising_pledge_end", { p_pledge: uuid(id, "pledgeId"), p_now: now().toISOString() });
|
|
262
|
+
},
|
|
263
|
+
async addCash(campaignId, o) {
|
|
264
|
+
return toGift(await call(db, "add cash", "fundraising_cash_add", {
|
|
265
|
+
p_campaign: uuid(campaignId, "campaign id"),
|
|
266
|
+
p_key: text(o.key, "key", 150),
|
|
267
|
+
p_amount: cents(o.amountCents, "amountCents"),
|
|
268
|
+
p_currency: currency,
|
|
269
|
+
p_note: optText(o.note, "note", 500),
|
|
270
|
+
p_by: text(o.by, "by"),
|
|
271
|
+
p_now: now().toISOString(),
|
|
272
|
+
}));
|
|
273
|
+
},
|
|
274
|
+
checkRaffle(r) {
|
|
275
|
+
const law = raffleLaw(r.place);
|
|
276
|
+
const settings = config.raffles;
|
|
277
|
+
const adults = law?.adults_only ? (r.adults_only ?? true) : (r.adults_only ?? settings?.adults_only ?? true);
|
|
278
|
+
return checkRaffle({ ...r, adults_only: adults });
|
|
279
|
+
},
|
|
280
|
+
async saveRaffle(r, by) {
|
|
281
|
+
const row = raffleRow(r);
|
|
282
|
+
const raffle = toRaffle(await call(db, "save raffle", "fundraising_raffle_save", { p: row, p_by: text(by, "by"), p_now: now().toISOString() }));
|
|
283
|
+
return { raffle, check: api.checkRaffle(inputOf(raffle)) };
|
|
284
|
+
},
|
|
285
|
+
async openRaffle(id, by) {
|
|
286
|
+
const r = await getRaffle(id);
|
|
287
|
+
const check = api.checkRaffle(inputOf(r));
|
|
288
|
+
if (!check.ok)
|
|
289
|
+
throw new FundraisingError("not_allowed", `This raffle can't open yet:\n${check.problems.map((p) => `- ${p.text}`).join("\n")}`);
|
|
290
|
+
if (new Date(r.sales_end) <= now())
|
|
291
|
+
throw new FundraisingError("not_allowed", "This raffle's sales have already ended: change the dates first");
|
|
292
|
+
const raffle = toRaffle(await call(db, "open raffle", "fundraising_raffle_move", { p_id: r.id, p_from: "draft", p_to: "selling", p_by: text(by, "by"), p_reason: null, p_now: now().toISOString() }));
|
|
293
|
+
return { raffle, check };
|
|
294
|
+
},
|
|
295
|
+
async closeSales(id, by) {
|
|
296
|
+
return toRaffle(await call(db, "close sales", "fundraising_raffle_move", { p_id: uuid(id, "id"), p_from: "selling", p_to: "closed", p_by: text(by, "by"), p_reason: null, p_now: now().toISOString() }));
|
|
297
|
+
},
|
|
298
|
+
async cancelRaffle(id, o) {
|
|
299
|
+
const r = await getRaffle(id);
|
|
300
|
+
if (r.status === "drawn" || r.status === "cancelled")
|
|
301
|
+
throw new FundraisingError("wrong_state", `cancel raffle: it's ${r.status}`);
|
|
302
|
+
const raffle = toRaffle(await call(db, "cancel raffle", "fundraising_raffle_move", { p_id: r.id, p_from: r.status, p_to: "cancelled", p_by: text(o.by, "by"), p_reason: text(o.reason, "reason", 500), p_now: now().toISOString() }));
|
|
303
|
+
const refunds = (await call(db, "refunds", "fundraising_refundable", { p_raffle: r.id })).map((x) => ({ ...x, amount_cents: num(x.amount_cents) }));
|
|
304
|
+
return { raffle, refunds };
|
|
305
|
+
},
|
|
306
|
+
async raffle(id) {
|
|
307
|
+
const r = await call(db, "raffle", "fundraising_raffle_get", { p_id: uuid(id, "raffle id") });
|
|
308
|
+
return r ? toRaffle(r) : null;
|
|
309
|
+
},
|
|
310
|
+
async raffles(campaignId) {
|
|
311
|
+
return (await call(db, "raffles", "fundraising_raffles", { p_campaign: campaignId ? uuid(campaignId, "campaign id") : null })).map(toRaffle);
|
|
312
|
+
},
|
|
313
|
+
async holdTickets(raffleId, o) {
|
|
314
|
+
const settings = raffles();
|
|
315
|
+
const max = settings.max_per_order ?? 50;
|
|
316
|
+
if (!Number.isInteger(o.count) || o.count < 1)
|
|
317
|
+
throw new FundraisingError("bad_input", "count must be a whole number, 1 or more");
|
|
318
|
+
if (o.count > max)
|
|
319
|
+
return { ok: false, reason: "too_many", max };
|
|
320
|
+
const r = await getRaffle(raffleId);
|
|
321
|
+
if (r.adults_only && o.adult !== true)
|
|
322
|
+
return { ok: false, reason: "adult_required" };
|
|
323
|
+
const email = text(o.buyer?.email, "buyer email", 254);
|
|
324
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
|
325
|
+
throw new FundraisingError("bad_input", "buyer email isn't an email address");
|
|
326
|
+
const at = now();
|
|
327
|
+
const res = await call(db, "hold tickets", "fundraising_tickets_hold", {
|
|
328
|
+
p_raffle: r.id,
|
|
329
|
+
p_ref: text(o.orderRef, "orderRef", 190),
|
|
330
|
+
p_count: o.count,
|
|
331
|
+
p_name: text(o.buyer?.name, "buyer name", 100),
|
|
332
|
+
p_email: email,
|
|
333
|
+
p_customer: refText(o.customer),
|
|
334
|
+
p_expires: new Date(at.getTime() + (settings.hold_minutes ?? 30) * 60_000).toISOString(),
|
|
335
|
+
p_now: at.toISOString(),
|
|
336
|
+
});
|
|
337
|
+
if (!res.ok)
|
|
338
|
+
return { ok: false, reason: res.reason, ...(res.left !== undefined ? { left: res.left } : {}) };
|
|
339
|
+
const order = { ...toOrder(res.order), currency };
|
|
340
|
+
return {
|
|
341
|
+
ok: true,
|
|
342
|
+
order,
|
|
343
|
+
line: { label: `Raffle ticket: ${r.title}`, quantity: order.count, unit_cents: r.ticket_cents, total_cents: order.count * r.ticket_cents },
|
|
344
|
+
source: { type: "raffle_order", id: order.ref },
|
|
345
|
+
};
|
|
346
|
+
},
|
|
347
|
+
async confirmTickets(orderRef, o) {
|
|
348
|
+
const res = await call(db, "confirm tickets", "fundraising_tickets_confirm", {
|
|
349
|
+
p_ref: text(orderRef, "orderRef", 190),
|
|
350
|
+
p_payment: text(o.paymentRef, "paymentRef"),
|
|
351
|
+
p_amount: cents(o.amountCents, "amountCents"),
|
|
352
|
+
p_now: now().toISOString(),
|
|
353
|
+
});
|
|
354
|
+
if (!res.ok)
|
|
355
|
+
return { ok: false, reason: "too_late" };
|
|
356
|
+
return { ok: true, order: { ...toOrder(res.order), currency } };
|
|
357
|
+
},
|
|
358
|
+
async releaseTickets(orderRef) {
|
|
359
|
+
return call(db, "release tickets", "fundraising_tickets_release", { p_ref: text(orderRef, "orderRef", 190), p_now: now().toISOString() });
|
|
360
|
+
},
|
|
361
|
+
async voidTickets(ref) {
|
|
362
|
+
const r = await call(db, "void tickets", "fundraising_tickets_void", { p_ref: text(ref, "ref"), p_now: now().toISOString() });
|
|
363
|
+
return { ...r, amount_cents: num(r.amount_cents) };
|
|
364
|
+
},
|
|
365
|
+
async order(ref) {
|
|
366
|
+
const r = await call(db, "order", "fundraising_order_get", { p_ref: text(ref, "orderRef", 190) });
|
|
367
|
+
return r ? { ...toOrder(r), currency } : null;
|
|
368
|
+
},
|
|
369
|
+
async draw(raffleId, o) {
|
|
370
|
+
const by = text(o.by, "by");
|
|
371
|
+
const witnesses = (o.witnesses ?? []).map((w) => text(w, "witness", 100));
|
|
372
|
+
let r = await getRaffle(raffleId);
|
|
373
|
+
const at = now();
|
|
374
|
+
if (r.status === "selling" && new Date(r.sales_end) <= at)
|
|
375
|
+
r = (await api.closeSales(r.id, by));
|
|
376
|
+
if (r.status !== "closed")
|
|
377
|
+
throw new FundraisingError("wrong_state", r.status === "selling" ? "draw: ticket sales haven't closed yet" : `draw: the raffle is ${r.status}`);
|
|
378
|
+
const state = await call(db, "draw", "fundraising_draw_state", { p_raffle: r.id });
|
|
379
|
+
if (state.held > 0)
|
|
380
|
+
throw new FundraisingError("wrong_state", "draw: an order is still being paid for; draw once it's paid or its hold lapses");
|
|
381
|
+
const voids = state.void_numbers.map(Number);
|
|
382
|
+
const inDraw = state.issued - voids.length;
|
|
383
|
+
if (inDraw < r.prizes.length)
|
|
384
|
+
throw new FundraisingError("wrong_state", `draw: ${inDraw} tickets sold for ${r.prizes.length} prizes`);
|
|
385
|
+
const seed = newSeed();
|
|
386
|
+
const winners = await drawWinners({ seed, raffleId: r.id, issued: state.issued, voidNumbers: voids, ranks: r.prizes.map((p) => p.rank), at: at.toISOString() });
|
|
387
|
+
const hash = await ticketsHash(state.issued, voids);
|
|
388
|
+
const raffle = toRaffle(await call(db, "draw", "fundraising_raffle_draw", {
|
|
389
|
+
p_raffle: r.id,
|
|
390
|
+
p_seed: seed,
|
|
391
|
+
p_issued: state.issued,
|
|
392
|
+
p_void: voids,
|
|
393
|
+
p_hash: hash,
|
|
394
|
+
p_winners: winners,
|
|
395
|
+
p_by: by,
|
|
396
|
+
p_witnesses: witnesses,
|
|
397
|
+
p_now: at.toISOString(),
|
|
398
|
+
}));
|
|
399
|
+
return { raffle, record: api.drawRecord(raffle), results: api.results(raffle) };
|
|
400
|
+
},
|
|
401
|
+
async redraw(raffleId, rank, o) {
|
|
402
|
+
const r = await getRaffle(raffleId);
|
|
403
|
+
if (r.status !== "drawn" || !r.seed)
|
|
404
|
+
throw new FundraisingError("wrong_state", "redraw: the raffle hasn't been drawn");
|
|
405
|
+
if (!r.prizes.some((p) => p.rank === rank))
|
|
406
|
+
throw new FundraisingError("bad_input", `redraw: no prize ${rank}`);
|
|
407
|
+
if (r.claimed.includes(rank))
|
|
408
|
+
throw new FundraisingError("wrong_state", `redraw: prize ${rank} was claimed`);
|
|
409
|
+
const at = now();
|
|
410
|
+
const winner = await redrawWinner({ seed: r.seed, raffleId: r.id, issued: r.issued, voidNumbers: r.void_numbers, rank, previous: r.winners, at: at.toISOString() });
|
|
411
|
+
const raffle = toRaffle(await call(db, "redraw", "fundraising_raffle_redraw", {
|
|
412
|
+
p_raffle: r.id,
|
|
413
|
+
p_rank: rank,
|
|
414
|
+
p_expected: r.winners.length,
|
|
415
|
+
p_winner: winner,
|
|
416
|
+
p_by: text(o.by, "by"),
|
|
417
|
+
p_reason: text(o.reason, "reason", 500),
|
|
418
|
+
p_now: at.toISOString(),
|
|
419
|
+
}));
|
|
420
|
+
return { raffle, winner };
|
|
421
|
+
},
|
|
422
|
+
async markClaimed(raffleId, rank, by) {
|
|
423
|
+
return toRaffle(await call(db, "prize claimed", "fundraising_prize_claimed", { p_raffle: uuid(raffleId, "raffle id"), p_rank: rank, p_by: text(by, "by"), p_now: now().toISOString() }));
|
|
424
|
+
},
|
|
425
|
+
results(raffle) {
|
|
426
|
+
const row = raffle;
|
|
427
|
+
const latest = new Map();
|
|
428
|
+
for (const w of row.winners ?? []) {
|
|
429
|
+
const seen = latest.get(w.rank);
|
|
430
|
+
if (!seen || w.redraw > seen.redraw)
|
|
431
|
+
latest.set(w.rank, w);
|
|
432
|
+
}
|
|
433
|
+
return raffle.prizes
|
|
434
|
+
.filter((p) => latest.has(p.rank))
|
|
435
|
+
.map((p) => ({ rank: p.rank, label: p.label, number: latest.get(p.rank).number, claimed: (row.claimed ?? []).includes(p.rank) }));
|
|
436
|
+
},
|
|
437
|
+
async winnersToTell(raffleId) {
|
|
438
|
+
const r = await getRaffle(raffleId);
|
|
439
|
+
const labels = new Map(r.prizes.map((p) => [p.rank, p.label]));
|
|
440
|
+
const rows = await call(db, "winners", "fundraising_winner_contacts", { p_raffle: r.id });
|
|
441
|
+
return rows.map((w) => ({ ...w, label: labels.get(w.rank) ?? "" }));
|
|
442
|
+
},
|
|
443
|
+
drawRecord(raffle) {
|
|
444
|
+
const r = raffle;
|
|
445
|
+
if (r.status !== "drawn" || !r.seed || r.issued === null || !r.tickets_hash)
|
|
446
|
+
return null;
|
|
447
|
+
return {
|
|
448
|
+
raffle_id: r.id,
|
|
449
|
+
seed: r.seed,
|
|
450
|
+
issued: r.issued,
|
|
451
|
+
void_numbers: r.void_numbers,
|
|
452
|
+
tickets_hash: r.tickets_hash,
|
|
453
|
+
winners: r.winners.map((w) => ({ rank: w.rank, number: w.number, redraw: w.redraw, at: w.at })),
|
|
454
|
+
by: r.drawn_by ?? "",
|
|
455
|
+
witnesses: r.witnesses,
|
|
456
|
+
drawn_at: r.drawn_at,
|
|
457
|
+
};
|
|
458
|
+
},
|
|
459
|
+
async handlePayment(outcome) {
|
|
460
|
+
const src = outcome.invoice?.source ?? null;
|
|
461
|
+
const sub = outcome.subscription ?? null;
|
|
462
|
+
const pay = outcome.payment ?? null;
|
|
463
|
+
const giftOf = sub?.source?.type === "gift" ? sub.source.id : src?.type === "gift" ? src.id : null;
|
|
464
|
+
if ((outcome.kind === "paid" || outcome.kind === "renewed") && giftOf && pay) {
|
|
465
|
+
const gift = await api.recordGift({ pledgeId: giftOf, paymentRef: pay.id, amountCents: pay.amount_cents });
|
|
466
|
+
return { kind: "gift", gift, first: !gift.repeat };
|
|
467
|
+
}
|
|
468
|
+
if (outcome.kind === "subscription_ended" && sub?.source?.type === "gift") {
|
|
469
|
+
await api.endMonthlyGift(sub.source.id);
|
|
470
|
+
return { kind: "gift_ended", pledge_id: sub.source.id };
|
|
471
|
+
}
|
|
472
|
+
if (src?.type === "raffle_order") {
|
|
473
|
+
if (outcome.kind === "paid" && pay) {
|
|
474
|
+
const c = await api.confirmTickets(src.id, { paymentRef: pay.id, amountCents: pay.amount_cents });
|
|
475
|
+
if (c.ok)
|
|
476
|
+
return { kind: "tickets", order: c.order };
|
|
477
|
+
return { kind: "refund_tickets", order_ref: src.id, payment_ref: pay.id, amount_cents: pay.amount_cents };
|
|
478
|
+
}
|
|
479
|
+
if (outcome.kind === "failed" || outcome.kind === "expired") {
|
|
480
|
+
await api.releaseTickets(src.id);
|
|
481
|
+
return { kind: "tickets_released", order_ref: src.id };
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
return { kind: "ignored" };
|
|
485
|
+
},
|
|
486
|
+
async tick() {
|
|
487
|
+
const r = await call(db, "tick", "fundraising_tick", { p_now: now().toISOString() });
|
|
488
|
+
return { released: num(r.released), closed_raffles: r.closed_raffles, closed_campaigns: num(r.closed_campaigns) };
|
|
489
|
+
},
|
|
490
|
+
async cleanup() {
|
|
491
|
+
return call(db, "cleanup", "fundraising_cleanup", { p_now: now().toISOString(), p_months: config.retention_months ?? 24 });
|
|
492
|
+
},
|
|
493
|
+
};
|
|
494
|
+
return api;
|
|
495
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { createFundraising, type CampaignInput, type Fundraising, type FundraisingClient, type FundraisingOptions, type GiftRefusal, type Handled, type HeldTickets, type PaymentOutcome, type StartedGift, } from "./fundraising.ts";
|
|
2
|
+
export { fundraisingMigration } from "./migration.ts";
|
|
3
|
+
export { STARTER_FUNDRAISING } from "./starters.ts";
|
|
4
|
+
export { checkFundraising, fundraisingProblems, fundraisingWarnings } from "./config.ts";
|
|
5
|
+
export { checkRaffle, raffleLaw, RAFFLE_LAWS, PLACES, type Band, type RaffleLaw } from "./law.ts";
|
|
6
|
+
export { drawWinners, redrawWinner, ticketsHash, verifyDraw } from "./draw.ts";
|
|
7
|
+
export { toCents } from "./money.ts";
|
|
8
|
+
export { FundraisingError, type FundraisingErrorCode } from "./errors.ts";
|
|
9
|
+
export type * from "./types.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// @mccaskie-labs/workbench-fundraising: fundraising campaigns with a goal,
|
|
2
|
+
// gifts of an amount the giver chooses (once or monthly, through
|
|
3
|
+
// workbench-payments), cash the owner adds, and raffles checked against the
|
|
4
|
+
// law of the Australian state or territory, or the Philippines, they run in,
|
|
5
|
+
// with tickets sold through payments and a recorded, checkable draw. In the
|
|
6
|
+
// app's own database. Spec: docs/capabilities/31-fundraising.md; the law:
|
|
7
|
+
// docs/raffles.md.
|
|
8
|
+
export { createFundraising, } from "./fundraising.js";
|
|
9
|
+
export { fundraisingMigration } from "./migration.js";
|
|
10
|
+
export { STARTER_FUNDRAISING } from "./starters.js";
|
|
11
|
+
export { checkFundraising, fundraisingProblems, fundraisingWarnings } from "./config.js";
|
|
12
|
+
export { checkRaffle, raffleLaw, RAFFLE_LAWS, PLACES } from "./law.js";
|
|
13
|
+
export { drawWinners, redrawWinner, ticketsHash, verifyDraw } from "./draw.js";
|
|
14
|
+
export { toCents } from "./money.js";
|
|
15
|
+
export { FundraisingError } from "./errors.js";
|
package/dist/law.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { PermitNeed, Place, PrizeKind, RaffleCheck, RaffleInput } from "./types.ts";
|
|
2
|
+
/** A limit and the permit needed above it. */
|
|
3
|
+
export interface Band {
|
|
4
|
+
/** Up to and including this many cents needs `permit`; null: everything above the last limit. */
|
|
5
|
+
up_to_cents: number | null;
|
|
6
|
+
/** null: no permit needed in this band. */
|
|
7
|
+
permit: PermitNeed | null;
|
|
8
|
+
}
|
|
9
|
+
export interface RaffleLaw {
|
|
10
|
+
place: Place;
|
|
11
|
+
name: string;
|
|
12
|
+
/** The act, as the owner's page names it. */
|
|
13
|
+
law: string;
|
|
14
|
+
regulator: string;
|
|
15
|
+
url: string;
|
|
16
|
+
/** When the regulator's page was read. */
|
|
17
|
+
checked: string;
|
|
18
|
+
/** What the limits count: the prizes' value, or the most the tickets can take. */
|
|
19
|
+
measure: "prizes" | "sales";
|
|
20
|
+
bands: readonly Band[];
|
|
21
|
+
/** Permits needed whatever the size (the Philippines). */
|
|
22
|
+
always: readonly PermitNeed[];
|
|
23
|
+
/** WA: a raffle sold over more than one day needs this permit. */
|
|
24
|
+
multi_day?: PermitNeed;
|
|
25
|
+
/** Prizes as a share of the most the tickets can take: at least min, at most max. */
|
|
26
|
+
prize_share?: {
|
|
27
|
+
min?: number;
|
|
28
|
+
max?: number;
|
|
29
|
+
only_without_permit?: boolean;
|
|
30
|
+
};
|
|
31
|
+
/** The longest sales may run, in months. */
|
|
32
|
+
max_sales_months?: {
|
|
33
|
+
months: number;
|
|
34
|
+
only_without_permit?: boolean;
|
|
35
|
+
};
|
|
36
|
+
/** The latest the draw may be after sales close, in days. */
|
|
37
|
+
draw_within_days_of_close?: {
|
|
38
|
+
days: number;
|
|
39
|
+
only_without_permit?: boolean;
|
|
40
|
+
};
|
|
41
|
+
/** The latest the draw may be after sales open, in months. */
|
|
42
|
+
draw_within_months_of_open?: number;
|
|
43
|
+
/** "none": no cash prizes (travel may carry cash up to travel_cash_share of its value). */
|
|
44
|
+
cash: {
|
|
45
|
+
kind: "allowed";
|
|
46
|
+
} | {
|
|
47
|
+
kind: "none";
|
|
48
|
+
travel_cash_share: number;
|
|
49
|
+
} | {
|
|
50
|
+
kind: "max";
|
|
51
|
+
cents: number;
|
|
52
|
+
};
|
|
53
|
+
/** Prize kinds refused. */
|
|
54
|
+
banned: readonly PrizeKind[];
|
|
55
|
+
/** "not_first": liquor can't be the main prize. "minors": not where under-18s can buy. "limits": volume limits apply. */
|
|
56
|
+
liquor: "allowed" | "not_first" | "minors" | "limits" | "conditions" | "not_stated";
|
|
57
|
+
/** Buyers must be 18 or over. */
|
|
58
|
+
adults_only: boolean;
|
|
59
|
+
/** The least share of gross proceeds for the cause, as the owner's page explains it (a warning: the tool can't see costs). */
|
|
60
|
+
cause_share?: string;
|
|
61
|
+
/** Results must be published (as ticket numbers) for prizes over this. */
|
|
62
|
+
publish_over_cents?: number;
|
|
63
|
+
/** How long an unclaimed prize is held before a redraw, in months. */
|
|
64
|
+
unclaimed_months: number;
|
|
65
|
+
/** How long the raffle's records are kept, in years. */
|
|
66
|
+
records_years: number;
|
|
67
|
+
/** Who may run one: a warning, since the tool can't check it. */
|
|
68
|
+
eligible: string;
|
|
69
|
+
/** Always shown with this place. */
|
|
70
|
+
notes: readonly string[];
|
|
71
|
+
}
|
|
72
|
+
export declare const RAFFLE_LAWS: Readonly<Record<Place, RaffleLaw>>;
|
|
73
|
+
export declare const PLACES: Place[];
|
|
74
|
+
/** The law for a place, or null where Workbench has none written down. */
|
|
75
|
+
export declare function raffleLaw(place: string): RaffleLaw | null;
|
|
76
|
+
/**
|
|
77
|
+
* Checks a raffle against its place's law. Refusals (problems) stop it
|
|
78
|
+
* opening; warnings are shown beside it either way. Pure: no clock beyond
|
|
79
|
+
* the dates given, no database.
|
|
80
|
+
*/
|
|
81
|
+
export declare function checkRaffle(r: RaffleInput): RaffleCheck;
|