Shaurya2020 commited on
Commit
210cfbb
Β·
verified Β·
1 Parent(s): 6a44b15

Betting: 4 endpoints with server-side selection validation

Browse files
Files changed (1) hide show
  1. src/bettingApi.js +135 -0
src/bettingApi.js ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { Router } = require('express');
2
+ const { db, newId, h, bad, conflict, notFound, scope, loadEvent, BET_TYPES, currentOdds } = require('./core.js');
3
+
4
+ const r = Router();
5
+
6
+ const shape = b => ({
7
+ id: b.id, event_id: b.event_id, punter_ref: b.punter_ref, bet_type: b.bet_type,
8
+ selections: JSON.parse(b.selections_json), stake: b.stake, struck_odds: b.struck_odds,
9
+ odds_version: b.odds_version_no, status: b.status, dividend: b.dividend,
10
+ payout: b.payout, created_at: b.created_at, settled_at: b.settled_at
11
+ });
12
+
13
+ /**
14
+ * Selection validation. The client mirrors this for a fast error message, but
15
+ * this is the copy that decides β€” a bet that skips the UI still lands here.
16
+ */
17
+ function validate(betType, selections, eventId) {
18
+ const spec = BET_TYPES[betType];
19
+ if (!spec) bad('Unknown bet type.', { bet_type: betType, allowed: Object.keys(BET_TYPES) });
20
+ if (!Array.isArray(selections)) bad('selections must be an array of participant ids.');
21
+
22
+ if (selections.length !== spec.picks)
23
+ bad(`A ${betType} needs exactly ${spec.picks} selection${spec.picks > 1 ? 's' : ''}${spec.ordered ? ', in finishing order' : ''}.`,
24
+ { supplied: selections.length, required: spec.picks });
25
+
26
+ if (new Set(selections).size !== selections.length)
27
+ bad('The same runner appears twice in the selection.');
28
+
29
+ const rows = db.prepare(
30
+ `SELECT id, is_scratched, horse_name FROM race_participants WHERE event_id = ? AND id IN (${selections.map(() => '?').join(',')})`
31
+ ).all(eventId, ...selections);
32
+
33
+ if (rows.length !== selections.length)
34
+ bad('A selection does not belong to this race.', { event_id: eventId });
35
+
36
+ const scratched = rows.filter(p => p.is_scratched);
37
+ if (scratched.length)
38
+ bad('A scratched runner is selected.', { scratched: scratched.map(p => p.horse_name) });
39
+
40
+ return spec;
41
+ }
42
+
43
+ /* 1 ── POST /bets ───────────────────────────────────────────────────────── */
44
+ r.post('/', h((req, res) => {
45
+ const b = req.body || {};
46
+ const e = loadEvent(req.admin, b.event_id);
47
+
48
+ if (e.status !== 'open') conflict(`Betting is not open on this race (status: ${e.status}).`);
49
+ if (new Date(e.post_time) <= new Date()) conflict('Post time has passed. Close the race before it can be settled.');
50
+ if (!(b.stake > 0)) bad('stake must be greater than zero.');
51
+ if (!b.punter_ref) bad('punter_ref is required.');
52
+
53
+ const spec = validate(b.bet_type, b.selections, e.id);
54
+
55
+ // Straight bets lock the price now. Reading it at settlement instead would let
56
+ // a later price move change what an already-struck bet pays.
57
+ let struck = null;
58
+ if (!spec.exotic) {
59
+ const price = currentOdds(e.id).find(o => o.participant_id === b.selections[0]);
60
+ if (!price) conflict('That runner has no price on the current odds version.');
61
+ struck = price.decimal_odds;
62
+ }
63
+
64
+ const id = newId('bet');
65
+ db.prepare(`INSERT INTO bets
66
+ (id, owner_admin_id, event_id, punter_ref, bet_type, selections_json, selection_count,
67
+ stake, struck_odds, odds_version_no)
68
+ VALUES (?,?,?,?,?,?,?,?,?,?)`)
69
+ .run(id, e.owner_admin_id, e.id, b.punter_ref, b.bet_type,
70
+ JSON.stringify(b.selections), b.selections.length, b.stake, struck, e.current_odds_version);
71
+
72
+ const row = db.prepare('SELECT * FROM bets WHERE id = ?').get(id);
73
+ res.status(201).json({ data: { ...shape(row),
74
+ potential_return: struck ? +(b.stake * struck).toFixed(2) : null,
75
+ settlement_basis: spec.exotic ? `pari-mutuel, ${spec.takeout * 100}% takeout` : 'fixed odds' } });
76
+ }));
77
+
78
+ /* 2 ── GET /bets ────────────────────────────────────────────────────────── */
79
+ r.get('/', h((req, res) => {
80
+ const s = scope(req.admin, 'b');
81
+ const where = [s.sql], params = [...s.params];
82
+ for (const [q, col] of [['event_id', 'b.event_id'], ['bet_type', 'b.bet_type'],
83
+ ['status', 'b.status'], ['punter_ref', 'b.punter_ref']])
84
+ if (req.query[q]) { where.push(`${col} = ?`); params.push(req.query[q]); }
85
+
86
+ const limit = Math.min(parseInt(req.query.limit) || 100, 500);
87
+ const offset = parseInt(req.query.offset) || 0;
88
+
89
+ const rows = db.prepare(`
90
+ SELECT b.*, e.name AS event_name, e.venue
91
+ FROM bets b JOIN race_events e ON e.id = b.event_id
92
+ WHERE ${where.join(' AND ')}
93
+ ORDER BY b.created_at DESC LIMIT ? OFFSET ?`).all(...params, limit, offset);
94
+
95
+ const totals = db.prepare(`
96
+ SELECT count(*) n, coalesce(sum(b.stake),0) staked, coalesce(sum(b.payout),0) paid
97
+ FROM bets b WHERE ${where.join(' AND ')}`).get(...params);
98
+
99
+ res.json({
100
+ data: rows.map(x => ({ ...shape(x), event_name: x.event_name, venue: x.venue })),
101
+ meta: { count: totals.n, total_staked: totals.staked, total_paid: totals.paid, limit, offset }
102
+ });
103
+ }));
104
+
105
+ /* 3 ── GET /bets/:id ────────────────────���───────────────────────────────── */
106
+ r.get('/:id', h((req, res) => {
107
+ const s = scope(req.admin, 'b');
108
+ const row = db.prepare(`SELECT b.* FROM bets b WHERE b.id = ? AND ${s.sql}`).get(req.params.id, ...s.params);
109
+ if (!row) notFound('Bet not found.');
110
+
111
+ const sels = JSON.parse(row.selections_json);
112
+ const runners = db.prepare(
113
+ `SELECT id, cloth_no, horse_name FROM race_participants WHERE id IN (${sels.map(() => '?').join(',')})`
114
+ ).all(...sels);
115
+
116
+ res.json({ data: { ...shape(row),
117
+ selection_detail: sels.map((id, i) => ({ position: i + 1, ...runners.find(r2 => r2.id === id) })) } });
118
+ }));
119
+
120
+ /* 4 ── PATCH /bets/:id/cancel ───────────────────────────────────────────── */
121
+ r.patch('/:id/cancel', h((req, res) => {
122
+ const s = scope(req.admin, 'b');
123
+ const row = db.prepare(`SELECT b.* FROM bets b WHERE b.id = ? AND ${s.sql}`).get(req.params.id, ...s.params);
124
+ if (!row) notFound('Bet not found.');
125
+ if (row.status !== 'open') conflict(`A ${row.status} bet cannot be cancelled.`);
126
+
127
+ const e = db.prepare('SELECT status FROM race_events WHERE id = ?').get(row.event_id);
128
+ if (e.status !== 'open') conflict('Bets can only be cancelled while betting is still open.');
129
+
130
+ db.prepare(`UPDATE bets SET status = 'cancelled', payout = stake, settled_at = datetime('now') WHERE id = ?`)
131
+ .run(row.id);
132
+ res.json({ data: shape(db.prepare('SELECT * FROM bets WHERE id = ?').get(row.id)) });
133
+ }));
134
+
135
+ module.exports = r;