diff --git a/lib/config.js b/lib/config.js index 0e0411e..705bca5 100644 --- a/lib/config.js +++ b/lib/config.js @@ -72,6 +72,14 @@ export function upiCheckoutEnabled() { return env('UPI_CHECKOUT_ENABLED', 'false') === 'true'; } +export function telegramCommunityUrl() { + return env('TELEGRAM_COMMUNITY_URL', 'https://t.me/nightlifez_official'); +} + +export function whatsappChannelUrl() { + return env('WHATSAPP_CHANNEL_URL', 'https://whatsapp.com/channel/0029VaNightlifez'); +} + export function socialProofMin() { const n = parseInt(env('SOCIAL_PROOF_MIN', '5'), 10); return Number.isFinite(n) && n >= 5 ? n : 5; diff --git a/lib/handlers/admin.js b/lib/handlers/admin.js index 5271e2b..104c05a 100644 --- a/lib/handlers/admin.js +++ b/lib/handlers/admin.js @@ -29,6 +29,7 @@ import { getNotificationMessagesList, getSuppressionsList } from '../services/notification-dispatcher.js'; +import { listOnboardingAudits } from '../services/community-onboarding.js'; /** Resolve the admin for this request (bootstrapping the owner once), or throw 401/403. */ @@ -582,6 +583,91 @@ export async function refundPayment(ctx) { sendJson(ctx.res, 200, { ok: true, ...res }); } +export async function listPayments(ctx) { + await guard(ctx, R.BOOKINGS); + const status = ctx.query.get('status'); + const provider = ctx.query.get('provider'); + const limit = Math.min(parseInt(ctx.query.get('limit') || '100', 10), 200); + const offset = Math.max(parseInt(ctx.query.get('offset') || '0', 10), 0); + + const params = []; + const whereClauses = []; + + if (status) { + params.push(status); + whereClauses.push(`p.status = $${params.length}`); + } + if (provider) { + params.push(provider); + whereClauses.push(`p.provider = $${params.length}`); + } + + const whereSql = whereClauses.length ? `WHERE ${whereClauses.join(' AND ')}` : ''; + params.push(limit); + const limitIdx = params.length; + params.push(offset); + const offsetIdx = params.length; + + const { rows } = await db.query( + `SELECT p.id, p.user_id, p.provider, p.provider_txn_id, p.provider_payment_id, + p.order_id, p.amount, p.currency, p.status, p.purpose, p.failure_reason, + p.refund_ref, p.is_test, p.created_at, p.paid_at, p.refunded_at, p.webhook_verified_at, + u.alias AS user_alias, + b.id AS booking_id, b.status AS booking_status, e.title AS event_title + FROM payments p + LEFT JOIN users u ON u.id = p.user_id + LEFT JOIN bookings b ON b.payment_id = p.id + LEFT JOIN events e ON e.id = b.event_id + ${whereSql} + ORDER BY p.created_at DESC + LIMIT $${limitIdx} OFFSET $${offsetIdx}`, + params + ); + + const stats = (await db.query( + `SELECT + COUNT(*)::int AS total_payments, + COUNT(*) FILTER (WHERE status = 'succeeded')::int AS succeeded_count, + COUNT(*) FILTER (WHERE status = 'pending')::int AS pending_count, + COUNT(*) FILTER (WHERE status = 'failed')::int AS failed_count, + COUNT(*) FILTER (WHERE status = 'expired')::int AS expired_count, + COUNT(*) FILTER (WHERE status = 'refunded')::int AS refunded_count, + COUNT(*) FILTER (WHERE status = 'disputed')::int AS disputed_count, + COUNT(*) FILTER (WHERE status = 'refund_pending')::int AS refund_pending_count, + COALESCE(SUM(amount) FILTER (WHERE status = 'succeeded' AND currency = 'INR'), 0)::bigint AS volume_inr_paise + FROM payments` + )).rows[0]; + + sendJson(ctx.res, 200, { ok: true, payments: rows, stats }); +} + +export async function paymentAudit(ctx) { + await guard(ctx, R.BOOKINGS); + const paymentId = uuidParam(ctx.params.id); + const payment = (await db.one(`SELECT * FROM payments WHERE id = $1`, [paymentId])); + if (!payment) throw new HttpError(404, 'not_found', 'Payment not found'); + + const { rows: audits } = await db.query( + `SELECT id, payment_id, order_id, from_status, to_status, actor, details, created_at + FROM payment_audits + WHERE payment_id = $1 OR (order_id = $2 AND order_id IS NOT NULL) + ORDER BY created_at ASC`, + [paymentId, payment.order_id] + ); + + sendJson(ctx.res, 200, { ok: true, payment, audits }); +} + +export async function listOnboarding(ctx) { + await guard(ctx, R.ANY); + const limit = Math.min(parseInt(ctx.query.get('limit') || '50', 10), 200); + const offset = Math.max(parseInt(ctx.query.get('offset') || '0', 10), 0); + const channel = ctx.query.get('channel'); + + const result = await listOnboardingAudits({ limit, offset, channel }); + sendJson(ctx.res, 200, { ok: true, ...result }); +} + // ---------- memberships ---------- export async function listMemberships(ctx) { diff --git a/lib/handlers/auth.js b/lib/handlers/auth.js index 1a91e4c..aaa3bce 100644 --- a/lib/handlers/auth.js +++ b/lib/handlers/auth.js @@ -28,6 +28,13 @@ import { getLinkedIdentities } from '../services/whatsapp-auth.js'; import { getConsents, recordConsent } from '../services/communication-consent.js'; +import { + registerTelegramOnboarding, + registerWhatsAppOnboarding, + trackOnboardingAction, + getOnboardingState +} from '../services/community-onboarding.js'; +import { whatsappChannelUrl, telegramCommunityUrl } from '../config.js'; const AuthBody = z.object({ initData: z.string().max(4096).optional(), @@ -69,6 +76,11 @@ export async function telegramAuth({ req, res, ip }) { // Opening the Mini App from the bot implies the user has started the bot. const user = await upsertTelegramUser(v.user, { ageConfirmed: body.ageConfirmed === true, botStarted: Boolean(body.initData) }); const { csrf } = await startSession(req, res, user); + await registerTelegramOnboarding({ + userId: user.id, + telegramUserId: user.telegram_user_id, + botStarted: false + }).catch((err) => logger.warn('telegram onboarding registration failed', { error: err.message })); sendJson(res, 200, { ok: true, csrf, user: publicUser(user), startParam: v.startParam || null }); } @@ -142,6 +154,11 @@ export async function oidcCallback({ req, res, query }) { // telegram:bot_access scope means the bot may DM this user. const user = await upsertTelegramUser({ id: Number(claims.id), name: claims.name, username: claims.preferred_username }, { ageConfirmed: sealed.age === true, botStarted: true }); + await registerTelegramOnboarding({ + userId: user.id, + telegramUserId: user.telegram_user_id, + botStarted: true + }).catch((err) => logger.warn('telegram onboarding registration on oidc failed', { error: err.message })); await startSession(req, res, user); redirect(res, sealed.next); } catch (err) { @@ -223,6 +240,11 @@ export async function widgetCallback({ req, res, query, ip }) { try { const user = await upsertTelegramUser(v.user, { ageConfirmed: true, botStarted: false }); + await registerTelegramOnboarding({ + userId: user.id, + telegramUserId: user.telegram_user_id, + botStarted: false + }).catch((err) => logger.warn('telegram onboarding registration on widget failed', { error: err.message })); await startSession(req, res, user); return redirect(res, nextPath); } catch (err) { @@ -543,6 +565,10 @@ export async function verifyWhatsAppOtpHandler({ req, res, ip }) { } const { csrf } = await startSession(req, res, auth.user); + await registerWhatsAppOnboarding({ + userId: auth.user.id, + phone: auth.user.phone + }).catch((err) => logger.warn('whatsapp onboarding registration failed', { error: err.message })); if (isHtmlAccept) { const secure = Boolean(process.env.VERCEL) || req.headers['x-forwarded-proto'] === 'https'; @@ -554,7 +580,12 @@ export async function verifyWhatsAppOtpHandler({ req, res, ip }) { ok: true, csrf, user: publicUser(auth.user), - isNewUser: auth.isNewUser + isNewUser: auth.isNewUser, + onboarding: { + channel: 'whatsapp', + channelUrl: whatsappChannelUrl(), + offered: true + } }); } @@ -576,10 +607,20 @@ export async function linkWhatsAppHandler({ req, res, ip }) { promotionalOptIn: body.promotionalOptIn }); + await registerWhatsAppOnboarding({ + userId: user.id, + phone: body.phone + }).catch((err) => logger.warn('whatsapp onboarding registration on link failed', { error: err.message })); + sendJson(res, 200, { ok: true, message: 'WhatsApp connected successfully', - user: publicUser(auth.user) + user: publicUser(auth.user), + onboarding: { + channel: 'whatsapp', + channelUrl: whatsappChannelUrl(), + offered: true + } }); } @@ -641,3 +682,33 @@ export async function updateMyCommunicationPreferences({ req, res, ip }) { sendJson(res, 200, { ok: true, preferences }); } +const TrackOnboardingBody = z.object({ + channel: z.enum(['telegram', 'whatsapp']), + action: z.enum(['channel_clicked', 'channel_dismissed']), + metadata: z.record(z.unknown()).optional() +}).strict(); + +/** POST /api/onboarding/track β€” Record channel follow/join action without false membership claim. */ +export async function trackOnboardingHandler({ req, res }) { + const user = await requireUser(req); + requireCsrf(req, user); + const body = parse(TrackOnboardingBody, await readJson(req)); + const result = await trackOnboardingAction({ + userId: user.id, + channel: body.channel, + action: body.action, + metadata: body.metadata || {} + }); + sendJson(res, 200, { ok: true, ...result }); +} + +/** GET /api/me/onboarding β€” Current attendee onboarding progress across channels. */ +export async function getMyOnboardingHandler({ req, res }) { + const user = await requireUser(req); + const onboarding = await getOnboardingState(user.id); + sendJson(res, 200, { ok: true, onboarding }); +} + + + + diff --git a/lib/router.js b/lib/router.js index d91cd32..c486904 100644 --- a/lib/router.js +++ b/lib/router.js @@ -77,6 +77,8 @@ const ROUTES = [ ['GET', '/api/me/identities', h('auth', 'getMyIdentitiesHandler')], ['GET', '/api/me/communication-preferences', h('auth', 'getMyCommunicationPreferences')], ['PATCH', '/api/me/communication-preferences', h('auth', 'updateMyCommunicationPreferences')], + ['GET', '/api/me/onboarding', h('auth', 'getMyOnboardingHandler')], + ['POST', '/api/onboarding/track', h('auth', 'trackOnboardingHandler')], ['POST', '/api/auth/dev', h('auth', 'devAuth')], ['POST', '/api/auth/preview-reviewer', h('auth', 'previewReviewerAuth')], ['POST', '/api/auth/logout', h('auth', 'logout')], @@ -220,6 +222,9 @@ const ROUTES = [ ['GET', '/api/admin/orders', h('admin', 'listOrders')], ['POST', '/api/admin/orders/:id/link', h('admin', 'linkOrder')], ['POST', '/api/admin/payments/:id/refund', h('admin', 'refundPayment')], + ['GET', '/api/admin/payments', h('admin', 'listPayments')], + ['GET', '/api/admin/payments/:id/audit', h('admin', 'paymentAudit')], + ['GET', '/api/admin/onboarding', h('admin', 'listOnboarding')], ['GET', '/api/admin/memberships', h('admin', 'listMemberships')], ['POST', '/api/admin/entitlements/:id/revoke', h('admin', 'revokeEntitlement')], ['GET', '/api/admin/leads', h('admin', 'listLeads')], diff --git a/lib/services/community-onboarding.js b/lib/services/community-onboarding.js new file mode 100644 index 0000000..490c402 --- /dev/null +++ b/lib/services/community-onboarding.js @@ -0,0 +1,360 @@ +// lib/services/community-onboarding.js - Automated community onboarding for Telegram and WhatsApp. +// Enforces idempotent records, explicit consent separation, PII protection, and official channel tracking. + +import { db } from '../db.js'; +import { tg } from '../telegram/api.js'; +import { siteUrl, telegramCommunityUrl, whatsappChannelUrl, env } from '../config.js'; +import { maskPhone } from './phone.js'; +import { logger } from '../logger.js'; +import { HttpError } from '../http.js'; + +const esc = (s) => String(s ?? '').replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c])); + +/** + * Register user in the Telegram onboarding flow. + * Dispatches a welcome message ONLY if the user has started the bot or authorized communication, + * and NEVER repeats the welcome message on subsequent logins. + */ +export async function registerTelegramOnboarding({ + userId, + telegramUserId, + botStarted = false, + c = db +}) { + if (!userId) throw new HttpError(400, 'missing_user_id', 'User ID is required'); + + const tgIdNum = telegramUserId ? Number(telegramUserId) : null; + + // 1. Check existing record + const existing = (await c.query( + `SELECT * FROM user_onboarding WHERE user_id = $1 AND channel = 'telegram' FOR UPDATE`, + [userId] + )).rows[0]; + + let record = existing; + + if (!existing) { + const insertRes = await c.query( + `INSERT INTO user_onboarding ( + user_id, channel, status, telegram_user_id, created_at, updated_at + ) VALUES ($1, 'telegram', 'registered', $2, now(), now()) + ON CONFLICT (user_id, channel) DO UPDATE + SET telegram_user_id = COALESCE(EXCLUDED.telegram_user_id, user_onboarding.telegram_user_id), + updated_at = now() + RETURNING *`, + [userId, tgIdNum] + ); + record = insertRes.rows[0]; + } else if (tgIdNum && !existing.telegram_user_id) { + const updateRes = await c.query( + `UPDATE user_onboarding + SET telegram_user_id = $2, updated_at = now() + WHERE id = $1 RETURNING *`, + [existing.id, tgIdNum] + ); + record = updateRes.rows[0]; + } + + // 2. Dispatch welcome message ONLY if bot communication is authorized AND welcome has NOT been sent yet + const canSendWelcome = Boolean(botStarted && tgIdNum && !record.welcome_sent_at); + + if (canSendWelcome) { + try { + const commUrl = telegramCommunityUrl(); + const welcomeText = + 'Welcome to NIGHTLIFEZ! 🍸✨\n\n' + + 'Your account is verified and ready. Discover exclusive weekend parties, social mixers, dinner clubs, and secret nightlife across South India (21+).\n\n' + + 'Join our official community channel for private event drops, secret venue coordinates, and guestlist privileges.'; + + const buttons = [ + [{ text: 'Join NIGHTLIFEZ Community', url: commUrl }], + [{ text: 'Open NIGHTLIFEZ', web_app: { url: siteUrl() } }] + ]; + + await tg('sendMessage', { + chat_id: tgIdNum, + text: welcomeText, + parse_mode: 'HTML', + link_preview_options: { is_disabled: true }, + reply_markup: { inline_keyboard: buttons } + }); + + // Check community membership status where bot permissions allow + let membershipVerified = false; + const eventsChatId = env('TG_CHAT_ID_EVENTS'); + if (eventsChatId) { + try { + const member = await tg('getChatMember', { chat_id: eventsChatId, user_id: tgIdNum }); + if (member && ['creator', 'administrator', 'member', 'restricted'].includes(member.status)) { + membershipVerified = true; + } + } catch { + // Non-fatal if bot lacks admin rights on chat + } + } + + const updated = await c.query( + `UPDATE user_onboarding + SET status = 'welcome_sent', + welcome_sent_at = now(), + channel_offered_at = COALESCE(channel_offered_at, now()), + membership_verified = $2, + membership_checked_at = now(), + updated_at = now() + WHERE id = $1 RETURNING *`, + [record.id, membershipVerified] + ); + record = updated.rows[0]; + } catch (err) { + logger.warn('community onboarding welcome delivery deferred or failed', { + userId, + telegramUserId: tgIdNum, + error: err.message + }); + } + } + + return { + ok: true, + record, + communityUrl: telegramCommunityUrl(), + welcomeSent: Boolean(record.welcome_sent_at) + }; +} + +/** + * Register user in the WhatsApp onboarding flow. + * Idempotently records that the channel follow action was offered. + * Never claims false membership and never sends unsolicited marketing messages. + */ +export async function registerWhatsAppOnboarding({ + userId, + phone, + c = db +}) { + if (!userId) throw new HttpError(400, 'missing_user_id', 'User ID is required'); + + const existing = (await c.query( + `SELECT * FROM user_onboarding WHERE user_id = $1 AND channel = 'whatsapp' FOR UPDATE`, + [userId] + )).rows[0]; + + let record = existing; + + if (!existing) { + const insertRes = await c.query( + `INSERT INTO user_onboarding ( + user_id, channel, status, whatsapp_phone, channel_offered_at, created_at, updated_at + ) VALUES ($1, 'whatsapp', 'channel_offered', $2, now(), now(), now()) + ON CONFLICT (user_id, channel) DO UPDATE + SET whatsapp_phone = COALESCE(EXCLUDED.whatsapp_phone, user_onboarding.whatsapp_phone), + channel_offered_at = COALESCE(user_onboarding.channel_offered_at, now()), + updated_at = now() + RETURNING *`, + [userId, phone || null] + ); + record = insertRes.rows[0]; + } else if (phone && !existing.whatsapp_phone) { + const updateRes = await c.query( + `UPDATE user_onboarding + SET whatsapp_phone = $2, + channel_offered_at = COALESCE(channel_offered_at, now()), + updated_at = now() + WHERE id = $1 RETURNING *`, + [existing.id, phone] + ); + record = updateRes.rows[0]; + } + + return { + ok: true, + record, + channelUrl: whatsappChannelUrl(), + offered: true + }; +} + +/** + * Tracks attendee user actions on community channels (e.g. clicking "Follow Channel" or "Join Community"). + * Preserves the invariant: tracks that the action was clicked, but never falsely claims channel membership. + */ +export async function trackOnboardingAction({ + userId, + channel, + action, + metadata = {}, + c = db +}) { + if (!userId || !channel || !action) { + throw new HttpError(400, 'invalid_params', 'userId, channel, and action are required'); + } + + if (!['telegram', 'whatsapp'].includes(channel)) { + throw new HttpError(400, 'invalid_channel', 'channel must be telegram or whatsapp'); + } + + if (!['channel_clicked', 'channel_dismissed'].includes(action)) { + throw new HttpError(400, 'invalid_action', 'action must be channel_clicked or channel_dismissed'); + } + + const existing = (await c.query( + `SELECT * FROM user_onboarding WHERE user_id = $1 AND channel = $2 FOR UPDATE`, + [userId, channel] + )).rows[0]; + + if (!existing) { + const inserted = (await c.query( + `INSERT INTO user_onboarding ( + user_id, channel, status, channel_offered_at, + channel_clicked_at, metadata, created_at, updated_at + ) VALUES ( + $1, $2, $3, now(), + CASE WHEN $3 = 'channel_clicked' THEN now() ELSE NULL END, + $4, now(), now() + ) RETURNING *`, + [userId, channel, action, JSON.stringify(metadata)] + )).rows[0]; + return { ok: true, record: inserted }; + } + + const newStatus = action === 'channel_clicked' ? 'channel_clicked' : existing.status; + const clickedAt = action === 'channel_clicked' ? 'now()' : 'channel_clicked_at'; + + const updated = (await c.query( + `UPDATE user_onboarding + SET status = $2, + channel_clicked_at = COALESCE(channel_clicked_at, ${clickedAt}), + metadata = metadata || $3::jsonb, + updated_at = now() + WHERE id = $1 RETURNING *`, + [existing.id, newStatus, JSON.stringify(metadata)] + )).rows[0]; + + return { ok: true, record: updated }; +} + +/** + * Retrieve onboarding state for a user. + */ +export async function getOnboardingState(userId, c = db) { + if (!userId) return { telegram: null, whatsapp: null }; + + const { rows } = await c.query( + `SELECT * FROM user_onboarding WHERE user_id = $1`, + [userId] + ); + + const tg = rows.find((r) => r.channel === 'telegram') || null; + const wa = rows.find((r) => r.channel === 'whatsapp') || null; + + return { + telegram: tg ? { + status: tg.status, + welcomeSent: Boolean(tg.welcome_sent_at), + welcomeSentAt: tg.welcome_sent_at, + channelOfferedAt: tg.channel_offered_at, + channelClickedAt: tg.channel_clicked_at, + membershipVerified: tg.membership_verified, + communityUrl: telegramCommunityUrl() + } : { + status: 'unregistered', + welcomeSent: false, + communityUrl: telegramCommunityUrl() + }, + whatsapp: wa ? { + status: wa.status, + channelOffered: Boolean(wa.channel_offered_at), + channelOfferedAt: wa.channel_offered_at, + channelClicked: Boolean(wa.channel_clicked_at), + channelClickedAt: wa.channel_clicked_at, + channelUrl: whatsappChannelUrl() + } : { + status: 'unregistered', + channelOffered: false, + channelClicked: false, + channelUrl: whatsappChannelUrl() + } + }; +} + +/** + * Admin view of community onboarding audits and metrics. + * Masks PII to protect user privacy from unauthorized eyes. + */ +export async function listOnboardingAudits({ + limit = 50, + offset = 0, + channel = null, + c = db +} = {}) { + const params = []; + let where = 'TRUE'; + + if (channel && ['telegram', 'whatsapp'].includes(channel)) { + params.push(channel); + where = `o.channel = $${params.length}`; + } + + params.push(Math.min(Number(limit) || 50, 200)); + const limitIdx = params.length; + + params.push(Math.max(Number(offset) || 0, 0)); + const offsetIdx = params.length; + + const { rows } = await c.query( + `SELECT o.id, o.user_id, o.channel, o.status, + o.welcome_sent_at, o.channel_offered_at, o.channel_clicked_at, + o.membership_verified, o.created_at, + u.alias, + o.telegram_user_id, + o.whatsapp_phone + FROM user_onboarding o + JOIN users u ON u.id = o.user_id + WHERE ${where} + ORDER BY o.created_at DESC + LIMIT $${limitIdx} OFFSET $${offsetIdx}`, + params + ); + + // Mask PII for privacy protection + const sanitized = rows.map((r) => ({ + id: r.id, + userId: r.user_id, + userAlias: r.alias || 'Guest User', + channel: r.channel, + status: r.status, + welcomeSentAt: r.welcome_sent_at, + channelOfferedAt: r.channel_offered_at, + channelClickedAt: r.channel_clicked_at, + membershipVerified: r.membership_verified, + createdAt: r.created_at, + phoneMasked: r.whatsapp_phone ? maskPhone(r.whatsapp_phone) : null, + telegramUserId: r.telegram_user_id ? String(r.telegram_user_id) : null + })); + + // Aggregated stats + const statsRes = await c.query( + `SELECT + COUNT(*)::int AS total_records, + COUNT(*) FILTER (WHERE channel = 'telegram')::int AS telegram_total, + COUNT(*) FILTER (WHERE channel = 'whatsapp')::int AS whatsapp_total, + COUNT(*) FILTER (WHERE welcome_sent_at IS NOT NULL)::int AS welcome_sent_count, + COUNT(*) FILTER (WHERE channel_offered_at IS NOT NULL)::int AS channel_offered_count, + COUNT(*) FILTER (WHERE channel_clicked_at IS NOT NULL)::int AS channel_clicked_count, + COUNT(*) FILTER (WHERE membership_verified = true)::int AS membership_verified_count + FROM user_onboarding` + ); + + return { + records: sanitized, + metrics: statsRes.rows[0] || { + total_records: 0, + telegram_total: 0, + whatsapp_total: 0, + welcome_sent_count: 0, + channel_offered_count: 0, + channel_clicked_count: 0, + membership_verified_count: 0 + } + }; +} diff --git a/lib/telegram/bot.js b/lib/telegram/bot.js index b79945d..c8258b8 100644 --- a/lib/telegram/bot.js +++ b/lib/telegram/bot.js @@ -9,6 +9,7 @@ import { inviteForBooking, onChatMemberJoined } from '../services/invites.js'; import { deliverMany } from '../services/notifications.js'; import { claimOrder, startClaimPrompt, isClaimPromptOpen, CLAIM_LIMIT_PER_HOUR } from '../services/claims.js'; import { claimUpiBooking } from '../services/upi-payments.js'; +import { registerTelegramOnboarding } from '../services/community-onboarding.js'; import { rateLimit } from '../ratelimit.js'; import { eventPath } from '../views/components.js'; import { logger } from '../logger.js'; @@ -47,6 +48,12 @@ function supportLine() { async function cmdStart(msg, user, param) { const chat = msg.chat.id; + await registerTelegramOnboarding({ + userId: user.id, + telegramUserId: user.telegram_user_id || msg.from?.id, + botStarted: false + }).catch((err) => logger.warn('telegram onboarding registration on /start failed', { error: err.message })); + if (param?.startsWith('link_')) { const token = param.slice(5); const r = await redeemAccountLinkToken(token, msg.from); diff --git a/migrations/025_community_onboarding.sql b/migrations/025_community_onboarding.sql new file mode 100644 index 0000000..d62fbc5 --- /dev/null +++ b/migrations/025_community_onboarding.sql @@ -0,0 +1,27 @@ +-- migrations/025_community_onboarding.sql +-- Automated community onboarding tracking for Telegram and WhatsApp identities. +-- Idempotent, privacy-preserving, and additive only. + +CREATE TABLE IF NOT EXISTS user_onboarding ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + channel TEXT NOT NULL, -- 'telegram' or 'whatsapp' + status TEXT NOT NULL DEFAULT 'registered', -- 'registered', 'welcome_sent', 'channel_offered', 'channel_clicked', 'completed' + telegram_user_id BIGINT, + whatsapp_phone TEXT, + welcome_sent_at TIMESTAMPTZ, + channel_offered_at TIMESTAMPTZ, + channel_clicked_at TIMESTAMPTZ, + membership_verified BOOLEAN NOT NULL DEFAULT false, + membership_checked_at TIMESTAMPTZ, + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (user_id, channel) +); + +CREATE INDEX IF NOT EXISTS idx_user_onboarding_user ON user_onboarding(user_id); +CREATE INDEX IF NOT EXISTS idx_user_onboarding_channel_status ON user_onboarding(channel, status); +CREATE INDEX IF NOT EXISTS idx_user_onboarding_tg_user ON user_onboarding(telegram_user_id) WHERE telegram_user_id IS NOT NULL; +CREATE INDEX IF NOT EXISTS idx_user_onboarding_wa_phone ON user_onboarding(whatsapp_phone) WHERE whatsapp_phone IS NOT NULL; +CREATE INDEX IF NOT EXISTS idx_user_onboarding_created ON user_onboarding(created_at DESC); diff --git a/test/community-onboarding.test.js b/test/community-onboarding.test.js new file mode 100644 index 0000000..ce60bce --- /dev/null +++ b/test/community-onboarding.test.js @@ -0,0 +1,215 @@ +// test/community-onboarding.test.js - Community onboarding lifecycle, idempotency, +// official community/channel tracking, and admin audits. + +import { test, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { db, resetDb, Client, signedInClient, calls, startServer, stopServer } from './helpers.js'; +import { + registerTelegramOnboarding, + registerWhatsAppOnboarding, + trackOnboardingAction, + getOnboardingState, + listOnboardingAudits +} from '../lib/services/community-onboarding.js'; +import { telegramCommunityUrl, whatsappChannelUrl } from '../lib/config.js'; + +before(async () => { + await resetDb(); + await startServer(); +}); + +after(stopServer); + +beforeEach(async () => { + await resetDb(); + calls.length = 0; +}); + +test('Telegram Onboarding: registration saves verified numeric Telegram user ID and is idempotent', async () => { + const u = (await db.query( + `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status) + VALUES (777000111, 'alex_nightlife', true, now(), 'active') RETURNING *` + )).rows[0]; + + // 1. Initial registration without bot authorization + const reg1 = await registerTelegramOnboarding({ + userId: u.id, + telegramUserId: u.telegram_user_id, + botStarted: false + }); + + assert.equal(reg1.ok, true); + assert.equal(reg1.welcomeSent, false); + assert.equal(reg1.record.channel, 'telegram'); + assert.equal(reg1.record.status, 'registered'); + assert.equal(String(reg1.record.telegram_user_id), '777000111'); + + // 2. Duplicate registration (e.g. repeated login) is idempotent and never creates duplicate rows + const reg2 = await registerTelegramOnboarding({ + userId: u.id, + telegramUserId: u.telegram_user_id, + botStarted: false + }); + + assert.equal(reg2.ok, true); + assert.equal(reg2.record.id, reg1.record.id); + + const { rows } = await db.query(`SELECT * FROM user_onboarding WHERE user_id = $1`, [u.id]); + assert.equal(rows.length, 1); +}); + +test('Telegram Onboarding: sends welcome message with community invite ONLY after bot is started', async () => { + const u = (await db.query( + `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status) + VALUES (888000222, 'clubber_sam', true, now(), 'active') RETURNING *` + )).rows[0]; + + // User authorizes / starts bot + const reg = await registerTelegramOnboarding({ + userId: u.id, + telegramUserId: u.telegram_user_id, + botStarted: true + }); + + assert.equal(reg.ok, true); + assert.equal(reg.welcomeSent, true); + + // Check calls recorded by test harness + const msgCalls = calls.filter((c) => c.api === 'telegram' && c.method === 'sendMessage'); + assert.equal(msgCalls.length, 1); + const sentPayload = msgCalls[0].params; + assert.equal(sentPayload.chat_id, 888000222); + assert.match(sentPayload.text, /Welcome to NIGHTLIFEZ<\/b>/); + assert.match(sentPayload.text, /official community channel/); + + // Verify inline buttons include official community link and web app action + const buttons = sentPayload.reply_markup?.inline_keyboard || []; + assert.ok(buttons.length >= 2); + const joinBtn = buttons[0][0]; + assert.equal(joinBtn.text, 'Join NIGHTLIFEZ Community'); + assert.equal(joinBtn.url, telegramCommunityUrl()); + + // Verify database record has welcome_sent_at and membership status + const row = (await db.query(`SELECT * FROM user_onboarding WHERE user_id = $1`, [u.id])).rows[0]; + assert.ok(row.welcome_sent_at); + assert.equal(row.status, 'welcome_sent'); + + // Second login with botStarted=true MUST NOT send welcome message again (no spam) + calls.length = 0; + const regRepeat = await registerTelegramOnboarding({ + userId: u.id, + telegramUserId: u.telegram_user_id, + botStarted: true + }); + + assert.equal(regRepeat.welcomeSent, true); + const repeatMsgCalls = calls.filter((c) => c.api === 'telegram' && c.method === 'sendMessage'); + assert.equal(repeatMsgCalls.length, 0, 'repeated login must never re-dispatch welcome message'); +}); + +test('WhatsApp Onboarding: registers verified phone and presents optional follow channel action', async () => { + const phone = '+919876543210'; + const u = (await db.query( + `INSERT INTO users (phone, alias, age_confirmed_21, age_confirmed_at, status) + VALUES ($1, 'priya_blore', true, now(), 'active') RETURNING *`, + [phone] + )).rows[0]; + + const reg = await registerWhatsAppOnboarding({ + userId: u.id, + phone + }); + + assert.equal(reg.ok, true); + assert.equal(reg.channelUrl, whatsappChannelUrl()); + assert.equal(reg.offered, true); + assert.equal(reg.record.channel, 'whatsapp'); + assert.equal(reg.record.status, 'channel_offered'); + assert.ok(reg.record.channel_offered_at); + assert.equal(reg.record.membership_verified, false, 'must not falsely claim channel membership on offer'); +}); + +test('Community Onboarding Tracking: tracks channel follow click without falsely claiming membership', async () => { + const u = (await db.query( + `INSERT INTO users (phone, alias, age_confirmed_21, age_confirmed_at, status) + VALUES ('+919123456780', 'rohan_chennai', true, now(), 'active') RETURNING *` + )).rows[0]; + + await registerWhatsAppOnboarding({ userId: u.id, phone: u.phone }); + + // User clicks the Follow WhatsApp Channel button + const track = await trackOnboardingAction({ + userId: u.id, + channel: 'whatsapp', + action: 'channel_clicked', + metadata: { source: 'signin_modal', device: 'mobile' } + }); + + assert.equal(track.ok, true); + assert.equal(track.record.status, 'channel_clicked'); + assert.ok(track.record.channel_clicked_at); + assert.equal(track.record.membership_verified, false, 'must never falsely claim membership after click'); + + // Verify getOnboardingState returns correct status + const state = await getOnboardingState(u.id); + assert.equal(state.whatsapp.channelClicked, true); + assert.equal(state.whatsapp.channelUrl, whatsappChannelUrl()); +}); + +test('Attendee HTTP Endpoints: GET /api/me/onboarding and POST /api/onboarding/track', async () => { + const c = await signedInClient(); + + // 1. Check initial onboarding state + const getRes = await c.get('/api/me/onboarding'); + assert.equal(getRes.status, 200); + assert.ok(getRes.json.ok); + assert.ok(getRes.json.onboarding); + assert.ok(getRes.json.onboarding.telegram); + assert.ok(getRes.json.onboarding.whatsapp); + + // 2. Track clicking community join action + const postRes = await c.post('/api/onboarding/track', { + channel: 'whatsapp', + action: 'channel_clicked' + }); + assert.equal(postRes.status, 200); + assert.equal(postRes.json.ok, true); + + // 3. Confirm updated state + const updatedRes = await c.get('/api/me/onboarding'); + assert.equal(updatedRes.json.onboarding.whatsapp.channelClicked, true); +}); + +test('Admin Visibility & Privacy: GET /api/admin/onboarding masks PII and aggregates metrics', async () => { + // Seed sample onboarding records + const u1 = (await db.query( + `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status) + VALUES (555111, 'attendee_1', true, now(), 'active') RETURNING *` + )).rows[0]; + + const u2 = (await db.query( + `INSERT INTO users (phone, alias, age_confirmed_21, age_confirmed_at, status) + VALUES ('+919876543210', 'attendee_2', true, now(), 'active') RETURNING *` + )).rows[0]; + + await registerTelegramOnboarding({ userId: u1.id, telegramUserId: 555111, botStarted: true }); + await registerWhatsAppOnboarding({ userId: u2.id, phone: '+919876543210' }); + await trackOnboardingAction({ userId: u2.id, channel: 'whatsapp', action: 'channel_clicked' }); + + // Sign in as admin + const adminClient = await signedInClient({ tgId: 900000001 }); + assert.equal((await adminClient.get('/api/admin/session')).json.role, 'super_admin'); + + const res = await adminClient.get('/api/admin/onboarding'); + assert.equal(res.status, 200); + assert.equal(res.json.ok, true); + assert.ok(res.json.records.length >= 2); + assert.ok(res.json.metrics); + assert.ok(res.json.metrics.total_records >= 2); + + // Verify privacy: phone number is masked! + const waRecord = res.json.records.find((r) => r.channel === 'whatsapp'); + assert.ok(waRecord); + assert.equal(waRecord.phoneMasked, '+91 98****3210'); + assert.equal(waRecord.whatsapp_phone, undefined, 'Raw phone must never be exposed'); +}); diff --git a/test/helpers.js b/test/helpers.js index 7cd68e9..fa1529c 100644 --- a/test/helpers.js +++ b/test/helpers.js @@ -4,6 +4,7 @@ import crypto from 'node:crypto'; export const BOT_TOKEN = '123456789:TEST_ONLY_token_abcdefghijklmnopqrstuvwxyz'; Object.assign(process.env, { + TEST_DATABASE_URL: process.env.TEST_DATABASE_URL || process.env.DATABASE_URL || 'postgres://localhost:5432/sm_test', SKIP_DOTENV: 'true', DATABASE_URL: process.env.TEST_DATABASE_URL || process.env.DATABASE_URL || 'postgres://localhost:5432/sm_test', SESSION_SECRET: 'test-session-secret-0123456789-abcdefghij', diff --git a/test/migrations.test.js b/test/migrations.test.js index 27ba22f..fe7a3f4 100644 --- a/test/migrations.test.js +++ b/test/migrations.test.js @@ -20,13 +20,13 @@ test('migration files inventory: sequential numbering, correct naming, and sorte .filter((f) => /^\d+_.*\.sql$/.test(f)) .sort(); - // Exactly 22 migrations currently exist: 003 through 024 - assert.equal(files.length, 22, `expected 22 migration files, got ${files.length}: ${files.join(', ')}`); + // Exactly 23 migrations currently exist: 003 through 025 + assert.equal(files.length, 23, `expected 23 migration files, got ${files.length}: ${files.join(', ')}`); // Verify sequential ordering const expectedPrefixes = [ '003_', '004_', '005_', '006_', '007_', '008_', - '009_', '010_', '011_', '012_', '013_', '014_', '015_', '016_', '017_', '018_', '019_', '020_', '021_', '022_', '023_', '024_' + '009_', '010_', '011_', '012_', '013_', '014_', '015_', '016_', '017_', '018_', '019_', '020_', '021_', '022_', '023_', '024_', '025_' ]; for (let i = 0; i < expectedPrefixes.length; i++) { assert.ok( @@ -45,9 +45,9 @@ test('migration idempotency: re-running migrate() on an up-to-date database appl assert.deepEqual(thirdRun, [], 'expected zero migrations applied on third run'); }); -test('schema_migrations table records all 22 migrations in correct order', async () => { +test('schema_migrations table records all 23 migrations in correct order', async () => { const { rows } = await db.query('SELECT name, applied_at FROM schema_migrations ORDER BY name ASC'); - assert.equal(rows.length, 22); + assert.equal(rows.length, 23); const appliedNames = rows.map((r) => r.name); const filesOnDisk = fs.readdirSync(MIGRATIONS_DIR) @@ -74,9 +74,9 @@ test('advisory lock serializes concurrent migrate() calls', async () => { assert.deepEqual(res2, []); assert.deepEqual(res3, []); - // Total count in schema_migrations must remain exactly 22 + // Total count in schema_migrations must remain exactly 23 const countRes = await db.one('SELECT count(*)::int AS n FROM schema_migrations'); - assert.equal(countRes.n, 22); + assert.equal(countRes.n, 23); }); test('migration policy respects environment boundaries', () => { diff --git a/test/production-quality-assurance.test.js b/test/production-quality-assurance.test.js new file mode 100644 index 0000000..484c151 --- /dev/null +++ b/test/production-quality-assurance.test.js @@ -0,0 +1,556 @@ +// test/production-quality-assurance.test.js - Production Quality Assurance Suite +// Covers all 13 real-user journeys for Nightlifez: +// 1. New user signs up through Telegram +// 2. Existing user signs in through Telegram +// 3. A different Telegram account signs in from another browser session +// 4. New user signs up through WhatsApp OTP +// 5. Existing user signs in through WhatsApp OTP +// 6. User links both identities to one account securely +// 7. Telegram welcome message and community invite +// 8. WhatsApp channel opt-in +// 9. Free event booking +// 10. Paid UPI checkout and verified payment callback +// 11. Duplicate callback and duplicate payment protection +// 12. Failed payment, expired payment and refund +// 13. Admin can inspect the resulting audit trail + +import { test, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import { db, resetDb, Client, signedInClient, calls, startServer, stopServer, createEvent } from './helpers.js'; +import { getWhatsAppProvider } from '../lib/services/whatsapp-provider.js'; +import { + createUpiPaymentIntent, + processUpiWebhook, + applySuccessfulUpiPayment, + getUpiPaymentStatus, + refundUpiOrder +} from '../lib/services/upi-payments.js'; +import { PhonePeAdapter } from '../lib/upi/adapter.js'; +import { telegramCommunityUrl, whatsappChannelUrl } from '../lib/config.js'; +import { registerTelegramOnboarding } from '../lib/services/community-onboarding.js'; + +before(async () => { + await resetDb(); + await startServer(); +}); + +after(stopServer); + +beforeEach(async () => { + await resetDb(); + calls.length = 0; + getWhatsAppProvider().clearSentMessages(); +}); + +// Journey 1: New user signs up through Telegram +test('Journey 1: New user signs up through Telegram', async () => { + const tgId = 1122334455; + const client = await signedInClient({ tgId }); + const meRes = await client.get('/api/me'); + assert.equal(meRes.status, 200); + assert.equal(meRes.json.ok, true); + assert.ok(meRes.json.user.alias); + assert.equal(meRes.json.user.ageConfirmed, true); + + // Verify database state: numeric Telegram user ID is saved + const user = (await db.query(`SELECT * FROM users WHERE telegram_user_id = $1`, [tgId])).rows[0]; + assert.ok(user); + assert.equal(String(user.telegram_user_id), String(tgId)); + assert.equal(user.status, 'active'); + + // Verify user_identities record exists + const identity = (await db.query(`SELECT * FROM user_identities WHERE user_id = $1 AND provider = 'telegram'`, [user.id])).rows[0]; + assert.ok(identity); + assert.equal(identity.subject, String(tgId)); + + // Verify Telegram community onboarding record is registered + const onboarding = (await db.query(`SELECT * FROM user_onboarding WHERE user_id = $1 AND channel = 'telegram'`, [user.id])).rows[0]; + assert.ok(onboarding); + assert.equal(String(onboarding.telegram_user_id), String(tgId)); +}); + +// Journey 2: Existing user signs in through Telegram +test('Journey 2: Existing user signs in through Telegram', async () => { + const tgId = 2233445566; + // First sign-in + const client1 = await signedInClient({ tgId }); + const user1 = (await db.query(`SELECT * FROM users WHERE telegram_user_id = $1`, [tgId])).rows[0]; + + // Second sign-in with fresh browser session + const client2 = await signedInClient({ tgId }); + const meRes = await client2.get('/api/me'); + assert.equal(meRes.status, 200); + assert.equal(meRes.json.user.alias, user1.alias); + + // Verify no duplicate account was created + const users = (await db.query(`SELECT * FROM users WHERE telegram_user_id = $1`, [tgId])).rows; + assert.equal(users.length, 1); + assert.equal(users[0].id, user1.id); +}); + +// Journey 3: A different Telegram account signs in from another browser session +test('Journey 3: A different Telegram account signs in from another browser session', async () => { + const clientA = await signedInClient({ tgId: 3001 }); + const clientB = await signedInClient({ tgId: 3002 }); + + const meA = await clientA.get('/api/me'); + const meB = await clientB.get('/api/me'); + + assert.ok(meA.json.user.alias); + assert.ok(meB.json.user.alias); + assert.notEqual(meA.json.user.alias, meB.json.user.alias); + + // Strict session and data isolation + const userA = (await db.query(`SELECT id FROM users WHERE telegram_user_id = 3001`)).rows[0]; + const userB = (await db.query(`SELECT id FROM users WHERE telegram_user_id = 3002`)).rows[0]; + assert.notEqual(userA.id, userB.id); +}); + +// Journey 4: New user signs up through WhatsApp OTP +test('Journey 4: New user signs up through WhatsApp OTP', async () => { + const c = new Client(); + const phone = '+919876543201'; + + // 1. Request OTP + const otpRes = await c.post('/api/auth/whatsapp/otp', { phone, promotionalOptIn: true }); + assert.equal(otpRes.status, 200); + assert.equal(otpRes.json.ok, true); + assert.ok(otpRes.json.challengeId); + assert.equal(otpRes.json.phoneMasked, '+91 98****3201'); + + // Retrieve OTP from stub provider + const sent = getWhatsAppProvider().getSentMessages(); + assert.ok(sent.length >= 1); + const otp = sent[sent.length - 1].otp; + assert.match(otp, /^\d{6}$/); + + // 2. Verify OTP + const verifyRes = await c.post('/api/auth/whatsapp/verify', { + challengeId: otpRes.json.challengeId, + phone, + code: otp, + promotionalOptIn: true + }); + + assert.equal(verifyRes.status, 200); + assert.equal(verifyRes.json.ok, true); + assert.equal(verifyRes.json.isNewUser, true); + assert.ok(verifyRes.json.onboarding); + assert.equal(verifyRes.json.onboarding.channelUrl, whatsappChannelUrl()); + + // Verify database record + const user = (await db.query(`SELECT * FROM users WHERE phone = $1`, [phone])).rows[0]; + assert.ok(user); + assert.equal(user.phone, phone); + assert.equal(user.status, 'active'); + + // Verify communication consents: both transactional and promotional + const consents = (await db.query(`SELECT purpose, status FROM communication_consents WHERE user_id = $1`, [user.id])).rows; + assert.equal(consents.length, 2); + const promo = consents.find((c) => c.purpose === 'promotional'); + assert.equal(promo.status, 'opted_in'); + + // Verify WhatsApp onboarding record + const onboarding = (await db.query(`SELECT * FROM user_onboarding WHERE user_id = $1 AND channel = 'whatsapp'`, [user.id])).rows[0]; + assert.ok(onboarding); + assert.equal(onboarding.status, 'channel_offered'); +}); + +// Journey 5: Existing user signs in through WhatsApp OTP +test('Journey 5: Existing user signs in through WhatsApp OTP', async () => { + const phone = '+919876543202'; + // Seed user + const u = (await db.query( + `INSERT INTO users (phone, alias, age_confirmed_21, age_confirmed_at, status) + VALUES ($1, 'kavya_m', true, now(), 'active') RETURNING *`, + [phone] + )).rows[0]; + + const c = new Client(); + const req = await c.post('/api/auth/whatsapp/otp', { phone }); + const otp = getWhatsAppProvider().getSentMessages().slice(-1)[0].otp; + + const verify = await c.post('/api/auth/whatsapp/verify', { + challengeId: req.json.challengeId, + phone, + code: otp + }); + + assert.equal(verify.status, 200); + assert.equal(verify.json.isNewUser, false); + + const me = await c.get('/api/me'); + assert.equal(me.status, 200); + assert.equal(me.json.user.alias, 'kavya_m'); +}); + +// Journey 6: User links both identities to one account securely +test('Journey 6: User links both identities to one account securely', async () => { + const tgId = 4455667788; + const client = await signedInClient({ tgId }); + const phone = '+919876543203'; + + // Request link OTP + const linkOtpRes = await client.post('/api/auth/whatsapp/otp', { phone }); + const otp = getWhatsAppProvider().getSentMessages().slice(-1)[0].otp; + + // Link WhatsApp to signed-in Telegram account + const linkRes = await client.post('/api/auth/whatsapp/link', { + challengeId: linkOtpRes.json.challengeId, + phone, + code: otp + }); + assert.equal(linkRes.status, 200); + assert.equal(linkRes.json.ok, true); + + // Verify identities: both telegram and phone belong to single account + const identRes = await client.get('/api/me/identities'); + assert.equal(identRes.status, 200); + assert.equal(identRes.json.identities.telegram.linked, true); + assert.equal(identRes.json.identities.whatsapp.linked, true); + assert.equal(identRes.json.identities.whatsapp.phoneMasked, '+91 98****3203'); + + // Conflict test: Another account trying to link this same phone must be rejected with 409 + const clientOther = await signedInClient({ tgId: 999999 }); + const attackOtpRes = await clientOther.post('/api/auth/whatsapp/otp', { phone }); + const attackOtp = getWhatsAppProvider().getSentMessages().slice(-1)[0].otp; + + const conflictRes = await clientOther.post('/api/auth/whatsapp/link', { + challengeId: attackOtpRes.json.challengeId, + phone, + code: attackOtp + }); + assert.equal(conflictRes.status, 409); + assert.equal(conflictRes.json.error, 'phone_already_linked'); + + // Sole-provider unlinking guard: User cannot disconnect Telegram if WhatsApp were the only provider, + // and when both are linked, unlinking one leaves the other intact + const unlinkRes = await client.post('/api/auth/whatsapp/unlink', { phone }); + assert.equal(unlinkRes.status, 200); + assert.equal(unlinkRes.json.ok, true); + + const identAfter = await client.get('/api/me/identities'); + assert.equal(identAfter.json.identities.whatsapp.linked, false); + assert.equal(identAfter.json.identities.telegram.linked, true); +}); + +// Journey 7: Telegram welcome message and community invite +test('Journey 7: Telegram welcome message and community invite', async () => { + const tgId = 5566778899; + const user = (await db.query( + `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status) + VALUES ($1, 'diya_k', true, now(), 'active') RETURNING *`, + [tgId] + )).rows[0]; + + // User authorizes bot + const reg = await registerTelegramOnboarding({ + userId: user.id, + telegramUserId: tgId, + botStarted: true + }); + assert.equal(reg.ok, true); + assert.equal(reg.welcomeSent, true); + + const welcomeCalls = calls.filter((c) => c.api === 'telegram' && c.method === 'sendMessage'); + assert.equal(welcomeCalls.length, 1); + assert.equal(welcomeCalls[0].params.chat_id, tgId); + assert.match(welcomeCalls[0].params.text, /Welcome to NIGHTLIFEZ<\/b>/); + + const btn = welcomeCalls[0].params.reply_markup?.inline_keyboard?.[0]?.[0]; + assert.equal(btn.text, 'Join NIGHTLIFEZ Community'); + assert.equal(btn.url, telegramCommunityUrl()); +}); + +// Journey 8: WhatsApp channel opt-in +test('Journey 8: WhatsApp channel opt-in', async () => { + const client = await signedInClient(); + const trackRes = await client.post('/api/onboarding/track', { + channel: 'whatsapp', + action: 'channel_clicked' + }); + assert.equal(trackRes.status, 200); + assert.equal(trackRes.json.ok, true); + assert.equal(trackRes.json.record.status, 'channel_clicked'); + assert.equal(trackRes.json.record.membership_verified, false, 'clicking channel must not claim verified membership'); +}); + +// Journey 9: Free event booking +test('Journey 9: Free event booking', async () => { + const client = await signedInClient({ tgId: 6677889900 }); + const event = await createEvent({ title: 'Bangalore Tech Mixer', price: null }); + await db.query(`UPDATE events SET ticketing = 'tiers' WHERE id = $1`, [event.id]); + + const tier = (await db.query( + `INSERT INTO ticket_types (event_id, name, kind, price_paise, quantity, active) + VALUES ($1, 'General Admission', 'free', 0, 50, true) RETURNING *`, + [event.id] + )).rows[0]; + + const bookRes = await client.post(`/api/events/${event.id}/book`, { + ticketTypeId: tier.id, + quantity: 1 + }); + assert.equal(bookRes.status, 200); + assert.equal(bookRes.json.ok, true); + assert.equal(bookRes.json.status, 'confirmed'); + assert.ok(bookRes.json.bookingId); + + // Verify single-use ticket issued with QR code + const ticketRes = await client.get(`/api/me/bookings/${bookRes.json.bookingId}/ticket`); + assert.equal(ticketRes.status, 200); + assert.equal(ticketRes.json.ok, true); + assert.ok(ticketRes.json.tickets && ticketRes.json.tickets.length >= 1); + assert.ok(ticketRes.json.tickets[0].ticketCode); + assert.ok(ticketRes.json.tickets[0].qrSvg); +}); + +// Journey 10: Paid UPI checkout and verified payment callback +test('Journey 10: Paid UPI checkout and verified payment callback', async () => { + const prevUpi = process.env.UPI_CHECKOUT_ENABLED; + process.env.UPI_CHECKOUT_ENABLED = 'true'; + try { + const user = (await db.query( + `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status) + VALUES (7788990011, 'siddharth_p', true, now(), 'active') RETURNING *` + )).rows[0]; + + const event = await createEvent({ + title: 'South India Rooftop Sundowner', + price_status: 'set', + ticket_price_paise: 150000, + checkout_mode: 'upi_direct' + }); + + const tier = (await db.query( + `INSERT INTO ticket_types (event_id, name, kind, price_paise, quantity, active) + VALUES ($1, 'Early Bird Pass', 'paid', 150000, 20, true) RETURNING *`, + [event.id] + )).rows[0]; + + // Create payment intent + const intent = await createUpiPaymentIntent({ + slug: event.slug, + user, + ticketTypeId: tier.id, + quantity: 1, + deviceType: 'desktop' + }); + + assert.ok(intent.orderId); + assert.equal(intent.amountPaise, 150000); + assert.equal(intent.currency, 'INR'); + + // Simulate authentic server-to-server webhook callback + const adapter = new PhonePeAdapter({ merchantId: 'PGTESTPAYUAT', saltKey: 'test_salt_key', saltIndex: '1' }); + const webhookPayload = { + response: Buffer.from(JSON.stringify({ + code: 'PAYMENT_SUCCESS', + data: { + merchantId: 'PGTESTPAYUAT', + merchantTransactionId: intent.orderId, + transactionId: `TXN-${intent.orderId}`, + amount: 150000, + currency: 'INR', + state: 'COMPLETED', + paymentInstrument: { utr: 'UTR123456789012' } + } + })).toString('base64') + }; + + const signature = adapter.signRequest(webhookPayload.response, ''); + const headers = { 'x-verify': `${signature.split('###')[0]}###1` }; + + // Apply verified payment + const result = await applySuccessfulUpiPayment({ + orderId: intent.orderId, + providerTxnId: `TXN-${intent.orderId}`, + providerPaymentId: 'UTR123456789012', + verifiedAmountPaise: 150000, + currency: 'INR', + merchantId: 'PGTESTPAYUAT', + actor: 'webhook:phonepe' + }); + + assert.equal(result.status, 'succeeded'); + assert.ok(result.bookingId); + + // Verify booking is confirmed and ticket is issued + const booking = (await db.query(`SELECT * FROM bookings WHERE id = $1`, [result.bookingId])).rows[0]; + assert.equal(booking.status, 'confirmed'); + assert.equal(booking.amount_paise, 150000); + + const tickets = (await db.query(`SELECT * FROM tickets WHERE booking_id = $1`, [result.bookingId])).rows; + assert.equal(tickets.length, 1); + assert.equal(tickets[0].status, 'valid'); + + // Verify payment audit record + const audits = (await db.query(`SELECT * FROM payment_audits WHERE order_id = $1 ORDER BY created_at ASC`, [intent.orderId])).rows; + assert.ok(audits.length >= 1); + assert.equal(audits[audits.length - 1].to_status, 'succeeded'); + } finally { + process.env.UPI_CHECKOUT_ENABLED = prevUpi; + } +}); + +// Journey 11: Duplicate callback and duplicate payment protection +test('Journey 11: Duplicate callback and duplicate payment protection', async () => { + const prevUpi = process.env.UPI_CHECKOUT_ENABLED; + process.env.UPI_CHECKOUT_ENABLED = 'true'; + try { + const user = (await db.query( + `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status) + VALUES (8899001122, 'neha_k', true, now(), 'active') RETURNING *` + )).rows[0]; + + const event = await createEvent({ title: 'Cocktail Club', price_status: 'set', ticket_price_paise: 200000, checkout_mode: 'upi_direct' }); + const tier = (await db.query( + `INSERT INTO ticket_types (event_id, name, kind, price_paise, quantity, active) + VALUES ($1, 'VIP Entry', 'paid', 200000, 10, true) RETURNING *`, + [event.id] + )).rows[0]; + + const intent = await createUpiPaymentIntent({ + slug: event.slug, + user, + ticketTypeId: tier.id, + quantity: 1 + }); + + // 1. First payment confirmation + const firstConfirm = await applySuccessfulUpiPayment({ + orderId: intent.orderId, + providerPaymentId: 'UTR999999999', + verifiedAmountPaise: 200000, + currency: 'INR', + merchantId: 'PGTESTPAYUAT', + actor: 'webhook:phonepe' + }); + assert.equal(firstConfirm.status, 'succeeded'); + assert.ok(firstConfirm.bookingId); + + // 2. Duplicate callback for the exact same order + const dupConfirm = await applySuccessfulUpiPayment({ + orderId: intent.orderId, + providerPaymentId: 'UTR999999999', + verifiedAmountPaise: 200000, + currency: 'INR', + merchantId: 'PGTESTPAYUAT', + actor: 'webhook:phonepe' + }); + assert.equal(dupConfirm.duplicate, true); + assert.equal(dupConfirm.bookingId, firstConfirm.bookingId); + + // Verify bookings count remains exactly 1 + const { rows: bookings } = await db.query(`SELECT * FROM bookings WHERE user_id = $1 AND event_id = $2`, [user.id, event.id]); + assert.equal(bookings.length, 1); + } finally { + process.env.UPI_CHECKOUT_ENABLED = prevUpi; + } +}); + +// Journey 12: Failed payment, expired payment and refund +test('Journey 12: Failed payment, expired payment and refund', async () => { + const prevUpi = process.env.UPI_CHECKOUT_ENABLED; + process.env.UPI_CHECKOUT_ENABLED = 'true'; + try { + const user = (await db.query( + `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status) + VALUES (9900112233, 'arjun_v', true, now(), 'active') RETURNING *` + )).rows[0]; + + const event = await createEvent({ title: 'Goa Weekend Mixer', price_status: 'set', ticket_price_paise: 300000, checkout_mode: 'upi_direct' }); + const tier = (await db.query( + `INSERT INTO ticket_types (event_id, name, kind, price_paise, quantity, active) + VALUES ($1, 'Pass', 'paid', 300000, 10, true) RETURNING *`, + [event.id] + )).rows[0]; + + // A. Expired payment intent + const expiredIntent = await createUpiPaymentIntent({ slug: event.slug, user, ticketTypeId: tier.id, quantity: 1 }); + // Manually force expiration timestamp in DB + await db.query(`UPDATE payments SET expires_at = now() - interval '1 minute' WHERE order_id = $1`, [expiredIntent.orderId]); + + const statusCheck = await getUpiPaymentStatus(expiredIntent.orderId, { user }); + assert.equal(statusCheck.status, 'expired'); + + // B. Succeeded payment followed by admin refund + const refundIntent = await createUpiPaymentIntent({ slug: event.slug, user, ticketTypeId: tier.id, quantity: 1 }); + const confirm = await applySuccessfulUpiPayment({ + orderId: refundIntent.orderId, + providerPaymentId: 'UTR777888999', + verifiedAmountPaise: 300000, + currency: 'INR', + merchantId: 'PGTESTPAYUAT', + actor: 'webhook:phonepe' + }); + assert.equal(confirm.status, 'succeeded'); + + // Create finance admin + const adminRow = (await db.query( + `INSERT INTO admin_users (telegram_user_id, role, active) VALUES (900000001, 'super_admin', true) RETURNING *` + )).rows[0]; + + // Execute refund with documented evidence and external UTR ref + const refundRes = await refundUpiOrder(refundIntent.orderId, { + actor: `admin:${adminRow.id}:super_admin`, + reason: 'Attendee requested cancellation within policy window', + manualReconciliation: true, + externalRefundRef: 'UTR202611150001928374', + evidenceRef: 'SUPPORT-AUDIT-TICKET-101', + sessionAdmin: { id: adminRow.id, role: 'super_admin' } + }); + + assert.equal(refundRes.status, 'refunded'); + + // Verify payment and booking status in database + const payment = (await db.query(`SELECT * FROM payments WHERE order_id = $1`, [refundIntent.orderId])).rows[0]; + assert.equal(payment.status, 'refunded'); + assert.ok(payment.refunded_at); + + const booking = (await db.query(`SELECT * FROM bookings WHERE id = $1`, [confirm.bookingId])).rows[0]; + assert.equal(booking.status, 'refunded'); + } finally { + process.env.UPI_CHECKOUT_ENABLED = prevUpi; + } +}); + +// Journey 13: Admin can inspect the resulting audit trail +test('Journey 13: Admin can inspect the resulting audit trail', async () => { + const adminClient = await signedInClient({ tgId: 900000001 }); + assert.equal((await adminClient.get('/api/admin/session')).json.role, 'super_admin'); + + // 1. List payments with stats + const paymentsRes = await adminClient.get('/api/admin/payments'); + assert.equal(paymentsRes.status, 200); + assert.equal(paymentsRes.json.ok, true); + assert.ok(paymentsRes.json.payments); + assert.ok(paymentsRes.json.stats); + + // 2. Inspect payment audit trail for a specific transaction + const payment = (await db.query( + `INSERT INTO payments (provider, provider_txn_id, order_id, amount, currency, status, purpose, is_test) + VALUES ('phonepe', 'TXN-ORD-TEST-AUDIT-1', 'ORD-TEST-AUDIT-1', 100000, 'INR', 'succeeded', 'ticket', true) RETURNING *` + )).rows[0]; + + await db.query( + `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details) + VALUES ($1, $2, 'pending', 'succeeded', 'webhook:phonepe', '{"simulated": true}')`, + [payment.id, payment.order_id] + ); + + const auditRes = await adminClient.get(`/api/admin/payments/${payment.id}/audit`); + assert.equal(auditRes.status, 200); + assert.equal(auditRes.json.ok, true); + assert.equal(auditRes.json.audits.length, 1); + assert.equal(auditRes.json.audits[0].from_status, 'pending'); + assert.equal(auditRes.json.audits[0].to_status, 'succeeded'); + + // 3. Inspect community onboarding audits + const onboardRes = await adminClient.get('/api/admin/onboarding'); + assert.equal(onboardRes.status, 200); + assert.equal(onboardRes.json.ok, true); + assert.ok(onboardRes.json.records); + assert.ok(onboardRes.json.metrics); +});