const express = require('express'); const router = express.Router(); const pool = require('../pool'); const { HOLD_DAYS } = require('../services/affiliateConfig'); const CODE_PATTERN = /^[a-z0-9]{3,20}$/; // POST /api/affiliates/apply // // Public application form (public/affiliate-program.html). Applicant picks // their own code — like a username — rather than the system generating one, // since it's what they'll actually put in their promo link // (aidocked.com/?ref=THIS_CODE). Rows are created with status='pending' and // do NOT start earning clicks/commission until manually flipped to 'active' // in Supabase's Table Editor — same lightweight review step already used // for the rest of the affiliate program, no separate approval UI needed. router.post('/affiliates/apply', async (req, res) => { try { const code = String(req.body.code || '').trim().toLowerCase(); const name = String(req.body.name || '').trim(); const payout_email = String(req.body.payout_email || '').trim(); const promotion_plan = req.body.promotion_plan ? String(req.body.promotion_plan).trim().slice(0, 500) : null; if (!CODE_PATTERN.test(code)) { return res.status(400).json({ error: 'Code must be 3-20 characters, lowercase letters and numbers only.' }); } if (!name) { return res.status(400).json({ error: 'Name is required.' }); } if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(payout_email)) { return res.status(400).json({ error: 'A valid payout email is required.' }); } const { rows } = await pool.query( `INSERT INTO affiliates (code, name, payout_email, promotion_plan, status, click_count) VALUES ($1, $2, $3, $4, 'pending', 0) RETURNING code, status`, [code, name, payout_email, promotion_plan] ); res.status(201).json(rows[0]); } catch (err) { if (err.code === '23505') { // unique_violation on code return res.status(409).json({ error: 'That code is already taken — try another.' }); } res.status(500).json({ error: err.message }); } }); // POST /api/affiliates/:code/click // Fired by the homepage whenever a visitor arrives with ?ref=CODE in the URL. // No auth — this is a public, low-stakes counter, not financial data. router.post('/affiliates/:code/click', async (req, res) => { try { const { rows } = await pool.query( `UPDATE affiliates SET click_count = click_count + 1 WHERE code = $1 AND status = 'active' RETURNING code`, [req.params.code] ); // Unknown/disabled code: don't error, just no-op — a visitor's browser // sending a bad ref code shouldn't produce a visible failure. res.status(204).end(); } catch (err) { res.status(204).end(); } }); // GET /api/affiliates/:code/stats // Public, read-only self-check page for the affiliate — no login. Anyone // who knows the code can see its stats; see the note in affiliate.html // about why that's an accepted tradeoff at this stage. router.get('/affiliates/:code/stats', async (req, res) => { try { const code = req.params.code; const { rows: affRows } = await pool.query('SELECT * FROM affiliates WHERE code = $1', [code]); const affiliate = affRows[0]; if (!affiliate) { return res.status(404).json({ error: 'No affiliate found with that code' }); } const { rows: signupRows } = await pool.query( 'SELECT COUNT(*)::int AS count FROM merchants WHERE referred_by = $1', [code] ); // pending = recorded but not paid out yet; "payable" = the part of // pending that has passed the refund hold window. const { rows: commissionRows } = await pool.query( `SELECT status, COALESCE(SUM(commission_amount), 0)::float AS total, COALESCE(SUM(commission_amount) FILTER (WHERE created_at <= now() - ($2::int * interval '1 day')), 0)::float AS matured FROM referrals WHERE affiliate_code = $1 GROUP BY status`, [code, HOLD_DAYS] ); let pending = 0, payable = 0, paid = 0, cancelled = 0; commissionRows.forEach(r => { if (r.status === 'pending') { pending = r.total; payable = r.matured; } if (r.status === 'paid') paid = r.total; if (r.status === 'cancelled' || r.status === 'clawback') cancelled += r.total; }); res.json({ code: affiliate.code, name: affiliate.name, status: affiliate.status, clicks: affiliate.click_count, signups: signupRows[0].count, pendingCommission: pending, payableCommission: payable, paidCommission: paid, cancelledCommission: cancelled, holdDays: HOLD_DAYS }); } catch (err) { res.status(500).json({ error: err.message }); } }); module.exports = router;