()
| 16 | * Mounted at /api |
| 17 | */ |
| 18 | export function createReferralsRouter(): Router { |
| 19 | const router = Router(); |
| 20 | |
| 21 | // GET /api/referral/:code - Validate a referral code and return referrer + discount info |
| 22 | // Public endpoint — used by the /join/:code landing page |
| 23 | router.get('/referral/:code', async (req, res) => { |
| 24 | try { |
| 25 | const { code } = req.params; |
| 26 | const referralCode = await getReferralCode(code); |
| 27 | |
| 28 | if (!referralCode) { |
| 29 | return res.status(404).json({ error: 'Referral code not found' }); |
| 30 | } |
| 31 | |
| 32 | if (referralCode.status !== 'active') { |
| 33 | return res.status(410).json({ error: 'Referral code is no longer active' }); |
| 34 | } |
| 35 | |
| 36 | if (referralCode.expires_at && referralCode.expires_at < new Date()) { |
| 37 | return res.status(410).json({ error: 'Referral code has expired' }); |
| 38 | } |
| 39 | |
| 40 | if (referralCode.max_uses !== null && referralCode.used_count >= referralCode.max_uses) { |
| 41 | return res.status(410).json({ error: 'Referral code has been fully redeemed' }); |
| 42 | } |
| 43 | |
| 44 | // Fetch member profile for richer landing page experience |
| 45 | const profile = await memberDb.getProfileByOrgId(referralCode.referrer_org_id); |
| 46 | |
| 47 | let logo_url: string | null = null; |
| 48 | let brand_color: string | null = null; |
| 49 | if (profile?.primary_brand_domain) { |
| 50 | const domain = profile.primary_brand_domain; |
| 51 | // Skip orphaned brands — manifest is preserved server-side for adoption |
| 52 | // but must not surface on public read paths until claim is applied. |
| 53 | const hosted = await brandDb.getHostedBrandByDomain(domain); |
| 54 | if (hosted?.brand_json && !hosted.manifest_orphaned) { |
| 55 | const resolved = resolveBrandFromJson(domain, hosted.brand_json as Record<string, unknown>, hosted.domain_verified ?? false); |
| 56 | logo_url = resolved.logo_url ?? null; |
| 57 | brand_color = resolved.brand_color ?? null; |
| 58 | } |
| 59 | if (!logo_url) { |
| 60 | const discovered = await brandDb.getDiscoveredBrandByDomain(domain); |
| 61 | if (discovered?.brand_manifest && !discovered.manifest_orphaned) { |
| 62 | const resolved = resolveBrandFromJson(domain, discovered.brand_manifest as Record<string, unknown>, discovered.domain_verified ?? false); |
| 63 | logo_url = resolved.logo_url ?? null; |
| 64 | brand_color = brand_color || (resolved.brand_color ?? null); |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | res.json({ |
| 70 | valid: true, |
| 71 | code: referralCode.code, |
| 72 | discount_percent: referralCode.discount_percent, |
| 73 | target_company_name: referralCode.target_company_name, |
| 74 | referred_by: referralCode.referrer_user_name, |
| 75 | referrer_org_name: profile?.display_name || null, |
no test coverage detected