diff --git a/e2e/wizard-tap-targets.spec.js b/e2e/wizard-tap-targets.spec.js index 1b2cd76..69f594a 100644 --- a/e2e/wizard-tap-targets.spec.js +++ b/e2e/wizard-tap-targets.spec.js @@ -43,6 +43,7 @@ for (const width of [320, 360, 375, 390, 430]) { // Features step: every switch. await page.getByRole('button', { name: /Next: Features/ }).click(); + await expect(page.getByRole('heading', { name: 'Ask guests questions' })).toBeVisible(); const switches = page.getByRole('switch'); expect(await switches.count()).toBeGreaterThanOrEqual(4); for (const s of await switches.all()) await expect.poll(async () => Math.min(...((await box(s)) ?? [0]))).toBeGreaterThanOrEqual(44); diff --git a/lib/handlers/auth.js b/lib/handlers/auth.js index 6f0a5c5..8298a06 100644 --- a/lib/handlers/auth.js +++ b/lib/handlers/auth.js @@ -435,16 +435,13 @@ export async function previewReviewerAuth({ req, res, query, ip }) { if (query && query.get('next')) next = safeNext(query.get('next')); // Ensure or fetch the synthetic reviewer user (guaranteed guest role, no admin/organiser escalation) - let user = await db.one('SELECT * FROM users WHERE telegram_user_id = $1', [REVIEWER_TG_ID]); - if (!user) { - user = (await db.query( - `INSERT INTO users (telegram_user_id, alias, display_name, age_confirmed_21, age_confirmed_at, status, bot_started, onboarding_completed, onboarding_step) - VALUES ($1, $2, $2, true, now(), 'active', true, true, 6) - ON CONFLICT (telegram_user_id) DO UPDATE SET age_confirmed_21 = true, status = 'active', onboarding_completed = true - RETURNING *`, - [REVIEWER_TG_ID, REVIEWER_ALIAS] - )).rows[0]; - } + const user = (await db.query( + `INSERT INTO users (telegram_user_id, alias, display_name, age_confirmed_21, age_confirmed_at, status, bot_started, onboarding_completed, onboarding_step) + VALUES ($1, $2, $2, true, now(), 'active', true, true, 6) + ON CONFLICT (telegram_user_id) DO UPDATE SET age_confirmed_21 = true, status = 'active', onboarding_completed = true + RETURNING *`, + [REVIEWER_TG_ID, REVIEWER_ALIAS] + )).rows[0]; if (user.status !== 'active') throw new HttpError(403, 'account_restricted', 'Reviewer account is not active'); const { csrf } = await startSession(req, res, user); diff --git a/lib/handlers/checkout.js b/lib/handlers/checkout.js index 4e2defa..5ff7dc8 100644 --- a/lib/handlers/checkout.js +++ b/lib/handlers/checkout.js @@ -14,7 +14,12 @@ export async function checkoutRedirect({ req, res, params, query, ip }) { if (req.method === 'HEAD') return redirect(res, `/events/${slug}`); await rateLimit(`co:${hashIp(ip)}`, 30, 600); - const ev = await db.one('SELECT checkout_mode FROM events WHERE slug = $1', [slug]); + const ev = await db.one('SELECT checkout_mode, payment_method, organiser_upi_id, organiser_payee_name FROM events WHERE slug = $1', [slug]); + const isDirectUpi = ev?.payment_method === 'direct_upi' || (Boolean(ev?.organiser_upi_id) && Boolean(ev?.organiser_payee_name)); + if (isDirectUpi) { + const qStr = query.toString() ? `?${query.toString()}` : ''; + return redirect(res, `/checkout/${slug}/upi${qStr}`); + } if (ev?.checkout_mode === 'upi_direct') { if (!upiCheckoutEnabled()) return redirect(res, `/events/${slug}`); const qStr = query.toString() ? `?${query.toString()}` : ''; diff --git a/lib/handlers/organiser.js b/lib/handlers/organiser.js index 9f30ef8..605fe1b 100644 --- a/lib/handlers/organiser.js +++ b/lib/handlers/organiser.js @@ -34,6 +34,11 @@ import { saveOrganiserPaymentSettings, deleteOrganiserPaymentSettings } from '../services/payment-settings.js'; +import { + listDirectUpiBookings, + confirmDirectUpiPayment, + rejectDirectUpiPayment +} from '../services/direct-upi.js'; const id = (v) => { if (!uuid.safeParse(v).success) throw new HttpError(404, 'not_found', 'Not found'); @@ -586,3 +591,28 @@ export async function deletePaymentSettingsHandler(ctx) { sendJson(ctx.res, 200, { ok: true, message: 'Payment details removed.', ...res }); } +export async function listDirectUpiPayments(ctx) { + const user = await organiser(ctx); + const eventId = id(ctx.params.id); + const r = await listDirectUpiBookings(user, eventId); + sendJson(ctx.res, 200, r); +} + +export async function confirmPayment(ctx) { + const user = await organiser(ctx, { write: true }); + const eventId = id(ctx.params.id); + const bookingId = id(ctx.params.bookingId); + const body = await readJson(ctx.req); + const r = await confirmDirectUpiPayment(user, eventId, bookingId, body); + sendJson(ctx.res, 200, r); +} + +export async function rejectPayment(ctx) { + const user = await organiser(ctx, { write: true }); + const eventId = id(ctx.params.id); + const bookingId = id(ctx.params.bookingId); + const body = await readJson(ctx.req); + const r = await rejectDirectUpiPayment(user, eventId, bookingId, body); + sendJson(ctx.res, 200, r); +} + diff --git a/lib/handlers/upi-checkout.js b/lib/handlers/upi-checkout.js index c3741f2..1c81499 100644 --- a/lib/handlers/upi-checkout.js +++ b/lib/handlers/upi-checkout.js @@ -1,6 +1,6 @@ // lib/handlers/upi-checkout.js - HTTP routes for UPI-first checkout, status polling, and PhonePe webhooks. import { sendJson, sendHtml, redirect, readRawBody, readJson, hashIp, HttpError } from '../http.js'; -import { getSessionUser } from '../session.js'; +import { getSessionUser, csrfTokenFor } from '../session.js'; import { rateLimit } from '../ratelimit.js'; import { db } from '../db.js'; import { @@ -10,6 +10,11 @@ import { processUpiWebhook, assertUpiCheckoutEnabled } from '../services/upi-payments.js'; +import { + createDirectUpiBooking, + reportDirectUpiPayment, + getDirectUpiBookingStatus +} from '../services/direct-upi.js'; import { renderUpiCheckout } from '../views/checkout-upi.js'; import { WebhookSignatureError } from '../upi/adapter.js'; import { logger } from '../logger.js'; @@ -22,7 +27,6 @@ function isMobileUserAgent(ua = '') { * GET /checkout/:slug/upi - Renders the UPI-First interactive checkout view. */ export async function upiCheckoutPage({ req, res, params, query, ip }) { - assertUpiCheckoutEnabled(); // before rate limits and body reads: the route does not exist when off const slug = params.slug; if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug)) throw new HttpError(404, 'not_found', 'Event not found'); @@ -38,12 +42,19 @@ export async function upiCheckoutPage({ req, res, params, query, ip }) { // Fetch event details const event = await db.one( - `SELECT id, slug, title, city, status, start_at, capacity FROM events - WHERE slug = $1 AND status = 'published'`, + `SELECT id, slug, title, city, status, start_at, capacity, payment_method, checkout_mode, + organiser_upi_id, organiser_payee_name, payment_instructions, organiser_user_id + FROM events + WHERE slug = $1 AND status = 'published'`, [slug] ); if (!event) throw new HttpError(404, 'event_not_found', 'This event is not available'); + const isDirectUpi = event.payment_method === 'direct_upi' || (Boolean(event.organiser_upi_id) && Boolean(event.organiser_payee_name)); + if (!isDirectUpi) { + assertUpiCheckoutEnabled(); + } + // Determine tier let tierId = query.get('tier') || query.get('ticket_type_id'); let tier; @@ -68,21 +79,33 @@ export async function upiCheckoutPage({ req, res, params, query, ip }) { const qty = parseInt(query.get('qty') || query.get('quantity'), 10) || 1; - // Create payment intent - const order = await createUpiPaymentIntent({ - slug, - user, - ticketTypeId: tier.id, - quantity: qty, - deviceType, - clientIp: ip - }); + let order; + if (isDirectUpi) { + order = await createDirectUpiBooking({ + slug, + user, + ticketTypeId: tier.id, + quantity: qty + }); + } else { + order = await createUpiPaymentIntent({ + slug, + user, + ticketTypeId: tier.id, + quantity: qty, + deviceType, + clientIp: ip + }); + } + const csrfToken = user ? csrfTokenFor(user.sessionToken) : ''; const html = renderUpiCheckout({ order, event, tier, - user + user, + isDirectUpi, + csrfToken }); sendHtml(res, 200, html); @@ -186,3 +209,29 @@ export async function phonepeWebhook({ req, res, ip }) { sendJson(res, 500, { ok: false, error: 'processing_error' }); } } + +/** + * POST /api/checkout/upi/report-payment - Attendee reports payment UTR reference. + */ +export async function reportPaymentApi({ req, res, ip }) { + await rateLimit(`upi_report:${hashIp(ip)}`, 20, 600); + const user = await getSessionUser(req); + if (!user) throw new HttpError(401, 'unauthorized', 'Please sign in to report payment.'); + const body = await readJson(req); + const { bookingId, utr } = body; + if (!bookingId || !utr) throw new HttpError(400, 'validation', 'bookingId and utr are required.'); + const r = await reportDirectUpiPayment(user, bookingId, utr); + sendJson(res, 200, r); +} + +/** + * GET /api/checkout/upi/booking-status/:id - Real-time polling for direct UPI booking verification. + */ +export async function bookingStatusApi({ req, res, params, ip }) { + const bookingId = params.id; + if (!bookingId) throw new HttpError(400, 'validation', 'bookingId is required.'); + await rateLimit(`upi_poll_direct:${hashIp(ip)}`, 180, 60); + const user = await getSessionUser(req); + const r = await getDirectUpiBookingStatus(bookingId, user?.id); + sendJson(res, 200, r); +} diff --git a/lib/router.js b/lib/router.js index 053c6a4..43afef5 100644 --- a/lib/router.js +++ b/lib/router.js @@ -137,6 +137,8 @@ const ROUTES = [ ['POST', '/api/checkout/upi/intent', h('upi-checkout', 'createUpiIntentApi')], ['GET', '/api/checkout/upi/status/:id', h('upi-checkout', 'getUpiStatusApi')], ['POST', '/api/checkout/upi/claim', h('upi-checkout', 'claimUpiBookingApi')], + ['POST', '/api/checkout/upi/report-payment', h('upi-checkout', 'reportPaymentApi')], + ['GET', '/api/checkout/upi/booking-status/:id', h('upi-checkout', 'bookingStatusApi')], // Organisations, members, venues (session + can(); outsiders get 404) ['GET', '/api/me/orgs', h('orgs', 'myOrgs')], @@ -229,6 +231,9 @@ const ROUTES = [ ['GET', '/api/organiser/payment-settings', h('organiser', 'getPaymentSettingsHandler')], ['PUT', '/api/organiser/payment-settings', h('organiser', 'savePaymentSettingsHandler')], ['DELETE', '/api/organiser/payment-settings', h('organiser', 'deletePaymentSettingsHandler')], + ['GET', '/api/organiser/events/:id/payments', h('organiser', 'listDirectUpiPayments')], + ['POST', '/api/organiser/events/:id/payments/:bookingId/confirm', h('organiser', 'confirmPayment')], + ['POST', '/api/organiser/events/:id/payments/:bookingId/reject', h('organiser', 'rejectPayment')], // Event Promotional Campaigns (Opt-in WhatsApp Marketing) ['POST', '/api/campaigns/preview', h('campaigns', 'previewCampaignHandler')], diff --git a/lib/services/direct-upi.js b/lib/services/direct-upi.js new file mode 100644 index 0000000..93d809d --- /dev/null +++ b/lib/services/direct-upi.js @@ -0,0 +1,610 @@ +// lib/services/direct-upi.js - Direct Organiser UPI Payment Integration. +// Direct peer-to-peer payments between attendees and event organisers. +// NIGHTLIFEZ does not receive, hold, split, or control ticket payments. + +import crypto from 'node:crypto'; +import { db } from '../db.js'; +import { HttpError } from '../http.js'; +import { audit } from '../audit.js'; +import { validateUpiId, validatePayeeName, UPI_REGEX } from './payment-settings.js'; +import { generateQrSvg, buildUpiUri } from '../upi/qr.js'; +import { buildAppIntents } from '../upi/adapter.js'; +import { seatsTaken, tierSeatsTaken } from './bookings.js'; +import { issueTicketsForBooking } from './tickets.js'; +import { enqueue } from './notifications.js'; +import { can } from './permissions.js'; + +export const DIRECT_UPI_STATUSES = [ + 'awaiting_payment', + 'payment_reported', + 'payment_under_review', + 'payment_confirmed', + 'payment_rejected', + 'expired', + 'cancelled' +]; + +export const DIRECT_UPI_HOLD_MINUTES = 30; + +export function generateBookingRef() { + const rand = crypto.randomBytes(3).toString('hex').toUpperCase(); + return `NLZ-${Date.now().toString(36).toUpperCase().slice(-4)}-${rand}`; +} + +export function sanitizeUtr(raw) { + const clean = String(raw || '').trim().replace(/\s+/g, ''); + if (!clean) throw new HttpError(400, 'invalid_utr', 'Please provide a valid payment reference or UTR number.'); + if (clean.length < 6 || clean.length > 50) { + throw new HttpError(400, 'invalid_utr', 'Payment reference / UTR must be between 6 and 50 characters.'); + } + if (!/^[A-Za-z0-9_-]+$/.test(clean)) { + throw new HttpError(400, 'invalid_utr', 'Payment reference / UTR contains invalid characters.'); + } + return clean; +} + +/** + * Creates or retrieves a pending direct UPI booking, reserving inventory with row locks. + */ +export async function createDirectUpiBooking({ + slug, + user, + ticketTypeId, + quantity = 1, + answers = {}, + pickupPointId = null +}) { + if (!user) throw new HttpError(401, 'unauthorized', 'Please sign in to book tickets.'); + if (!user.age_confirmed_21) throw new HttpError(403, 'age_required', 'Please confirm you are 21 or older.'); + + const qty = Math.min(Math.max(parseInt(quantity, 10) || 1, 1), 20); + + return db.tx(async (c) => { + // 1. Lock and validate event + const event = (await c.query( + `SELECT id, slug, title, status, start_at, capacity, payment_method, checkout_mode, + organiser_user_id, organiser_upi_id, organiser_payee_name, payment_instructions, + booking_questions, pickup_points, requires_approval, refund_policy, features + FROM events + WHERE slug = $1 FOR UPDATE`, + [slug] + )).rows[0]; + + if (!event || event.status !== 'published') { + throw new HttpError(404, 'event_not_found', 'This event is not available for booking.'); + } + if (new Date(event.start_at) <= new Date()) { + throw new HttpError(409, 'event_started', 'This event has already started.'); + } + if (event.payment_method !== 'direct_upi' && event.checkout_mode !== 'upi_direct') { + throw new HttpError(400, 'invalid_payment_method', 'This event is not configured for direct UPI payment.'); + } + if (!event.organiser_upi_id || !event.organiser_payee_name) { + throw new HttpError(409, 'organiser_payment_not_configured', 'Organiser has not configured payment details.'); + } + + // 2. Lock and validate ticket tier + const tier = (await c.query( + `SELECT id, name, kind, price_paise, quantity, max_per_booking, min_per_booking, + category, admit_count, session_id, valid_on, sales_start_at, sales_end_at, active, eligibility + FROM ticket_types + WHERE id = $1 AND event_id = $2 AND active FOR UPDATE`, + [ticketTypeId, event.id] + )).rows[0]; + + if (!tier || tier.kind !== 'paid') { + throw new HttpError(404, 'ticket_not_found', 'That paid ticket type is not available.'); + } + const minPerBooking = tier.min_per_booking || 1; + if (qty < minPerBooking) { + throw new HttpError(400, 'validation', `At least ${minPerBooking} ticket${minPerBooking === 1 ? '' : 's'} required per booking.`); + } + if (qty > tier.max_per_booking) { + throw new HttpError(400, 'validation', `Up to ${tier.max_per_booking} tickets per booking.`); + } + if (tier.sales_start_at && new Date(tier.sales_start_at) > new Date()) { + throw new HttpError(409, 'sales_not_started', 'Ticket sales have not started yet.'); + } + if (tier.sales_end_at && new Date(tier.sales_end_at) < new Date()) { + throw new HttpError(409, 'sales_ended', 'Ticket sales have ended.'); + } + + const admitCount = Number.isInteger(tier.admit_count) && tier.admit_count > 0 + ? tier.admit_count + : (tier.category === 'couple' ? 2 : (tier.category === 'group' ? 4 : 1)); + const eventSeatsNeeded = qty * admitCount; + + // 3. Check for existing active booking for this user + const prior = (await c.query( + `SELECT * FROM bookings + WHERE event_id = $1 AND user_id = $2 + AND status IN ('pending_payment', 'confirmed', 'checked_in', 'pending_approval') + ORDER BY created_at DESC FOR UPDATE`, + [event.id, user.id] + )).rows; + + const activeConfirmed = prior.find((b) => ['confirmed', 'checked_in'].includes(b.status)); + if (activeConfirmed) { + throw new HttpError(409, 'already_booked', 'You already have a confirmed booking for this event.'); + } + + // Clean up stale / expired holds from this user so they can place a new booking + for (const b of prior) { + if (b.status === 'pending_payment') { + const isExpired = !b.hold_expires_at || new Date(b.hold_expires_at) <= new Date(); + if (isExpired) { + await c.query( + `UPDATE bookings + SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'hold_expired', + direct_upi_status = 'expired' + WHERE id = $1`, + [b.id] + ); + } else { + // Live unexpired hold exists for this user: return it if matching tier, or cancel to replace + if (b.ticket_type_id === tier.id && b.quantity === qty) { + return formatDirectUpiOrder(b, event, tier); + } + await c.query( + `UPDATE bookings + SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'hold_replaced', + direct_upi_status = 'cancelled' + WHERE id = $1`, + [b.id] + ); + } + } + } + + // 4. Assert capacity including confirmed bookings and active unexpired holds + const takenSeats = await seatsTaken(c, event.id); + const tierTaken = await tierSeatsTaken(c, tier.id); + + if (event.capacity - takenSeats < eventSeatsNeeded || tier.quantity - tierTaken < qty) { + const left = Math.max(0, Math.min(tier.quantity - tierTaken, Math.floor((event.capacity - takenSeats) / admitCount))); + throw new HttpError(409, 'sold_out', left > 0 ? `Only ${left} ${tier.name} ticket${left === 1 ? '' : 's'} left.` : `${tier.name} is sold out.`); + } + + // 5. Server-side total amount calculation (never trust client) + const totalAmountPaise = tier.price_paise * qty; + const bookingRef = generateBookingRef(); + const holdExpiresAt = new Date(Date.now() + DIRECT_UPI_HOLD_MINUTES * 60 * 1000); + + // 6. Insert pending booking + const booking = (await c.query( + `INSERT INTO bookings ( + event_id, user_id, ticket_type_id, quantity, admit_count, amount_paise, + status, payment_mode, direct_upi_status, booking_ref, hold_expires_at, + answers, pickup_point_id, created_at, updated_at + ) VALUES ($1, $2, $3, $4, $5, $6, 'pending_payment', 'direct_upi', 'awaiting_payment', $7, $8, $9, $10, now(), now()) + RETURNING *`, + [ + event.id, + user.id, + tier.id, + qty, + admitCount, + totalAmountPaise, + bookingRef, + holdExpiresAt, + JSON.stringify(answers || {}), + pickupPointId || null + ] + )).rows[0]; + + // 7. Audit log initial booking creation + await c.query( + `INSERT INTO direct_upi_payment_audits ( + booking_id, event_id, actor_user_id, actor_role, from_status, to_status, + amount_paise, notes, metadata + ) VALUES ($1, $2, $3, 'attendee', NULL, 'awaiting_payment', $4, 'Booking initiated with dynamic UPI intent', $5)`, + [ + booking.id, + event.id, + user.id, + totalAmountPaise, + JSON.stringify({ bookingRef, organiserUpiId: event.organiser_upi_id, qty, tierId: tier.id }) + ] + ); + + return formatDirectUpiOrder(booking, event, tier); + }); +} + +/** + * Format order response with safe UPI intent link and dynamic QR. + */ +export function formatDirectUpiOrder(booking, event, tier) { + const amountPaise = Number(booking.amount_paise); + const amountRupees = (amountPaise / 100).toFixed(2); + const bookingRef = booking.booking_ref || `NLZ-${booking.id.slice(0, 8).toUpperCase()}`; + + const note = `Pass ${bookingRef} - ${event.title}`.slice(0, 50); + + const upiIntentUrl = buildUpiUri({ + vpa: event.organiser_upi_id, + name: event.organiser_payee_name, + amountPaise, + orderId: bookingRef, + note + }); + + const qrSvg = generateQrSvg(upiIntentUrl, { size: 280 }); + const appIntents = buildAppIntents(upiIntentUrl); + + return { + bookingId: booking.id, + bookingRef, + orderId: bookingRef, + status: booking.direct_upi_status || 'awaiting_payment', + bookingStatus: booking.status, + amountPaise, + amountRupees, + quantity: booking.quantity, + ticketName: tier.name, + ticketTypeId: tier.id, + eventName: event.title, + eventSlug: event.slug, + eventCity: event.city, + organiserUpiId: event.organiser_upi_id, + organiserPayeeName: event.organiser_payee_name, + paymentInstructions: event.payment_instructions || null, + upiIntentUrl, + appIntents, + qrSvg, + utrReference: booking.utr_reference || null, + expiresAt: booking.hold_expires_at ? new Date(booking.hold_expires_at).toISOString() : null, + disclaimer: "Your payment goes directly to the event organiser's UPI account. NIGHTLIFEZ does not collect or hold this ticket payment. Your ticket will be confirmed after the organiser verifies receipt." + }; +} + +/** + * Attendee submits a UTR / payment reference number. + */ +export async function reportDirectUpiPayment(user, bookingId, rawUtr) { + if (!user) throw new HttpError(401, 'unauthorized', 'Please sign in.'); + const utr = sanitizeUtr(rawUtr); + + return db.tx(async (c) => { + const booking = (await c.query( + `SELECT b.*, e.title AS event_title, e.organiser_user_id + FROM bookings b + JOIN events e ON e.id = b.event_id + WHERE b.id = $1 FOR UPDATE`, + [bookingId] + )).rows[0]; + + if (!booking) throw new HttpError(404, 'booking_not_found', 'Booking not found.'); + if (booking.user_id !== user.id) { + throw new HttpError(403, 'forbidden', 'You cannot report payment for another attendee’s booking.'); + } + if (['confirmed', 'checked_in'].includes(booking.status)) { + return { ok: true, status: 'payment_confirmed', bookingId: booking.id, message: 'Payment is already confirmed.' }; + } + if (booking.status === 'cancelled') { + throw new HttpError(409, 'booking_cancelled', 'This booking has expired or was cancelled.'); + } + if (booking.hold_expires_at && new Date(booking.hold_expires_at) <= new Date()) { + throw new HttpError(409, 'hold_expired', 'The seat reservation window has expired.'); + } + + const prevStatus = booking.direct_upi_status || 'awaiting_payment'; + const newStatus = 'payment_reported'; + + await c.query( + `UPDATE bookings + SET direct_upi_status = $1, utr_reference = $2, payment_reported_at = now(), updated_at = now() + WHERE id = $3`, + [newStatus, utr, bookingId] + ); + + await c.query( + `INSERT INTO direct_upi_payment_audits ( + booking_id, event_id, actor_user_id, actor_role, from_status, to_status, + utr_reference, amount_paise, notes + ) VALUES ($1, $2, $3, 'attendee', $4, $5, $6, $7, 'Attendee submitted payment reference/UTR')`, + [bookingId, booking.event_id, user.id, prevStatus, newStatus, utr, booking.amount_paise] + ); + + // Notify organiser + if (booking.organiser_user_id) { + await enqueue(c, { + kind: 'payment_reported', + userId: booking.organiser_user_id, + bookingId: booking.id, + dedupeKey: `utr:${booking.id}:${utr}` + }).catch(() => null); + } + + return { + ok: true, + status: newStatus, + bookingId: booking.id, + utr, + message: 'Payment reported successfully. Awaiting organiser verification.' + }; + }); +} + +/** + * Organiser independently verifies bank/UPI credit and confirms payment received. + * Strictly requires explicit verification warning acknowledgment. + */ +export async function confirmDirectUpiPayment(user, eventId, bookingId, { note = '', warningConfirmed = false } = {}) { + if (!user) throw new HttpError(401, 'unauthorized', 'Please sign in.'); + if (warningConfirmed !== true) { + throw new HttpError(400, 'warning_confirmation_required', 'You must explicitly confirm that you independently verified full payment in your bank/UPI account.'); + } + + return db.tx(async (c) => { + // 1. Authorize organiser permissions on event + const event = (await c.query( + `SELECT id, title, organiser_user_id, organiser_org_id, status FROM events WHERE id = $1`, + [eventId] + )).rows[0]; + + if (!event) throw new HttpError(404, 'event_not_found', 'Event not found.'); + + const isAuthorized = event.organiser_user_id === user.id || + await can(user, 'event.manage_bookings', { eventId, orgId: event.organiser_org_id }, c); + + if (!isAuthorized) { + throw new HttpError(403, 'forbidden', 'Only event organisers or authorized team members can confirm payments.'); + } + + // 2. Lock booking + const booking = (await c.query( + `SELECT * FROM bookings WHERE id = $1 AND event_id = $2 FOR UPDATE`, + [bookingId, eventId] + )).rows[0]; + + if (!booking) throw new HttpError(404, 'booking_not_found', 'Booking not found.'); + + // Prevent attendees from confirming their own bookings + if (booking.user_id === user.id && event.organiser_user_id !== user.id) { + throw new HttpError(403, 'self_confirmation_forbidden', 'Attendees cannot confirm their own payments.'); + } + + // Prevent duplicate confirmation + if (booking.status === 'confirmed' && booking.direct_upi_status === 'payment_confirmed') { + return { ok: true, status: 'payment_confirmed', bookingId: booking.id, alreadyConfirmed: true }; + } + + if (booking.status === 'cancelled' && booking.direct_upi_status === 'payment_rejected') { + throw new HttpError(409, 'already_rejected', 'This payment was already rejected.'); + } + + const prevStatus = booking.direct_upi_status || 'awaiting_payment'; + const newStatus = 'payment_confirmed'; + + // 3. Update booking to confirmed status + await c.query( + `UPDATE bookings + SET status = 'confirmed', confirmed_at = now(), payment_mode = 'direct_upi', + direct_upi_status = $1, verified_by_user_id = $2, verified_at = now(), + verification_note = $3, updated_at = now() + WHERE id = $4`, + [newStatus, user.id, note || null, bookingId] + ); + + // 4. Issue digital ticket passes exactly once + await issueTicketsForBooking(bookingId, c); + + // 5. Immutable audit entry + await c.query( + `INSERT INTO direct_upi_payment_audits ( + booking_id, event_id, actor_user_id, actor_role, from_status, to_status, + utr_reference, amount_paise, notes, metadata + ) VALUES ($1, $2, $3, 'organiser', $4, $5, $6, $7, $8, $9)`, + [ + bookingId, + eventId, + user.id, + prevStatus, + newStatus, + booking.utr_reference || null, + booking.amount_paise, + note || 'Organiser confirmed bank credit', + JSON.stringify({ verifiedBy: user.id, verifiedAt: new Date().toISOString() }) + ] + ); + + // 6. Notify attendee + await enqueue(c, { + kind: 'booking_confirmed', + userId: booking.user_id, + bookingId: booking.id, + dedupeKey: `bk:${booking.id}:confirmed` + }).catch(() => null); + + return { + ok: true, + status: newStatus, + bookingId: booking.id, + bookingRef: booking.booking_ref, + confirmedAt: new Date().toISOString() + }; + }); +} + +/** + * Organiser rejects payment with reason, immediately releasing reserved inventory. + */ +export async function rejectDirectUpiPayment(user, eventId, bookingId, { reason = 'Payment not received in account' } = {}) { + if (!user) throw new HttpError(401, 'unauthorized', 'Please sign in.'); + const cleanReason = String(reason || '').trim(); + if (cleanReason.length < 3) { + throw new HttpError(400, 'reason_required', 'Please provide a valid reason for payment rejection (at least 3 characters).'); + } + + return db.tx(async (c) => { + const event = (await c.query( + `SELECT id, organiser_user_id, organiser_org_id FROM events WHERE id = $1`, + [eventId] + )).rows[0]; + + if (!event) throw new HttpError(404, 'event_not_found', 'Event not found.'); + + const isAuthorized = event.organiser_user_id === user.id || + await can(user, 'event.manage_bookings', { eventId, orgId: event.organiser_org_id }, c); + + if (!isAuthorized) { + throw new HttpError(403, 'forbidden', 'Only event organisers or authorized team members can reject payments.'); + } + + const booking = (await c.query( + `SELECT * FROM bookings WHERE id = $1 AND event_id = $2 FOR UPDATE`, + [bookingId, eventId] + )).rows[0]; + + if (!booking) throw new HttpError(404, 'booking_not_found', 'Booking not found.'); + if (booking.status === 'confirmed') { + throw new HttpError(409, 'already_confirmed', 'Confirmed bookings cannot be rejected via payment review.'); + } + + const prevStatus = booking.direct_upi_status || 'awaiting_payment'; + const newStatus = 'payment_rejected'; + + // Transition booking to cancelled to immediately release seat reservation + await c.query( + `UPDATE bookings + SET status = 'cancelled', cancelled_at = now(), cancel_reason = $1, + direct_upi_status = $2, rejection_reason = $1, updated_at = now() + WHERE id = $3`, + [cleanReason, newStatus, bookingId] + ); + + // Audit trail + await c.query( + `INSERT INTO direct_upi_payment_audits ( + booking_id, event_id, actor_user_id, actor_role, from_status, to_status, + utr_reference, amount_paise, notes + ) VALUES ($1, $2, $3, 'organiser', $4, $5, $6, $7, $8)`, + [ + bookingId, + eventId, + user.id, + prevStatus, + newStatus, + booking.utr_reference || null, + booking.amount_paise, + cleanReason + ] + ); + + return { + ok: true, + status: newStatus, + bookingId: booking.id, + rejectionReason: cleanReason + }; + }); +} + +/** + * Lists direct UPI payment bookings and audit records for organiser dashboard. + */ +export async function listDirectUpiBookings(user, eventId) { + if (!user) throw new HttpError(401, 'unauthorized', 'Please sign in.'); + + const event = (await db.query( + `SELECT id, title, organiser_user_id, organiser_org_id, organiser_upi_id, organiser_payee_name + FROM events WHERE id = $1`, + [eventId] + )).rows[0]; + + if (!event) throw new HttpError(404, 'event_not_found', 'Event not found.'); + + const isAuthorized = event.organiser_user_id === user.id || + await can(user, 'event.manage_bookings', { eventId, orgId: event.organiser_org_id }); + + if (!isAuthorized) { + throw new HttpError(403, 'forbidden', 'You do not have permission to view payment details for this event.'); + } + + const { rows } = await db.query( + `SELECT b.id, b.booking_ref, b.status AS booking_status, b.direct_upi_status, + b.amount_paise, b.quantity, b.utr_reference, b.payment_reported_at, + b.verified_at, b.verification_note, b.rejection_reason, b.created_at, b.hold_expires_at, + u.alias AS attendee_alias, u.phone AS attendee_phone, + t.name AS ticket_name, + v.alias AS verified_by_alias + FROM bookings b + JOIN users u ON u.id = b.user_id + JOIN ticket_types t ON t.id = b.ticket_type_id + LEFT JOIN users v ON v.id = b.verified_by_user_id + WHERE b.event_id = $1 + AND (b.payment_mode = 'direct_upi' OR b.direct_upi_status IS NOT NULL) + ORDER BY b.created_at DESC`, + [eventId] + ); + + return { + ok: true, + eventId: event.id, + eventTitle: event.title, + organiserDestination: { + upiId: event.organiser_upi_id, + payeeName: event.organiser_payee_name + }, + bookings: rows.map((r) => ({ + id: r.id, + bookingRef: r.booking_ref || `NLZ-${r.id.slice(0, 8).toUpperCase()}`, + bookingStatus: r.booking_status, + paymentStatus: r.direct_upi_status || 'awaiting_payment', + amountPaise: Number(r.amount_paise), + amountRupees: (Number(r.amount_paise) / 100).toFixed(2), + quantity: r.quantity, + ticketName: r.ticket_name, + attendeeAlias: r.attendee_alias || 'Attendee', + utrReference: r.utr_reference || null, + paymentReportedAt: r.payment_reported_at, + verifiedAt: r.verified_at, + verifiedBy: r.verified_by_alias || null, + verificationNote: r.verification_note, + rejectionReason: r.rejection_reason, + createdAt: r.created_at, + expiresAt: r.hold_expires_at, + isExpired: r.hold_expires_at && new Date(r.hold_expires_at) <= new Date() && r.booking_status === 'pending_payment' + })) + }; +} + +/** + * Get booking payment status for live checkout polling. + */ +export async function getDirectUpiBookingStatus(bookingId, userId = null) { + const row = (await db.query( + `SELECT b.id, b.booking_ref, b.status AS booking_status, b.direct_upi_status, + b.amount_paise, b.hold_expires_at, b.rejection_reason, b.user_id, + e.slug AS event_slug + FROM bookings b + JOIN events e ON e.id = b.event_id + WHERE b.id = $1`, + [bookingId] + )).rows[0]; + + if (!row) throw new HttpError(404, 'booking_not_found', 'Booking not found.'); + if (userId && row.user_id !== userId) { + throw new HttpError(403, 'forbidden', 'Cannot view status of another user’s booking.'); + } + + const isExpired = row.hold_expires_at && new Date(row.hold_expires_at) <= new Date() && row.booking_status === 'pending_payment'; + + let effectiveStatus = row.direct_upi_status || 'awaiting_payment'; + if (isExpired && effectiveStatus !== 'payment_confirmed') { + effectiveStatus = 'expired'; + } + + return { + ok: true, + bookingId: row.id, + bookingRef: row.booking_ref, + status: effectiveStatus, + bookingStatus: row.booking_status, + isConfirmed: effectiveStatus === 'payment_confirmed', + eventSlug: row.event_slug, + isExpired, + rejectionReason: row.rejection_reason || null + }; +} diff --git a/lib/services/events.js b/lib/services/events.js index fd56b10..6d95946 100644 --- a/lib/services/events.js +++ b/lib/services/events.js @@ -243,9 +243,13 @@ export function toPublicEvent(row, { checkout = checkoutForEvent(row) } = {}) { gallery: list(row.gallery).filter((u) => typeof u === 'string' && u.startsWith('/media/')), balance: Boolean(features.balance), organiserManaged: Boolean(row.organiser_user_id), - checkoutAvailable: Boolean(checkout?.available), - checkoutMode: sp ? (checkout.provider === 'phonepe' || checkout.provider === 'phonepe_sandbox' ? 'upi_direct' : 'superprofile') : (row.checkout_mode === 'upi_direct' ? 'upi_direct' : 'none'), - checkoutPath: (sp || row.checkout_mode === 'upi_direct') ? `/checkout/${row.slug}` : null, + checkoutAvailable: (row.payment_method === 'direct_upi' || (Boolean(row.organiser_upi_id) && Boolean(row.organiser_payee_name))) ? true : Boolean(checkout?.available), + checkoutMode: (row.payment_method === 'direct_upi' || (Boolean(row.organiser_upi_id) && Boolean(row.organiser_payee_name))) ? 'upi_direct' : (sp ? (checkout.provider === 'phonepe' || checkout.provider === 'phonepe_sandbox' ? 'upi_direct' : 'superprofile') : (row.checkout_mode === 'upi_direct' ? 'upi_direct' : 'none')), + checkoutPath: (row.payment_method === 'direct_upi' || (Boolean(row.organiser_upi_id) && Boolean(row.organiser_payee_name)) || sp || row.checkout_mode === 'upi_direct') ? `/checkout/${row.slug}` : null, + paymentMethod: (row.payment_method === 'direct_upi' || (Boolean(row.organiser_upi_id) && Boolean(row.organiser_payee_name))) ? 'direct_upi' : (row.payment_method || 'free'), + organiserUpiId: row.organiser_upi_id || null, + organiserPayeeName: row.organiser_payee_name || null, + paymentInstructions: row.payment_instructions || null, inclusions: arr(row.inclusions), exclusions: arr(row.exclusions), refundPolicy: row.refund_policy || '', diff --git a/lib/services/organiser.js b/lib/services/organiser.js index f2719e0..dd206d0 100644 --- a/lib/services/organiser.js +++ b/lib/services/organiser.js @@ -18,6 +18,7 @@ import { enqueue } from './notifications.js'; import { CancellationPolicyDraft, POLICY_TEMPLATES, resolveCancellationPolicy } from './cancellation-policy.js'; import { EventScheduleDraft, normalizeSchedule, deriveEventBounds } from './event-schedule.js'; import { reverseBookingFeeEntry } from './finance.js'; +import { validateUpiId, validatePayeeName, UPI_REGEX } from './payment-settings.js'; export const MAX_IMAGES = 5; export const MAX_TIERS = 10; @@ -135,6 +136,10 @@ export const DraftData = z.object({ coverImageId: z.union([z.string().uuid(), z.literal(''), z.null()]).optional().transform((v) => v === '' ? null : v), imageIds: z.array(z.string().uuid().or(z.literal(''))).max(MAX_IMAGES).optional().transform((arr) => arr ? arr.filter(Boolean) : undefined), imageRightsConfirmed: flag, + paymentMethod: z.enum(['free', 'direct_upi']).optional(), + organiserUpiId: z.string().max(256).optional(), + organiserPayeeName: z.string().max(100).optional(), + paymentInstructions: z.string().max(1000).optional(), refundPolicy: text(1000).optional(), cancellationPolicy: CancellationPolicyDraft.optional(), schedule: EventScheduleDraft.optional(), @@ -369,19 +374,40 @@ export function publishIssues(d, { checkout = ticketCheckoutStatus(), now = new if (capacity > MAX_CAPACITY) err('tickets', 'tickets', `Total tickets cannot exceed ${MAX_CAPACITY}.`); const paid = tickets.filter((t) => t.kind === 'paid' || (t.pricePaise && t.pricePaise > 0)); - if (paid.length && !d.cancellationPolicy && clean(d.refundPolicy).length < 10) { - err('tickets', 'refundPolicy', 'Paid tickets need a cancellation and refund policy.'); - } - const allowPaid = livePayments() || upiCheckoutEnabled() || process.env.ALLOW_PAID_PUBLISH === 'true'; - if (paid.length > 0 && !allowPaid) { - if (paid.length === tickets.length) { - err('tickets', 'tickets', 'Online payment is not available yet, so guests could not book any of these tickets. Add a free ticket, or save this draft until a payment method is configured.'); - } else { - err('tickets', 'tickets', 'Paid ticket sales are disabled. NIGHTLIFEZ is free event listings only for this phase. Convert all tickets to Free (₹0) to publish.'); + const isDirectUpi = d.paymentMethod === 'direct_upi' || (paid.length > 0 && Boolean(clean(d.organiserUpiId))); + + if (isDirectUpi) { + const upi = clean(d.organiserUpiId); + const payee = clean(d.organiserPayeeName); + if (!upi) { + err('tickets', 'organiserUpiId', 'Add your UPI ID to receive direct attendee payments.'); + } else if (!UPI_REGEX.test(upi)) { + err('tickets', 'organiserUpiId', 'Invalid UPI ID format. E.g. name@okaxis or business@okhdfcbank.'); + } + if (!payee) { + err('tickets', 'organiserPayeeName', 'Add your payee or account display name.'); + } else if (payee.length < 2) { + err('tickets', 'organiserPayeeName', 'Payee display name must be at least 2 characters.'); + } else if (payee.length > 100) { + err('tickets', 'organiserPayeeName', 'Payee display name cannot exceed 100 characters.'); + } + if (paid.length === 0) { + err('tickets', 'tickets', 'Direct UPI payment is selected: add at least one paid ticket tier, or switch to Free event.'); + } + if (paid.length && !d.cancellationPolicy && clean(d.refundPolicy).length < 10) { + err('tickets', 'refundPolicy', 'Paid tickets need a cancellation and refund policy.'); + } + } else { + if (paid.length && !d.cancellationPolicy && clean(d.refundPolicy).length < 10) { + err('tickets', 'refundPolicy', 'Paid tickets need a cancellation and refund policy.'); + } + if (paid.length && !checkout.available) { + if (paid.length === tickets.length) { + err('tickets', 'tickets', 'Online payment is not available yet, so guests could not book any of these tickets. Add a free ticket, or save this draft until a payment method is configured.'); + } else { + warn('tickets', 'tickets', 'Online payment is not available yet. Guests will see your paid tickets as “Paid ticket — external checkout not configured” and can book only the free ones.'); + } } - } else if (paid.length && !checkout.available) { - if (paid.length === tickets.length) err('tickets', 'tickets', 'Online payment is not available yet, so guests could not book any of these tickets. Add a free ticket, or save this draft until a payment method is configured.'); - else warn('tickets', 'tickets', 'Online payment is not available yet. Guests will see your paid tickets as “Paid ticket — external checkout not configured” and can book only the free ones.'); } // Features @@ -655,6 +681,11 @@ export function draftToRow(d, { hostFallback = '' } = {}) { source: 'internal', status: 'draft', is_demo: false, seats_taken: 0, cover_url: d.coverImageId ? imageUrl(d.coverImageId) : null, gallery: (d.imageIds || []).map(imageUrl), + payment_method: d.paymentMethod === 'direct_upi' || (tickets.some((t) => t.kind === 'paid') && Boolean(clean(d.organiserUpiId))) ? 'direct_upi' : 'free', + organiser_upi_id: clean(d.organiserUpiId) || null, + organiser_payee_name: clean(d.organiserPayeeName) || null, + payment_instructions: clean(d.paymentInstructions) || null, + checkout_mode: (d.paymentMethod === 'direct_upi' || Boolean(clean(d.organiserUpiId))) ? 'upi_direct' : 'free', ticketing: 'tiers', is_multi_day: effectiveMultiDay, requires_approval: Boolean(f.approval?.enabled), features: { ...featureFlags(f), @@ -726,9 +757,13 @@ export async function publishDraft(user, draftId, { version, confirm }) { const d = parse(DraftData, draft.data); const errors = blocking(publishIssues(d, { checkout })); if (errors.length) throw new HttpError(422, 'not_ready', 'Some details need attention before publishing.', { issues: errors }); - const allowPaid = livePayments() || upiCheckoutEnabled() || process.env.ALLOW_PAID_PUBLISH === 'true'; - if (!allowPaid && d.tickets?.some((t) => t.kind === 'paid' || (t.pricePaise && t.pricePaise > 0))) { - throw new HttpError(422, 'paid_tickets_disabled', 'Paid ticket sales are disabled. Only free events can be published.'); + const hasPaid = d.tickets?.some((t) => t.kind === 'paid' || (t.pricePaise && t.pricePaise > 0)); + const isDirectUpi = d.paymentMethod === 'direct_upi' || (hasPaid && Boolean(clean(d.organiserUpiId))); + if (hasPaid && !isDirectUpi) { + const allowPaid = livePayments() || upiCheckoutEnabled() || process.env.ALLOW_PAID_PUBLISH === 'true'; + if (!allowPaid) { + throw new HttpError(422, 'paid_tickets_disabled', 'Paid ticket sales require Direct UPI configuration or gateway activation.'); + } } const imageIds = [d.coverImageId, ...(d.imageIds || [])].filter(Boolean); @@ -791,8 +826,11 @@ export async function publishDraft(user, draftId, { version, confirm }) { ? (resolvedPolicy.renderedText || resolvedPolicy.snapshot.summary) : (clean(d.refundPolicy) || resolvedPolicy.renderedText || resolvedPolicy.snapshot.summary); - const hasPaid = tickets.some((t) => t.kind === 'paid'); - const checkoutMode = hasPaid ? (checkout.available && (checkout.provider === 'phonepe' || checkout.provider === 'phonepe_sandbox') ? 'upi_direct' : 'none') : 'free'; + const paymentMethod = isDirectUpi ? 'direct_upi' : 'free'; + const organiserUpiId = isDirectUpi ? clean(d.organiserUpiId) : null; + const organiserPayeeName = isDirectUpi ? clean(d.organiserPayeeName) : null; + const paymentInstructions = isDirectUpi ? (clean(d.paymentInstructions) || null) : null; + const checkoutMode = isDirectUpi ? 'upi_direct' : (hasPaid ? (checkout.available && (checkout.provider === 'phonepe' || checkout.provider === 'phonepe_sandbox') ? 'upi_direct' : 'none') : 'free'); let linkedVenueId = null; if (d.venueId) { @@ -811,10 +849,10 @@ export async function publishDraft(user, draftId, { version, confirm }) { `INSERT INTO events (slug, category, title, summary, description, city, city_id, locality_id, lat, lng, coords_provenance, area_public, venue_private, venue_privacy, start_at, end_at, timezone, capacity, price_status, refund_policy, organizer, status, published_at, organiser_user_id, draft_id, ticketing, is_multi_day, maps_url, requires_approval, booking_questions, pickup_points, contact_name, contact_phone, gallery, features, cover_media_id, - organiser_org_id, checkout_mode, venue_id) + organiser_org_id, checkout_mode, venue_id, payment_method, organiser_upi_id, organiser_payee_name, payment_instructions) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, 'tbd', $19, $20, 'published', now(), $21, $22, 'tiers', - $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35) RETURNING id, slug, category, venue_id`, + $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39) RETURNING id, slug, category, venue_id`, [slugify(d.title), d.category, clean(d.title), summaryOf(d.description) || null, clean(d.description), canonicalCity, cityId, localityId, lat, lng, coordsProvenance, clean(d.area) || null, clean(d.venue) || null, d.privateVenue ? 'disclosed_after_booking' : 'public', zonedToUtc(effectiveStart, tz), @@ -824,7 +862,8 @@ export async function publishDraft(user, draftId, { version, confirm }) { JSON.stringify(f.questions?.enabled ? sanitizeQuestions(f.questions.items) : []), JSON.stringify(f.pickup?.enabled ? sanitizePickups(f.pickup.points) : []), contactPhone ? clean(f.contact.name) : null, contactPhone, - JSON.stringify((d.imageIds || []).map(imageUrl)), JSON.stringify(finalFeatures), coverMediaId, orgId, checkoutMode, linkedVenueId])).rows[0]; + JSON.stringify((d.imageIds || []).map(imageUrl)), JSON.stringify(finalFeatures), coverMediaId, orgId, checkoutMode, linkedVenueId, + paymentMethod, organiserUpiId, organiserPayeeName, paymentInstructions])).rows[0]; // Insert recurring / multi-date occurrences into event_sessions const sessionMap = new Map(); diff --git a/lib/views/checkout-upi.js b/lib/views/checkout-upi.js index bb30b50..918d0a1 100644 --- a/lib/views/checkout-upi.js +++ b/lib/views/checkout-upi.js @@ -1,6 +1,4 @@ -// lib/views/checkout-upi.js - Responsive UPI-first checkout view. -// Adapts between Mobile (direct intent launch & app chooser) and Desktop (dynamic QR & live polling). - +// lib/views/checkout-upi.js - Responsive UPI checkout view for Direct Organiser payments and legacy UPI. import { html, raw } from './html.js'; import { layout } from './layout.js'; @@ -9,6 +7,7 @@ export function renderUpiCheckout({ event, tier, user, + isDirectUpi = false, csrfToken = '' }) { const amountRupees = (order.amountPaise / 100).toFixed(2); @@ -19,22 +18,26 @@ export function renderUpiCheckout({ ? (order.feePaise / 100).toFixed(2) : Math.max(0, Number(amountRupees) - Number(baseRupees)).toFixed(2); const feePct = order.feePercentage || 5; - const organiserDestination = order.organiserUpiId || event.organiser_upi_id || 'Organiser Verified UPI'; + const organiserDestination = order.organiserUpiId || event.organiser_upi_id || 'Organiser UPI'; + const organiserName = order.organiserPayeeName || event.organiser_payee_name || event.organizer || 'Event Organiser'; const upiUri = order.upiIntentUrl; const qrSvg = order.qrSvg; const expiresAt = order.expiresAt; - const unitPrice = tier.price_paise ? (tier.price_paise / 100).toFixed(2) : amountRupees; - const admitCount = Number.isInteger(tier.admit_count) && tier.admit_count > 0 ? tier.admit_count : (tier.category === 'couple' ? 2 : tier.category === 'group' ? 4 : 1); + const bookingRef = order.bookingRef || order.orderId; + const bookingId = order.bookingId || ''; + const admitCount = Number.isInteger(tier.admit_count) && tier.admit_count > 0 + ? tier.admit_count + : (tier.category === 'couple' ? 2 : (tier.category === 'group' ? 4 : 1)); const totalAdmit = (order.quantity || 1) * admitCount; const body = html` -
+
- ${order.isTest ? html` -
-

🧪 Test Environment: Order ${order.orderId} is running in sandbox test mode. No real money will be charged. Automated confirmation simulates provider webhook processing.

-
` : ''} -
Seat reservation holds for: - 15:00 + 30:00

Pay with UPI on this device

-

Tap below to open your preferred UPI application and approve payment.

+

Tap below to open your preferred UPI application and transfer ₹${amountRupees} directly to ${organiserName}.

- ⚡ Pay with Any UPI App + ⚡ Pay ₹${amountRupees} with Any UPI App + ${order.appIntents ? html`
- or choose your preferred app + or choose your UPI app
@@ -114,17 +131,13 @@ export function renderUpiCheckout({ B BHIM UPI -
- -

- Returning from the UPI app? We automatically verify payment confirmation with the banking network. -

+
` : ''}

Scan QR code to pay

-

Open any UPI app on your mobile phone and scan this dynamic code.

+

Scan with any UPI app on your mobile phone to pay ₹${amountRupees} to ${organiserName}.

${raw(qrSvg)} @@ -140,33 +153,48 @@ export function renderUpiCheckout({
+ +
+

Have you transferred the payment?

+

+ Enter the 12-digit UPI reference number or bank UTR from your payment confirmation screen to notify the organiser: +

+
+
+ + +
+

+
+
+
-

Awaiting payment authorization from bank...

+

${order.status === 'payment_reported' ? 'Payment reported. Awaiting organiser bank verification...' : 'Awaiting payment from attendee...'}

@@ -190,7 +218,6 @@ export function renderUpiCheckout({ .summary-admit { color: #06D6A0; font-size: 0.9rem; font-weight: 600; margin-bottom: 0.75rem; } .summary-breakdown { padding: 1rem 0; border-top: 1px solid var(--border-strong, #6670B0); border-bottom: 1px solid var(--border-strong, #6670B0); display: flex; flex-direction: column; gap: 0.5rem; font-size: 0.92rem; } .breakdown-row { display: flex; justify-content: space-between; align-items: center; color: var(--fg-secondary, #F1F3FA); } - .free-fee { color: #06D6A0; font-weight: 600; } .summary-price { display: flex; justify-content: space-between; align-items: baseline; margin: 1.25rem 0; } .price-label { font-size: 1rem; color: var(--fg-secondary, #F1F3FA); font-weight: 600; } .price-val { font-size: 1.85rem; font-weight: 800; color: #FFD166; letter-spacing: -0.02em; } @@ -222,9 +249,6 @@ export function renderUpiCheckout({ .status-screen { text-align: center; padding: 2.5rem 1rem; } .success-icon { width: 68px; height: 68px; border-radius: 50%; background: #06D6A0; color: #0E1224; font-size: 2.2rem; font-weight: 900; display: inline-flex; align-items: center; justify-content: center; margin-bottom: 1.25rem; } .warn-icon { font-size: 3rem; margin-bottom: 1rem; } - .badge-test { background: rgba(251, 191, 36, 0.18); color: #FBBF24; border: 1px solid rgba(251, 191, 36, 0.4); } - .sandbox-banner { background: rgba(251, 191, 36, 0.1); border: 1px solid rgba(251, 191, 36, 0.35); color: #FDE68A; padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1.25rem; font-size: 0.88rem; line-height: 1.4; } - .sandbox-banner code { color: #FFF; background: rgba(0,0,0,0.3); padding: 2px 6px; border-radius: 4px; } .error-icon { width: 68px; height: 68px; border-radius: 50%; background: #EF476F; color: #fff; font-size: 2.2rem; font-weight: 900; display: inline-flex; align-items: center; justify-content: center; margin-bottom: 1.25rem; } @@ -233,69 +257,132 @@ export function renderUpiCheckout({ var wrap = document.querySelector('.checkout-wrap'); if (!wrap) return; var orderId = wrap.getAttribute('data-order-id'); - var expiresAt = new Date(wrap.getAttribute('data-expires-at')).getTime(); + var bookingId = wrap.getAttribute('data-booking-id'); + var isDirect = wrap.getAttribute('data-is-direct') === '1'; + var csrfToken = wrap.getAttribute('data-csrf') || ''; + var expiresAtStr = wrap.getAttribute('data-expires-at'); + var expiresAt = expiresAtStr ? new Date(expiresAtStr).getTime() : 0; var timerDigits = document.getElementById('timer-digits'); var statusText = document.getElementById('status-text'); var manualPollBtn = document.getElementById('btn-manual-poll'); - var panel = document.getElementById('checkout-panel'); + var utrForm = document.getElementById('utr-form'); + var utrInput = document.getElementById('utr-input'); + var utrBtn = document.getElementById('utr-btn'); + var utrMsg = document.getElementById('utr-msg'); var successScreen = document.getElementById('success-screen'); var expiredScreen = document.getElementById('expired-screen'); var failedScreen = document.getElementById('failed-screen'); var pollingStatus = document.getElementById('polling-status'); var viewBookingBtn = document.getElementById('view-booking-btn'); + var utrPanel = document.getElementById('utr-panel'); // Countdown timer - var timerInterval = setInterval(function() { + var timerInterval = expiresAt ? setInterval(function() { var now = Date.now(); var leftMs = expiresAt - now; if (leftMs <= 0) { clearInterval(timerInterval); - timerDigits.textContent = '00:00'; + if (timerDigits) timerDigits.textContent = '00:00'; showExpired(); return; } var totalSec = Math.floor(leftMs / 1000); var mins = Math.floor(totalSec / 60); var secs = totalSec % 60; - timerDigits.textContent = (mins < 10 ? '0' : '') + mins + ':' + (secs < 10 ? '0' : '') + secs; - }, 1000); - - function showSuccess(bookingId) { - clearInterval(timerInterval); - document.getElementById('mobile-checkout').hidden = true; - document.getElementById('desktop-checkout').hidden = true; - document.getElementById('timer-box').hidden = true; - pollingStatus.hidden = true; - if (bookingId) viewBookingBtn.href = '/bookings/' + bookingId; + if (timerDigits) timerDigits.textContent = (mins < 10 ? '0' : '') + mins + ':' + (secs < 10 ? '0' : '') + secs; + }, 1000) : null; + + function showSuccess(confirmedBookingId) { + if (timerInterval) clearInterval(timerInterval); + var m = document.getElementById('mobile-checkout'); if (m) m.hidden = true; + var d = document.getElementById('desktop-checkout'); if (d) d.hidden = true; + var t = document.getElementById('timer-box'); if (t) t.hidden = true; + if (utrPanel) utrPanel.hidden = true; + if (pollingStatus) pollingStatus.hidden = true; + if (viewBookingBtn && (confirmedBookingId || bookingId)) { + viewBookingBtn.href = '/bookings/' + (confirmedBookingId || bookingId); + } successScreen.hidden = false; } function showExpired() { - document.getElementById('mobile-checkout').hidden = true; - document.getElementById('desktop-checkout').hidden = true; - pollingStatus.hidden = true; + var m = document.getElementById('mobile-checkout'); if (m) m.hidden = true; + var d = document.getElementById('desktop-checkout'); if (d) d.hidden = true; + if (utrPanel) utrPanel.hidden = true; + if (pollingStatus) pollingStatus.hidden = true; expiredScreen.hidden = false; } function showFailed(reason) { - document.getElementById('mobile-checkout').hidden = true; - document.getElementById('desktop-checkout').hidden = true; - pollingStatus.hidden = true; + var m = document.getElementById('mobile-checkout'); if (m) m.hidden = true; + var d = document.getElementById('desktop-checkout'); if (d) d.hidden = true; + if (utrPanel) utrPanel.hidden = true; + if (pollingStatus) pollingStatus.hidden = true; if (reason) document.getElementById('failed-msg').textContent = reason; failedScreen.hidden = false; } + // UTR report form submission + if (utrForm) { + utrForm.addEventListener('submit', function(ev) { + ev.preventDefault(); + var utrVal = utrInput.value.trim(); + if (!utrVal || utrVal.length < 6) { + utrMsg.style.color = '#FF315B'; + utrMsg.textContent = 'Please enter a valid reference / UTR number (at least 6 characters).'; + return; + } + utrBtn.disabled = true; + utrMsg.style.color = 'var(--neon-cyan, #00D9FF)'; + utrMsg.textContent = 'Submitting reference...'; + + fetch('/api/checkout/upi/report-payment', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'X-CSRF-Token': csrfToken + }, + body: JSON.stringify({ bookingId: bookingId, utr: utrVal }) + }) + .then(function(r) { return r.json(); }) + .then(function(res) { + utrBtn.disabled = false; + if (res.ok) { + utrMsg.style.color = 'var(--neon-green, #00FF88)'; + utrMsg.textContent = '✓ Payment reported! The organiser has been notified to verify your payment.'; + if (statusText) statusText.textContent = 'Payment reported. Awaiting organiser bank verification...'; + } else { + utrMsg.style.color = '#FF315B'; + utrMsg.textContent = res.message || 'Could not report payment. Please check and try again.'; + } + }) + .catch(function() { + utrBtn.disabled = false; + utrMsg.style.color = '#FF315B'; + utrMsg.textContent = 'Network error while submitting reference. Please retry.'; + }); + }); + } + function checkStatus() { - fetch('/api/checkout/upi/status/' + encodeURIComponent(orderId)) + var endpoint = isDirect && bookingId + ? '/api/checkout/upi/booking-status/' + encodeURIComponent(bookingId) + : '/api/checkout/upi/status/' + encodeURIComponent(orderId); + + fetch(endpoint) .then(function(res) { return res.json(); }) .then(function(data) { if (!data || !data.ok) return; - if (data.status === 'succeeded') { + var st = data.status; + if (st === 'payment_confirmed' || st === 'succeeded' || data.bookingStatus === 'confirmed') { showSuccess(data.bookingId); - } else if (data.status === 'expired') { + } else if (st === 'expired' || data.isExpired) { showExpired(); - } else if (data.status === 'failed' || data.status === 'cancelled') { - showFailed(data.message); + } else if (st === 'payment_rejected' || st === 'failed' || st === 'cancelled' || data.bookingStatus === 'cancelled') { + showFailed(data.rejectionReason || data.message); + } else if (st === 'payment_reported') { + if (statusText) statusText.textContent = 'Payment reported. Organiser is verifying your bank credit...'; } }) .catch(function() {}); @@ -308,9 +395,11 @@ export function renderUpiCheckout({ if (manualPollBtn) { manualPollBtn.addEventListener('click', function() { - statusText.textContent = 'Checking with gateway...'; + statusText.textContent = 'Checking status with organiser...'; checkStatus(); - setTimeout(function() { statusText.textContent = 'Awaiting payment authorization...'; }, 1500); + setTimeout(function() { + statusText.textContent = 'Awaiting payment verification...'; + }, 1500); }); } })(); @@ -318,9 +407,9 @@ export function renderUpiCheckout({ `; return layout({ - title: `Checkout — ${event.title}`, - description: `Pay securely with UPI for ${event.title}`, - path: `/checkout/${event.slug}`, + title: `Direct UPI Checkout — ${event.title}`, + description: `Pay securely via direct organiser UPI for ${event.title}`, + path: `/checkout/${event.slug}/upi`, body, noindex: true }); diff --git a/migrations/032_direct_organiser_upi_payments.sql b/migrations/032_direct_organiser_upi_payments.sql new file mode 100644 index 0000000..5d13f46 --- /dev/null +++ b/migrations/032_direct_organiser_upi_payments.sql @@ -0,0 +1,61 @@ +-- 032_direct_organiser_upi_payments.sql +-- Direct Organiser UPI Payment Integration: +-- Organiser-to-attendee direct peer-to-peer payments without intermediary gateway holding funds. + +-- 1. Extend events table +ALTER TABLE events ADD COLUMN IF NOT EXISTS payment_method TEXT DEFAULT 'free'; +ALTER TABLE events ADD COLUMN IF NOT EXISTS organiser_upi_id TEXT; +ALTER TABLE events ADD COLUMN IF NOT EXISTS organiser_payee_name TEXT; +ALTER TABLE events ADD COLUMN IF NOT EXISTS payment_instructions TEXT; + +-- 2. Extend bookings table for direct organiser UPI payment tracking +ALTER TABLE bookings ADD COLUMN IF NOT EXISTS booking_ref TEXT; +ALTER TABLE bookings ADD COLUMN IF NOT EXISTS direct_upi_status TEXT; +ALTER TABLE bookings ADD COLUMN IF NOT EXISTS utr_reference TEXT; +ALTER TABLE bookings ADD COLUMN IF NOT EXISTS payment_reported_at TIMESTAMPTZ; +ALTER TABLE bookings ADD COLUMN IF NOT EXISTS verified_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL; +ALTER TABLE bookings ADD COLUMN IF NOT EXISTS verified_at TIMESTAMPTZ; +ALTER TABLE bookings ADD COLUMN IF NOT EXISTS verification_note TEXT; +ALTER TABLE bookings ADD COLUMN IF NOT EXISTS rejection_reason TEXT; + +-- Update payment_mode check constraint to include direct_upi +ALTER TABLE bookings DROP CONSTRAINT IF EXISTS bookings_payment_mode; +ALTER TABLE bookings ADD CONSTRAINT bookings_payment_mode + CHECK (payment_mode IS NULL OR payment_mode IN ('free', 'provider', 'external', 'direct_upi')); + +-- Add check constraint for direct_upi_status +ALTER TABLE bookings DROP CONSTRAINT IF EXISTS bookings_direct_upi_status; +ALTER TABLE bookings ADD CONSTRAINT bookings_direct_upi_status + CHECK (direct_upi_status IS NULL OR direct_upi_status IN ( + 'awaiting_payment', + 'payment_reported', + 'payment_under_review', + 'payment_confirmed', + 'payment_rejected', + 'expired', + 'cancelled' + )); + +-- Unique booking reference index +CREATE UNIQUE INDEX IF NOT EXISTS uq_bookings_booking_ref ON bookings(booking_ref) WHERE booking_ref IS NOT NULL; +CREATE INDEX IF NOT EXISTS idx_bookings_direct_upi ON bookings(event_id, direct_upi_status); +CREATE INDEX IF NOT EXISTS idx_bookings_utr ON bookings(utr_reference) WHERE utr_reference IS NOT NULL; + +-- 3. Audit trail for direct organiser payment verifications and transitions +CREATE TABLE IF NOT EXISTS direct_upi_payment_audits ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + booking_id UUID NOT NULL REFERENCES bookings(id) ON DELETE CASCADE, + event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE, + actor_user_id UUID REFERENCES users(id) ON DELETE SET NULL, + actor_role TEXT NOT NULL DEFAULT 'organiser', + from_status TEXT, + to_status TEXT NOT NULL, + utr_reference TEXT, + amount_paise BIGINT NOT NULL, + notes TEXT, + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_direct_upi_audits_booking ON direct_upi_payment_audits(booking_id, created_at); +CREATE INDEX IF NOT EXISTS idx_direct_upi_audits_event ON direct_upi_payment_audits(event_id, created_at); diff --git a/public/js/organiser.js b/public/js/organiser.js index ebf636c..116ae3b 100644 --- a/public/js/organiser.js +++ b/public/js/organiser.js @@ -199,6 +199,7 @@ ['overview', '📊 Overview & Readiness'], ['inventory', '🎟️ Ticket Inventory'], ['attendees', '👥 Attendees & Guest List'], + ['payments', '💳 Direct UPI Payments'], ['finance', '💰 Finance & Fees'], ['staff', '🛡️ Event Staff'], ['announcements', '📢 Announcements'], @@ -250,6 +251,8 @@ renderInventoryTab(panel); } else if (activeTab === 'attendees') { renderAttendeesTab(panel); + } else if (activeTab === 'payments') { + renderPaymentsTab(panel); } else if (activeTab === 'finance') { renderFinanceTab(panel); } else if (activeTab === 'staff') { @@ -261,6 +264,141 @@ } } + function renderPaymentsTab(panel) { + panel.innerHTML = '

Loading direct UPI payments…

'; + api('GET', '/api/organiser/events/' + encodeURIComponent(id) + '/payments').then(function (r) { + if (!r.ok) { + panel.innerHTML = '

' + esc(r.message || 'Could not load payment records.') + '

'; + return; + } + + var dest = r.organiserDestination || {}; + var bookings = r.bookings || []; + + var pendingCount = 0; + var reportedCount = 0; + var confirmedCount = 0; + var confirmedTotalPaise = 0; + + bookings.forEach(function (b) { + if (b.paymentStatus === 'payment_reported') reportedCount++; + if (b.paymentStatus === 'awaiting_payment' || b.paymentStatus === 'payment_under_review') pendingCount++; + if (b.bookingStatus === 'confirmed') { + confirmedCount++; + confirmedTotalPaise += (b.amountPaise || 0); + } + }); + + var pendingBookings = bookings.filter(function (b) { + return b.bookingStatus === 'pending_payment' && b.paymentStatus !== 'payment_rejected'; + }); + + var historyBookings = bookings.filter(function (b) { + return b.bookingStatus !== 'pending_payment' || b.paymentStatus === 'payment_rejected'; + }); + + var h = '
' + + '
' + + '
' + + '

💳 Direct Organiser UPI Payments

' + + '

Payments go directly to your bank account via UPI. NIGHTLIFEZ does not hold funds. Verify incoming credit independently before confirming tickets.

' + + '
Peer-to-Peer Direct
' + + '
' + + + '
' + + '

Configured Payee Name: ' + esc(dest.payeeName || 'Not configured') + '

' + + '

Configured UPI ID: ' + esc(dest.upiId || 'Not configured') + ' ' + + (dest.upiId ? '' : '') + '

' + + '

⚠️ Ensure your UPI ID is active and can receive payments. Only confirm bookings after seeing credit in your bank app.

' + + '
' + + + '
' + + '
UTR Reported' + reportedCount + '
' + + '
Awaiting Transfer' + pendingCount + '
' + + '
Confirmed Bookings' + confirmedCount + '
' + + '
Total Received' + money(confirmedTotalPaise) + '
' + + '
' + + '
'; + + // Section 1: Pending & Reported Payments + h += '
' + + '

⏳ Pending Payment Verification (' + pendingBookings.length + ')

' + + '

Review attendee transfers. Compare the UTR and amount against your UPI or bank statement.

'; + + if (!pendingBookings.length) { + h += '

No pending payments

When attendees initiate direct UPI payments, they will appear here for verification.

'; + } else { + h += '
' + + '' + + '' + + pendingBookings.map(function (b) { + var statusPill = 'Awaiting Payment'; + if (b.paymentStatus === 'payment_reported') { + statusPill = 'UTR Reported'; + } else if (b.paymentStatus === 'payment_under_review') { + statusPill = 'Under Review'; + } + var utrDisplay = b.utrReference + ? '' + esc(b.utrReference) + '' + + '
' + esc(fmtInstant(b.paymentReportedAt)) + '' + : 'Not submitted yet'; + + var countdown = b.isExpired + ? 'Hold expired' + : 'Hold expires: ' + esc(fmtInstant(b.expiresAt)) + ''; + + return '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; + }).join('') + + '
Ref & AttendeeTicketExpected AmountSubmitted UTRStatusActions
' + esc(b.bookingRef) + '
' + esc(b.attendeeAlias) + '
' + esc(b.ticketName) + ' × ' + esc(b.quantity) + '' + money(b.amountPaise) + '' + utrDisplay + '' + statusPill + '
' + countdown + '
' + + '' + + '' + + '
'; + } + h += '
'; + + // Section 2: Audit History + h += '
' + + '

📜 Payment Verification History (' + historyBookings.length + ')

'; + + if (!historyBookings.length) { + h += '

No historical payments recorded yet.

'; + } else { + h += '
' + + '' + + '' + + historyBookings.map(function (b) { + var resPill = b.bookingStatus === 'confirmed' + ? 'Confirmed' + : '' + esc(b.paymentStatus === 'payment_rejected' ? 'Rejected' : b.bookingStatus) + ''; + + var auditNote = b.bookingStatus === 'confirmed' + ? 'Verified by ' + esc(b.verifiedBy || 'Host') + (b.verifiedAt ? ' on ' + esc(fmtInstant(b.verifiedAt)) : '') + (b.verificationNote ? '
' + esc(b.verificationNote) + '' : '') + '
' + : '' + esc(b.rejectionReason || 'Hold expired / Cancelled') + ''; + + return '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; + }).join('') + + '
Ref & AttendeeTicketAmountSubmitted UTRResultAudit Details
' + esc(b.bookingRef) + '
' + esc(b.attendeeAlias) + '
' + esc(b.ticketName) + ' × ' + esc(b.quantity) + '' + money(b.amountPaise) + '' + (b.utrReference ? '' + esc(b.utrReference) + '' : '—') + '' + resPill + '' + auditNote + '
'; + } + h += '
'; + + panel.innerHTML = h; + }); + } + function renderFinanceTab(panel) { panel.innerHTML = '

Loading financial records…

'; api('GET', '/api/organiser/events/' + encodeURIComponent(id) + '/finance').then(function (r) { @@ -1102,6 +1240,101 @@ return; } + if (b.getAttribute('data-action') === 'confirm-upi-payment') { + var bkId = b.getAttribute('data-id'); + var bkRef = b.getAttribute('data-ref'); + var bkAmt = b.getAttribute('data-amt'); + var bkUtr = b.getAttribute('data-utr'); + + var modal = document.createElement('div'); + modal.className = 'org-modal-backdrop'; + modal.innerHTML = '
' + + '

Confirm Direct UPI Payment

' + + '
' + + '
' + + '

Booking Reference: ' + esc(bkRef) + '

' + + '

Amount to Verify: ₹' + esc(bkAmt) + '

' + + (bkUtr ? '

Reported UTR / Ref: ' + esc(bkUtr) + '

' : '

Attendee has not submitted a UTR, but you may confirm if received.

') + + '
' + + '
' + + '⚠️ CRITICAL VERIFICATION REQUIRED:
' + + 'A UTR submission or screenshot is NOT proof of credit. You must independently check your bank or UPI app to ensure ₹' + esc(bkAmt) + ' has actually been credited.' + + '
' + + '' + + '' + + '
' + + '' + + '' + + '
' + + '

' + + '
'; + document.body.appendChild(modal); + + modal.addEventListener('click', function (mev) { + if (mev.target === modal || mev.target.hasAttribute('data-close-modal')) modal.remove(); + }); + + var cform = $('form[data-confirm-upi-form]', modal); + cform.addEventListener('submit', function (mev) { + mev.preventDefault(); + var cMsg = $('[data-confirm-msg]', cform); + var sBtn = $('button[type=submit]', cform); + if (!cform.warningConfirmed.checked) { + cMsg.className = 'form-msg error'; + cMsg.textContent = 'You must acknowledge the verification confirmation.'; + return; + } + sBtn.disabled = true; + api('POST', '/api/organiser/events/' + encodeURIComponent(id) + '/payments/' + encodeURIComponent(bkId) + '/confirm', { + warningConfirmed: true, + note: cform.note.value + }).then(function (cr) { + if (cr.ok) { + modal.remove(); + renderCurrentTab(); + } else { + sBtn.disabled = false; + cMsg.className = 'form-msg error'; + cMsg.textContent = cr.message || 'Could not confirm payment.'; + } + }).catch(function (err) { + sBtn.disabled = false; + cMsg.className = 'form-msg error'; + cMsg.textContent = (err && (err.message || err.error)) || 'Network error.'; + }); + }); + return; + } + + if (b.getAttribute('data-action') === 'reject-upi-payment') { + var rjId = b.getAttribute('data-id'); + var rjRef = b.getAttribute('data-ref'); + var reason = window.prompt('Reject payment for booking ' + rjRef + '?\nReserved seats will be released.\n\nEnter reason:', 'Payment not received in account'); + if (reason == null) return; + if (reason.trim().length < 3) { + alert('Please enter a valid rejection reason (at least 3 characters).'); + return; + } + b.disabled = true; + api('POST', '/api/organiser/events/' + encodeURIComponent(id) + '/payments/' + encodeURIComponent(rjId) + '/reject', { + reason: reason.trim() + }).then(function (rr) { + if (rr.ok) { + renderCurrentTab(); + } else { + alert(rr.message || 'Could not reject payment.'); + b.disabled = false; + } + }).catch(function (err) { + alert((err && (err.message || err.error)) || 'Network error.'); + b.disabled = false; + }); + return; + } + if (b.getAttribute('data-action') === 'cancel-event') { var evReason = window.prompt('Are you sure you want to cancel this event? All active tickets will be cancelled.\n\nEnter reason:', 'Event cancelled by organiser'); if (evReason == null) return; @@ -1991,42 +2224,76 @@ ['custom', 'Custom Category'] ]; - var freeNotice = '
' + - '

Online payment is pending gateway configuration. NIGHTLIFEZ is currently in free-listing only mode.

' + - '

Paid ticket sales and live payment collection are disabled during this phase. All published listings must be free for attendees.

' + + d.paymentMethod = d.paymentMethod || (d.organiserUpiId ? 'direct_upi' : 'free'); + var isDirect = d.paymentMethod === 'direct_upi'; + + var paymentMethodSelector = '
' + + 'Payment Method' + + '
' + + '' + + '' + + '
' + '
'; - var hasPaid = (d.tickets || []).some(function (t) { return t.kind === 'paid' || (t.pricePaise || 0) > 0; }); - var paidNotice = hasPaid - ? '

Paid tickets cannot be published: Convert paid tickets to Free (₹0) to publish this event.

' + - '
' - : ''; + var paymentDetailsBox = ''; + if (isDirect) { + paymentDetailsBox = '
' + + '
' + + '

Direct UPI Configuration

' + + '' + + '
' + + '
' + + text('organiserUpiId', 'Organiser UPI ID*', { max: 256, placeholder: 'e.g. name@okhdfcbank or business@upi', help: 'Attendees transfer ticket payments directly to this UPI ID.' }) + + text('organiserPayeeName', 'Account / Payee Display Name*', { max: 100, placeholder: 'e.g. Rohit Sharma or Nightlife Ventures', help: 'Account holder name displayed in attendee UPI apps.' }) + + '
' + + text('paymentInstructions', 'Payment Instructions for Attendees (Optional)', { max: 1000, area: true, rows: 2, placeholder: 'e.g. Please put your booking reference in the transaction note.', help: 'Shown on the attendee UPI checkout screen.' }) + + '
' + + 'Unverified Destination (Direct payment to your account)' + + '✓ Event payment settings saved with draft' + + '
' + + errSlot('organiserUpiId') + + errSlot('organiserPayeeName') + + '
'; + } else { + paymentDetailsBox = '
' + + '

Free Event Listing: Online payment is not configured yet for this event.

' + + '

Attendees can RSVP and book tickets for free. To sell paid tickets, select "Direct UPI Payment to Organiser" above.

' + + '
'; + } var tiers = (d.tickets || []).map(function (t, i) { var p = 'tickets.' + i; - var isPaid = t.kind === 'paid' || (t.pricePaise || 0) > 0; + var isPaid = isDirect && (t.kind === 'paid' || (t.pricePaise || 0) > 0); var statusPill = isPaid - ? 'Paid (Gateway Pending)' + ? 'Paid (₹' + ((t.pricePaise || 0) / 100) + ')' : 'Free RSVP (₹0)'; - var paidWarning = isPaid - ? '

⚠️ Paid tickets are preserved but cannot be published.

' - : ''; - var defaultAdmit = t.category === 'couple' ? 2 : (t.category === 'group' ? 4 : 1); + var typeAndPrice = isDirect + ? ('
' + + select(p + '.kind', 'Ticket Type', [['paid', 'Paid Pass'], ['free', 'Free Pass']], { def: t.kind || 'paid', rerender: true }) + + (t.kind !== 'free' + ? text(p + '.pricePaise', 'Ticket price (₹)*', { type: 'number', min: 1, max: 100000, inputmode: 'numeric', kind: 'rupees', placeholder: '499', help: 'Attendee transfers ₹' + ((t.pricePaise || 0) / 100) + ' directly to your UPI ID' }) + : '

Price

Free — ₹0

') + + '
') + : ('
' + + '

Ticket Type

Free Pass (₹0)

' + + '

Price

Free — ₹0

' + + '
'); + return '
  • ' + esc(t.name || 'Untitled ticket') + '

    ' + statusPill + '
    ' + - paidWarning + '
    ' + select(p + '.category', 'Ticket category', catOptions, { def: 'general' }) + text(p + '.name', 'Ticket display name', { max: 60, placeholder: 'e.g. Free RSVP / General Admission' }) + '
    ' + - '
    ' + - '

    Ticket Type

    ' + (isPaid ? 'Paid Pass (₹' + ((t.pricePaise || 0) / 100) + ')' : 'Free Pass (₹0)') + '

    ' + - text(p + '.admitCount', 'Admits (guests per ticket)', { type: 'number', min: 1, max: 20, inputmode: 'numeric', kind: 'int', def: defaultAdmit, help: 'E.g. Couple = 2 guests, Group = 4 guests' }) + - '
    ' + + typeAndPrice + '
    ' + - '

    Price

    ' + (isPaid ? '₹' + ((t.pricePaise || 0) / 100) : 'Free — ₹0') + '

    ' + + text(p + '.admitCount', 'Admits (guests per ticket)', { type: 'number', min: 1, max: 20, inputmode: 'numeric', kind: 'int', def: defaultAdmit, help: 'E.g. Couple = 2 guests, Group = 4 guests' }) + text(p + '.quantity', 'Quantity available', { type: 'number', min: 1, max: 5000, inputmode: 'numeric', kind: 'int', placeholder: '50' }) + text(p + '.maxPerBooking', 'Max per booking', { type: 'number', min: 1, max: 20, inputmode: 'numeric', kind: 'int', def: t.category === 'couple' ? 1 : 4 }) + '
    ' + @@ -2039,7 +2306,7 @@ '
  • '; }).join(''); - return card('Payment', freeNotice + paidNotice) + + return card('Payment', paymentMethodSelector + paymentDetailsBox) + card('Ticket types', '

    Quick add:

    ' + Object.keys(CFG.ticketPresets).map(function (k) { return ''; }).join('') + '
    ' + errSlot('tickets') + @@ -2047,7 +2314,7 @@ ((d.tickets || []).length < CFG.limits.tiers ? '' : '')) + card('Inventory', '
    ') + policyCardHtml() + - card('Coming later', '

    These features will be enabled in a future release.

    ', { cls: 'wz-card-muted' }) + + nav('basics', 'features', 'Next: Features'); nav('basics', 'features', 'Next: Features'); } @@ -2099,9 +2366,13 @@ var co = CFG.checkout; var schedDates = (d.schedule && d.schedule.dates && d.schedule.dates.length) ? d.schedule.dates : null; var isMulti = Boolean(d.multiDay) || Boolean(schedDates && schedDates.length > 1); + var isDirect = d.paymentMethod === 'direct_upi' || (d.organiserUpiId && d.organiserPayeeName); var where = d.privateVenue ? [d.area, d.city].filter(Boolean).join(', ') + ' — exact address shared with confirmed guests' : [d.venue, d.area, d.city].filter(Boolean).join(', '); var tix = (d.tickets || []).map(function (t) { - var note = t.kind === 'paid' && !co.available ? ' — Paid ticket — external checkout not configured' : ''; + var note = ''; + if (t.kind === 'paid') { + note = isDirect ? ' · Direct UPI payment to organiser' : (!co.available ? ' — Paid ticket — external checkout not configured' : ''); + } var valid = isMulti ? (t.validOn && t.validOn !== 'all' ? ' · Valid on ' + dayLabel(t.validOn) : ' · Valid for all dates') : ''; return '
  • ' + esc(t.name || 'Untitled') + ' · ' + (t.kind === 'free' ? 'Free' : Number.isInteger(t.pricePaise) ? esc(money(t.pricePaise)) : 'price missing') + ' · ' + esc(Number.isInteger(t.quantity) ? t.quantity : '?') + ' available' + esc(valid) + (f.balance && f.balance.enabled && t.eligibility ? ' · for ' + esc(t.eligibility) : '') + esc(note) + '
  • '; @@ -2113,6 +2384,15 @@ return '
  • ' + esc(dayLabel(s.date)) + ' · ' + esc(s.startLocal.slice(11, 16)) + '–' + esc(s.endLocal.slice(11, 16)) + (s.label ? ' (' + esc(s.label) + ')' : '') + '
  • '; }).join('') + '') : ''; + var paymentPreview = isDirect + ? ('

    Payment Transparency

    ' + + '
    ' + + '

    Recipient: ' + esc(d.organiserPayeeName || 'Organiser') + ' (' + esc(d.organiserUpiId || 'UPI ID') + ')

    ' + + (d.paymentInstructions ? '

    Instructions: ' + esc(d.paymentInstructions) + '

    ' : '') + + '

    Your payment goes directly to the event organiser\'s UPI account. NIGHTLIFEZ does not collect or hold this ticket payment. Your ticket will be confirmed after the organiser verifies receipt.

    ' + + '
    ') + : ''; + return '
    ' + (d.coverImageId ? '' : '') + '

    ' + esc(CAT[d.category] || '') + '' + esc(d.city || '') + '

    ' + @@ -2123,6 +2403,7 @@ '

    Entry

    • Adults 21+ only. Guests carry a photo ID.
    • ' + (f.approval && f.approval.enabled ? '
    • The host approves each guest.
    • ' : '') + '
    ' + (qs.length ? '

    Questions at booking

      ' + qs.map(function (x) { return '
    • ' + esc(x.label || 'Untitled question') + (x.required ? ' (required)' : '') + '
    • '; }).join('') + '
    ' : '') + (pts.length ? '

    Pickup points

      ' + pts.map(function (p) { return '
    • ' + esc(p.name || 'Unnamed') + (p.time ? ' · ' + esc(fmtLocal(p.time)) : '') + '
    • '; }).join('') + '
    ' : '') + + paymentPreview + '

    Cancellation & refunds

    ' + '
    ' + '

    ' + esc(((d.cancellationPolicy && d.cancellationPolicy.template) || 'standard').charAt(0).toUpperCase() + ((d.cancellationPolicy && d.cancellationPolicy.template) || 'standard').slice(1)) + ' Cancellation Policy · 🛡️ 100% Host Cancel Guarantee

    ' + @@ -2137,6 +2418,12 @@ var errs = S.issues.filter(function (i) { return i.severity === 'error'; }); var warns = S.issues.filter(function (i) { return i.severity === 'warning'; }); var label = { basics: 'Basics', tickets: 'Tickets', features: 'Features' }; + var isDirect = S.data.paymentMethod === 'direct_upi' || (S.data.organiserUpiId && S.data.organiserPayeeName); + var readyMsg = isDirect + ? '✓ Everything needed is in place. Your event with direct UPI payment is ready to publish.' + : '✓ Everything needed is in place. Your free event is ready to publish.'; + var pubBtnLabel = isDirect ? 'Publish Event' : 'Publish Free Event'; + var list = function (arr) { return '
      ' + arr.map(function (i) { return '
    • ' + esc(label[i.step] || i.step) + ' ' + esc(i.message) + '
    • '; @@ -2148,20 +2435,28 @@ '' + '
    '; - return card('Before you publish', (errs.length ? '

    ' + errs.length + ' item' + (errs.length === 1 ? '' : 's') + ' to complete before publishing:

    ' + list(errs) : '

    ✓ Everything needed is in place. Your free event is ready to publish.

    ') + + var dialogContent = isDirect + ? ('

    Publish event “' + esc(S.data.title || 'this event') + '”?

    ' + + '

    This event will be published on NIGHTLIFEZ. Attendees will pay ticket amounts directly to your UPI ID: ' + esc(S.data.organiserUpiId) + ' (' + esc(S.data.organiserPayeeName) + ').

    ' + + '

    Direct Organiser UPI: NIGHTLIFEZ does not receive or hold ticket payments. You independently verify receipt in your bank/UPI account before confirming bookings.

    ' + + '' + + '
    ') + : ('

    Publish free event “' + esc(S.data.title || 'this event') + '”?

    ' + + '

    This free event will be published on NIGHTLIFEZ for attendees to discover and book passes' + ((S.data.features || {}).approval && S.data.features.approval.enabled ? ', and guests can send requests to join.' : '.') + '

    ' + + '

    This is a free event listing. All tickets are ₹0 and no payment collection will occur.

    ' + + '' + + '
    '); + + return card('Before you publish', (errs.length ? '

    ' + errs.length + ' item' + (errs.length === 1 ? '' : 's') + ' to complete before publishing:

    ' + list(errs) : '

    ' + esc(readyMsg) + '

    ') + (warns.length ? '

    Suggested tips:

    ' + list(warns) : '')) + card('What guests will see', editNav + attendeePreview()) + '
    ' + '' + '' + 'Preview booking journey' + - '
    ' + + '
    ' + (errs.length ? '

    Complete the items above to publish. Your draft is automatically saved.

    ' : '') + - '

    Publish free event “' + esc(S.data.title || 'this event') + '”?

    ' + - '

    This free event will be published on NIGHTLIFEZ for attendees to discover and book passes' + ((S.data.features || {}).approval && S.data.features.approval.enabled ? ', and guests can send requests to join.' : '.') + '

    ' + - '

    This is a free event listing. All tickets are ₹0 and no payment collection will occur.

    ' + - '' + - '
    '; + '' + dialogContent + ''; } function screenPublished() { @@ -2279,8 +2574,14 @@ var p = clone(preset); p.id = uid(); p.category = p.category || key || 'general'; - p.kind = 'free'; - p.pricePaise = 0; + var isDirect = S.data && S.data.paymentMethod === 'direct_upi'; + if (isDirect && key !== 'free') { + p.kind = 'paid'; + p.pricePaise = key === 'vip' ? 99900 : (key === 'couple' ? 89900 : (key === 'early_bird' ? 29900 : 49900)); + } else { + p.kind = 'free'; + p.pricePaise = 0; + } p.admitCount = p.admitCount || (p.category === 'couple' ? 2 : p.category === 'group' ? 4 : 1); p.quantity = (Number.isInteger(p.quantity) && p.quantity > 0 && p.quantity <= 5000) ? p.quantity : 50; p.minPerBooking = p.minPerBooking || 1; @@ -2458,6 +2759,29 @@ else if (daylist.length > 1) daylist.splice(daypos, 1); S.data.schedule.recurring.daysOfWeek = daylist; touch(); return render(); + case 'set-pay-method': + var payMethod = b.getAttribute('data-method') || b.value; + S.data.paymentMethod = payMethod; + if (payMethod === 'free') { + (S.data.tickets || []).forEach(function (x) { x.kind = 'free'; x.pricePaise = 0; }); + } + touch(); return render(); + case 'use-saved-upi': + b.disabled = true; + api('GET', '/api/organiser/payment-settings').then(function (res) { + b.disabled = false; + if (res.ok && res.settings && res.settings.configured) { + S.data.organiserUpiId = res.settings.upiId || S.data.organiserUpiId; + S.data.organiserPayeeName = res.settings.payeeName || S.data.organiserPayeeName; + touch(); + render(); + } else { + window.alert('No saved business payment details found. Please enter your UPI ID and payee name directly.'); + } + }).catch(function () { + b.disabled = false; + }); + return; case 'convert-all-free': (S.data.tickets || []).forEach(function (x) { x.kind = 'free'; x.pricePaise = 0; }); touch(); return render(); diff --git a/test/direct-organiser-upi.test.js b/test/direct-organiser-upi.test.js new file mode 100644 index 0000000..ab39209 --- /dev/null +++ b/test/direct-organiser-upi.test.js @@ -0,0 +1,752 @@ +// test/direct-organiser-upi.test.js +// Automated test suite for Direct Organiser UPI Payment Integration. +// Covers all 15 required test scenarios: +// 1. Organiser configures UPI during event creation +// 2. UPI details persist after refresh +// 3. Event-specific UPI details do not leak between organisers +// 4. Paid event publishes successfully with valid direct UPI details +// 5. Paid event cannot publish without valid UPI details +// 6. Attendee receives the correct UPI payment intent and QR amount +// 7. Attendee cannot tamper with the UPI recipient or amount +// 8. UPI app redirect does not confirm payment +// 9. UTR submission does not automatically confirm payment +// 10. Organiser confirmation issues tickets exactly once +// 11. Unauthorised users cannot confirm payments +// 12. Rejected and expired payments restore inventory +// 13. Concurrent bookings cannot overbook inventory +// 14. Free event bookings remain unaffected +// 15. Existing paid drafts are preserved + +import { test, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { + resetDb, startServer, stopServer, Client, db, signedInClient, clearCalls +} from './helpers.js'; + +let org1; +let org2; +let attendee1; +let attendee2; +let stranger; + +/** IST wall-clock 'YYYY-MM-DDTHH:mm', `days` from now at 19:00. */ +function istLocal(days, hh = '19:00') { + const d = new Date(Date.now() + days * 864e5 + 5.5 * 3600e3).toISOString().slice(0, 10); + return `${d}T${hh}`; +} + +async function createOrganiser() { + const c = await signedInClient(); + await db.query('UPDATE users SET organiser_enabled = true WHERE id = $1', [c.userId]); + return c; +} + +before(async () => { + // Direct UPI must function with zero live gateway flags + process.env.ENABLE_LIVE_PAYMENTS = 'false'; + process.env.UPI_CHECKOUT_ENABLED = 'false'; + + await resetDb(); + await startServer(); + + org1 = await createOrganiser(); + org2 = await createOrganiser(); + attendee1 = await signedInClient(); + attendee2 = await signedInClient(); + stranger = await signedInClient(); +}); + +after(async () => { + await stopServer(); +}); + +beforeEach(clearCalls); + +function validDirectUpiDraftData(overrides = {}) { + return { + template: 'social', + category: 'nightlife', + title: 'Neon Underground Techno Night', + timezone: 'Asia/Kolkata', + startLocal: istLocal(5, '21:00'), + endLocal: istLocal(6, '03:00'), + multiDay: false, + venue: 'Warehouse 9, Indiranagar', + city: 'Bengaluru', + area: 'Indiranagar', + privateVenue: false, + description: 'Underground electronic music night. 21+ only, government photo ID mandatory.', + paymentMethod: 'direct_upi', + organiserUpiId: 'technohost@okhdfcbank', + organiserPayeeName: 'Techno Host Events', + paymentInstructions: 'Transfer via GooglePay/PhonePe to technohost@okhdfcbank and submit your 12-digit UTR.', + refundPolicy: 'Full refund if cancelled 48h before event.', + cancellationPolicy: { + template: 'standard', + primaryDeadlineHours: 48, + primaryRefundPercent: 100, + secondaryDeadlineHours: 24, + secondaryRefundPercent: 50, + noRefundHours: 24, + allowTransfers: false + }, + tickets: [ + { + id: 'vip_tier', + name: 'VIP Entry', + kind: 'paid', + pricePaise: 49900, + quantity: 10, + maxPerBooking: 4, + validOn: 'all' + } + ], + features: {}, + ...overrides + }; +} + +// ----------------------------------------------------------------------------- +// Scenario 1: Organiser configures UPI during event creation +// ----------------------------------------------------------------------------- +test('1. Organiser configures UPI during event creation', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + assert.equal(r.status, 201); + const draftId = r.json.draft.id; + const version = r.json.draft.version; + + const data = validDirectUpiDraftData(); + const putRes = await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data, + step: 'preview', + version + }); + + assert.equal(putRes.status, 200, putRes.text); + const savedDraft = putRes.json.draft; + assert.equal(savedDraft.data.paymentMethod, 'direct_upi'); + assert.equal(savedDraft.data.organiserUpiId, 'technohost@okhdfcbank'); + assert.equal(savedDraft.data.organiserPayeeName, 'Techno Host Events'); + assert.equal(savedDraft.data.paymentInstructions, 'Transfer via GooglePay/PhonePe to technohost@okhdfcbank and submit your 12-digit UTR.'); + assert.equal(savedDraft.data.tickets[0].kind, 'paid'); + assert.equal(savedDraft.data.tickets[0].pricePaise, 49900); +}); + +// ----------------------------------------------------------------------------- +// Scenario 2: UPI details persist after refresh +// ----------------------------------------------------------------------------- +test('2. UPI details persist after refresh', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'social' }); + const draftId = r.json.draft.id; + const data = validDirectUpiDraftData({ + organiserUpiId: 'rooftop.music@icici', + organiserPayeeName: 'Rooftop Sessions' + }); + + await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data, + step: 'preview', + version: r.json.draft.version + }); + + // Fetch draft again as if page reloaded + const fetchRes = await org1.get(`/api/organiser/drafts/${draftId}`); + assert.equal(fetchRes.status, 200); + const reloaded = fetchRes.json.draft; + + assert.equal(reloaded.data.paymentMethod, 'direct_upi'); + assert.equal(reloaded.data.organiserUpiId, 'rooftop.music@icici'); + assert.equal(reloaded.data.organiserPayeeName, 'Rooftop Sessions'); + assert.equal(reloaded.data.tickets[0].pricePaise, 49900); +}); + +// ----------------------------------------------------------------------------- +// Scenario 3: Event-specific UPI details do not leak between organisers +// ----------------------------------------------------------------------------- +test('3. Event-specific UPI details do not leak between organisers', async () => { + // org1 created a draft with rooftop.music@icici + const r1 = await org1.post('/api/organiser/drafts', { template: 'social' }); + await org1.req('PUT', `/api/organiser/drafts/${r1.json.draft.id}`, { + data: validDirectUpiDraftData({ organiserUpiId: 'secret1@okhdfcbank' }), + step: 'preview', + version: r1.json.draft.version + }); + + // org2 creates their own draft; defaults must be free and empty + const r2 = await org2.post('/api/organiser/drafts', { template: 'social' }); + assert.equal(r2.status, 201); + const org2Draft = r2.json.draft; + assert.ok(!org2Draft.data.paymentMethod || org2Draft.data.paymentMethod === 'free'); + assert.ok(!org2Draft.data.organiserUpiId, 'Must not have org1 UPI ID'); + + // org2 attempts to fetch org1's draft -> 404/403 + const leakAttempt = await org2.get(`/api/organiser/drafts/${r1.json.draft.id}`); + assert.ok(leakAttempt.status === 403 || leakAttempt.status === 404, 'Must not access other organiser draft'); +}); + +// ----------------------------------------------------------------------------- +// Scenario 4: Paid event publishes successfully with valid direct UPI details +// ----------------------------------------------------------------------------- +test('4. Paid event publishes successfully with valid direct UPI details without gateway', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const dId = r.json.draft.id; + const data = validDirectUpiDraftData({ + organiserUpiId: 'directfest@okaxis', + organiserPayeeName: 'Direct Fest Team' + }); + + const saveRes = await org1.req('PUT', `/api/organiser/drafts/${dId}`, { + data, + step: 'preview', + version: r.json.draft.version + }); + assert.equal(saveRes.status, 200); + + // Publish draft + const pubRes = await org1.post(`/api/organiser/drafts/${dId}/publish`, { + version: saveRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + assert.ok(pubRes.json.eventId); + + const eventRow = await db.one('SELECT * FROM events WHERE id = $1', [pubRes.json.eventId]); + assert.equal(eventRow.payment_method, 'direct_upi'); + assert.equal(eventRow.organiser_upi_id, 'directfest@okaxis'); + assert.equal(eventRow.organiser_payee_name, 'Direct Fest Team'); + assert.equal(eventRow.checkout_mode, 'upi_direct'); + + // Verify public view + const publicRes = await org1.get(pubRes.json.path); + assert.equal(publicRes.status, 200); +}); + +// ----------------------------------------------------------------------------- +// Scenario 5: Paid event cannot publish without valid UPI details +// ----------------------------------------------------------------------------- +test('5. Paid event cannot publish without valid UPI details', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const dId = r.json.draft.id; + + // Invalid: paymentMethod is direct_upi but organiserUpiId is invalid + const invalidData = validDirectUpiDraftData({ + organiserUpiId: 'invalid-upi-no-vpa', + organiserPayeeName: '' + }); + + const saveRes = await org1.req('PUT', `/api/organiser/drafts/${dId}`, { + data: invalidData, + step: 'preview', + version: r.json.draft.version + }); + assert.equal(saveRes.status, 200); + + // Issues should report the problems + const issues = saveRes.json.draft.issues; + assert.ok(issues.some(i => i.field === 'organiserUpiId')); + assert.ok(issues.some(i => i.field === 'organiserPayeeName')); + + // Publish must fail with 422 + const pubRes = await org1.post(`/api/organiser/drafts/${dId}/publish`, { + version: saveRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 422); + assert.match(pubRes.text, /valid UPI ID|organiser payee name/i); +}); + +// ----------------------------------------------------------------------------- +// Helper to publish a direct UPI event for checkout testing +// ----------------------------------------------------------------------------- +let directUpiEvent; +let directUpiTier; + +async function setupDirectUpiEvent() { + const r = await org1.post('/api/organiser/drafts', { template: 'social' }); + const dId = r.json.draft.id; + const data = validDirectUpiDraftData({ + title: 'Soundwave Festival 2026', + organiserUpiId: 'soundwave@hdfcbank', + organiserPayeeName: 'Soundwave Live', + tickets: [ + { + id: 'tier1', + name: 'Pass', + kind: 'paid', + pricePaise: 25000, // ₹250.00 + quantity: 5, + maxPerBooking: 3, + validOn: 'all' + } + ] + }); + + const saveRes = await org1.req('PUT', `/api/organiser/drafts/${dId}`, { + data, + step: 'preview', + version: r.json.draft.version + }); + const pubRes = await org1.post(`/api/organiser/drafts/${dId}/publish`, { + version: saveRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + + const event = await db.one('SELECT * FROM events WHERE id = $1', [pubRes.json.eventId]); + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.id]); + return { event, tier }; +} + +// ----------------------------------------------------------------------------- +// Scenario 6: Attendee receives correct UPI payment intent and QR amount +// ----------------------------------------------------------------------------- +test('6. Attendee receives correct UPI payment intent and QR amount', async () => { + const { event, tier } = await setupDirectUpiEvent(); + directUpiEvent = event; + directUpiTier = tier; + + // Attendee initiates checkout for 2 tickets: 2 × 25000 = 50000 paise (₹500.00) + const checkoutRes = await attendee1.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=2`); + assert.equal(checkoutRes.status, 200); + + // Verify response contains payee name, UPI ID, and calculated amount + assert.match(checkoutRes.text, /Soundwave Live/); + assert.match(checkoutRes.text, /soundwave@hdfcbank/); + assert.match(checkoutRes.text, /₹500\.00/); + + // Verify payment intent deep link + assert.match(checkoutRes.text, /pa=soundwave%40hdfcbank/); + assert.match(checkoutRes.text, /pn=Soundwave(?:\+|%20)Live/); + assert.match(checkoutRes.text, /am=500\.00/); + assert.match(checkoutRes.text, /cu=INR/); + + // Check booking created in DB + const booking = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 AND ticket_type_id = $3 ORDER BY created_at DESC LIMIT 1`, + [event.id, attendee1.userId, tier.id] + ); + assert.ok(booking); + assert.equal(booking.status, 'pending_payment'); + assert.equal(booking.direct_upi_status, 'awaiting_payment'); + assert.equal(booking.amount_paise, 50000); + assert.equal(booking.quantity, 2); + assert.ok(booking.booking_ref.startsWith('NLZ-')); +}); + +// ----------------------------------------------------------------------------- +// Scenario 7: Attendee cannot tamper with UPI recipient or amount +// ----------------------------------------------------------------------------- +test('7. Attendee cannot tamper with UPI recipient or amount', async () => { + const { event, tier } = await setupDirectUpiEvent(); + + // Try to tamper with amount or custom query params + const checkoutRes = await attendee2.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1&amount=1.00&pa=hacker@upi` + ); + assert.equal(checkoutRes.status, 200); + + // Server must strictly enforce the real tier price and organiser UPI + assert.match(checkoutRes.text, /am=250\.00/); + assert.doesNotMatch(checkoutRes.text, /am=1\.00/); + assert.match(checkoutRes.text, /pa=soundwave%40hdfcbank/); + assert.doesNotMatch(checkoutRes.text, /hacker@upi/); + + const booking = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.id, attendee2.userId] + ); + assert.equal(booking.amount_paise, 25000, 'Calculated server-side from tier pricePaise'); +}); + +// ----------------------------------------------------------------------------- +// Scenario 8: UPI app redirect does not confirm payment +// ----------------------------------------------------------------------------- +test('8. UPI app redirect does not confirm payment', async () => { + const { event, tier } = await setupDirectUpiEvent(); + + const checkoutRes = await attendee1.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1`); + assert.equal(checkoutRes.status, 200); + + const booking = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.id, attendee1.userId] + ); + + // Status check API + const statusRes = await attendee1.get(`/api/checkout/upi/booking-status/${booking.id}`); + assert.equal(statusRes.status, 200); + assert.equal(statusRes.json.bookingStatus, 'pending_payment'); + assert.equal(statusRes.json.status, 'awaiting_payment'); + assert.equal(statusRes.json.isConfirmed, false); + + // Tickets must not exist + const tickets = (await db.query(`SELECT * FROM tickets WHERE booking_id = $1`, [booking.id])).rows; + assert.equal(tickets.length, 0); +}); + +// ----------------------------------------------------------------------------- +// Scenario 9: UTR submission does not automatically confirm payment +// ----------------------------------------------------------------------------- +test('9. UTR submission does not automatically confirm payment', async () => { + const { event, tier } = await setupDirectUpiEvent(); + + await attendee1.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1`); + const booking = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.id, attendee1.userId] + ); + + // Attendee submits UTR reference + const reportRes = await attendee1.post('/api/checkout/upi/report-payment', { + bookingId: booking.id, + utr: '987654321098' + }); + assert.equal(reportRes.status, 200); + assert.equal(reportRes.json.ok, true); + assert.equal(reportRes.json.status, 'payment_reported'); + + // Verify in DB: booking is still pending_payment, not confirmed! + const updatedBooking = await db.one(`SELECT * FROM bookings WHERE id = $1`, [booking.id]); + assert.equal(updatedBooking.status, 'pending_payment'); + assert.equal(updatedBooking.direct_upi_status, 'payment_reported'); + assert.equal(updatedBooking.utr_reference, '987654321098'); + + // Zero tickets issued + const tickets = (await db.query(`SELECT * FROM tickets WHERE booking_id = $1`, [booking.id])).rows; + assert.equal(tickets.length, 0); +}); + +// ----------------------------------------------------------------------------- +// Scenario 10: Organiser confirmation issues tickets exactly once +// ----------------------------------------------------------------------------- +test('10. Organiser confirmation issues tickets exactly once', async () => { + const { event, tier } = await setupDirectUpiEvent(); + + await attendee1.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=2`); + const booking = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.id, attendee1.userId] + ); + await attendee1.post('/api/checkout/upi/report-payment', { + bookingId: booking.id, + utr: '112233445566' + }); + + // Organiser views payment dashboard + const listRes = await org1.get(`/api/organiser/events/${event.id}/payments`); + assert.equal(listRes.status, 200); + assert.equal(listRes.json.organiserDestination.upiId, 'soundwave@hdfcbank'); + assert.ok(listRes.json.bookings.some(b => b.id === booking.id && b.utrReference === '112233445566')); + + // Organiser confirms with mandatory warning acknowledgment + const confirmRes = await org1.post(`/api/organiser/events/${event.id}/payments/${booking.id}/confirm`, { + warningConfirmed: true, + note: 'Verified in HDFC merchant portal' + }); + assert.equal(confirmRes.status, 200); + assert.equal(confirmRes.json.ok, true); + assert.equal(confirmRes.json.status, 'payment_confirmed'); + + // Booking is confirmed + const confirmedBooking = await db.one(`SELECT * FROM bookings WHERE id = $1`, [booking.id]); + assert.equal(confirmedBooking.status, 'confirmed'); + assert.equal(confirmedBooking.direct_upi_status, 'payment_confirmed'); + assert.equal(confirmedBooking.verified_by_user_id, org1.userId); + + // Tickets issued exactly once for quantity (2) + const tickets = (await db.query(`SELECT * FROM tickets WHERE booking_id = $1`, [booking.id])).rows; + assert.equal(tickets.length, 2); + + // Audit entry logged + const audit = await db.one( + `SELECT * FROM direct_upi_payment_audits WHERE booking_id = $1 AND to_status = 'payment_confirmed'`, + [booking.id] + ); + assert.ok(audit); + assert.equal(audit.actor_user_id, org1.userId); + + // Repeat confirmation is idempotent and does not create duplicate tickets + const repeatRes = await org1.post(`/api/organiser/events/${event.id}/payments/${booking.id}/confirm`, { + warningConfirmed: true + }); + assert.equal(repeatRes.status, 200); + const ticketsAfter = (await db.query(`SELECT * FROM tickets WHERE booking_id = $1`, [booking.id])).rows; + assert.equal(ticketsAfter.length, 2, 'No duplicate tickets issued on repeat confirmation'); +}); + +// ----------------------------------------------------------------------------- +// Scenario 11: Unauthorised users cannot confirm payments +// ----------------------------------------------------------------------------- +test('11. Unauthorised users cannot confirm payments', async () => { + const { event, tier } = await setupDirectUpiEvent(); + + await attendee1.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1`); + const booking = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.id, attendee1.userId] + ); + + // 1. Attendee tries to confirm their own booking -> 403 + const selfConfirm = await attendee1.post(`/api/organiser/events/${event.id}/payments/${booking.id}/confirm`, { + warningConfirmed: true + }); + assert.equal(selfConfirm.status, 403); + + // 2. Stranger tries to confirm -> 403 + const strangerConfirm = await stranger.post(`/api/organiser/events/${event.id}/payments/${booking.id}/confirm`, { + warningConfirmed: true + }); + assert.equal(strangerConfirm.status, 403); + + // 3. Organiser confirms without warningConfirmed -> 400 + const noWarningConfirm = await org1.post(`/api/organiser/events/${event.id}/payments/${booking.id}/confirm`, { + warningConfirmed: false + }); + assert.equal(noWarningConfirm.status, 400); + assert.match(noWarningConfirm.text, /independently verified/i); +}); + +// ----------------------------------------------------------------------------- +// Scenario 12: Rejected and expired payments restore inventory +// ----------------------------------------------------------------------------- +test('12. Rejected and expired payments restore inventory', async () => { + // Create an event with capacity = 2 + const r = await org1.post('/api/organiser/drafts', { template: 'social' }); + const dId = r.json.draft.id; + const data = validDirectUpiDraftData({ + title: 'Intimate Masterclass', + organiserUpiId: 'masterclass@icici', + organiserPayeeName: 'Masterclass Coach', + tickets: [ + { + id: 'tier1', + name: 'Spot', + kind: 'paid', + pricePaise: 10000, + quantity: 2, + maxPerBooking: 2, + validOn: 'all' + } + ] + }); + + const saveRes = await org1.req('PUT', `/api/organiser/drafts/${dId}`, { + data, + step: 'preview', + version: r.json.draft.version + }); + const pubRes = await org1.post(`/api/organiser/drafts/${dId}/publish`, { + version: saveRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200); + + const event = await db.one('SELECT * FROM events WHERE id = $1', [pubRes.json.eventId]); + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.id]); + + // Attendee 1 reserves 2 spots (fills all inventory) + const bk1 = await attendee1.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=2`); + assert.equal(bk1.status, 200); + + const booking1 = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.id, attendee1.userId] + ); + + // Attendee 2 tries to book -> inventory full + const bk2 = await attendee2.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1`); + assert.equal(bk2.status, 409); + + // Organiser rejects Attendee 1's payment + const rejectRes = await org1.post(`/api/organiser/events/${event.id}/payments/${booking1.id}/reject`, { + reason: 'Payment not found in bank statement' + }); + assert.equal(rejectRes.status, 200); + assert.equal(rejectRes.json.status, 'payment_rejected'); + + const rejectedBooking = await db.one(`SELECT * FROM bookings WHERE id = $1`, [booking1.id]); + assert.equal(rejectedBooking.status, 'cancelled'); + assert.equal(rejectedBooking.direct_upi_status, 'payment_rejected'); + + // Now inventory is restored! Attendee 2 can book + const bk2Retry = await attendee2.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1`); + assert.equal(bk2Retry.status, 200); + + // Expired hold test: artificially expire booking 2 + const booking2 = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.id, attendee2.userId] + ); + await db.query(`UPDATE bookings SET hold_expires_at = now() - interval '5 minutes' WHERE id = $1`, [booking2.id]); + + // Attendee 1 can now book 2 tickets again because expired hold released seats + const bk1Retry = await attendee1.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=2`); + assert.equal(bk1Retry.status, 200); +}); + +// ----------------------------------------------------------------------------- +// Scenario 13: Concurrent bookings cannot overbook inventory +// ----------------------------------------------------------------------------- +test('13. Concurrent bookings cannot overbook inventory', async () => { + // Event with only 1 ticket + const r = await org1.post('/api/organiser/drafts', { template: 'social' }); + const dId = r.json.draft.id; + const data = validDirectUpiDraftData({ + title: 'One-on-One VIP Mentorship', + organiserUpiId: 'mentor@upi', + organiserPayeeName: 'Solo Mentor', + tickets: [ + { + id: 'tier1', + name: 'Seat', + kind: 'paid', + pricePaise: 50000, + quantity: 1, + maxPerBooking: 1, + validOn: 'all' + } + ] + }); + + const saveRes = await org1.req('PUT', `/api/organiser/drafts/${dId}`, { + data, + step: 'preview', + version: r.json.draft.version + }); + const pubRes = await org1.post(`/api/organiser/drafts/${dId}/publish`, { + version: saveRes.json.draft.version, + confirm: true + }); + const event = await db.one('SELECT * FROM events WHERE id = $1', [pubRes.json.eventId]); + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.id]); + + // Attempt concurrent requests for the single ticket + const [res1, res2] = await Promise.all([ + attendee1.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1`), + attendee2.get(`/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1`) + ]); + + const successCount = [res1, res2].filter(r => r.status === 200).length; + const failureCount = [res1, res2].filter(r => r.status === 409).length; + + assert.equal(successCount, 1, 'Exactly one concurrent booking succeeds'); + assert.equal(failureCount, 1, 'The other concurrent booking is rejected with 409'); +}); + +// ----------------------------------------------------------------------------- +// Scenario 14: Free event bookings remain unaffected +// ----------------------------------------------------------------------------- +test('14. Free event bookings remain unaffected', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'social' }); + const dId = r.json.draft.id; + const data = validDirectUpiDraftData({ + title: 'Free Community Meetup', + paymentMethod: 'free', + organiserUpiId: undefined, + organiserPayeeName: undefined, + tickets: [ + { + id: 'free_tier', + name: 'Community Pass', + kind: 'free', + pricePaise: 0, + quantity: 20, + maxPerBooking: 2, + validOn: 'all' + } + ] + }); + + const saveRes = await org1.req('PUT', `/api/organiser/drafts/${dId}`, { + data, + step: 'preview', + version: r.json.draft.version + }); + const pubRes = await org1.post(`/api/organiser/drafts/${dId}/publish`, { + version: saveRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200); + + const event = await db.one('SELECT * FROM events WHERE id = $1', [pubRes.json.eventId]); + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.id]); + + // Attendee books free pass + const bookRes = await attendee1.post(`/api/events/${event.id}/book`, { + ticketTypeId: tier.id, + quantity: 1 + }); + assert.equal(bookRes.status, 200); + assert.equal(bookRes.json.ok, true); + + // Booking is immediately confirmed + const booking = await db.one(`SELECT * FROM bookings WHERE id = $1`, [bookRes.json.bookingId]); + assert.equal(booking.status, 'confirmed'); + assert.equal(booking.amount_paise, 0); + + // Tickets issued immediately + const tickets = (await db.query(`SELECT * FROM tickets WHERE booking_id = $1`, [booking.id])).rows; + assert.equal(tickets.length, 1); +}); + +// ----------------------------------------------------------------------------- +// Scenario 15: Existing paid drafts are preserved +// ----------------------------------------------------------------------------- +test('15. Existing paid drafts are preserved', async () => { + // Simulate an older draft created without paymentMethod explicitly set + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const dId = r.json.draft.id; + + // Raw database insert of an older draft with paid tickets + const oldDraftData = { + title: 'Vintage Party Draft', + category: 'nightlife', + timezone: 'Asia/Kolkata', + city: 'Bengaluru', + tickets: [ + { + id: 'legacy_vip', + name: 'Legacy VIP', + kind: 'paid', + pricePaise: 75000, + quantity: 15, + maxPerBooking: 2 + } + ] + }; + + await db.query( + `UPDATE event_drafts SET data = $1 WHERE id = $2`, + [JSON.stringify(oldDraftData), dId] + ); + + // Organiser fetches draft: data is preserved, not wiped or converted to free + const fetchRes = await org1.get(`/api/organiser/drafts/${dId}`); + assert.equal(fetchRes.status, 200); + const draft = fetchRes.json.draft; + + assert.equal(draft.data.tickets[0].name, 'Legacy VIP'); + assert.equal(draft.data.tickets[0].kind, 'paid'); + assert.equal(draft.data.tickets[0].pricePaise, 75000); + + // Organiser adapts draft by configuring UPI details + const updateRes = await org1.req('PUT', `/api/organiser/drafts/${dId}`, { + data: { + ...draft.data, + startLocal: istLocal(5, '20:00'), + endLocal: istLocal(5, '23:00'), + venue: 'Legacy Club', + paymentMethod: 'direct_upi', + organiserUpiId: 'legacyhost@axisbank', + organiserPayeeName: 'Legacy Host' + }, + step: 'preview', + version: draft.version + }); + assert.equal(updateRes.status, 200); + + // Ticket remains paid at ₹750.00 + assert.equal(updateRes.json.draft.data.tickets[0].kind, 'paid'); + assert.equal(updateRes.json.draft.data.tickets[0].pricePaise, 75000); + assert.equal(updateRes.json.draft.data.paymentMethod, 'direct_upi'); +}); diff --git a/test/god-mode-e2e-workflow-matrix.test.js b/test/god-mode-e2e-workflow-matrix.test.js index 5d2a6fe..92c3e2c 100644 --- a/test/god-mode-e2e-workflow-matrix.test.js +++ b/test/god-mode-e2e-workflow-matrix.test.js @@ -1611,7 +1611,7 @@ test('H6. Migration 031 Pre-Migration State & Idempotency: isolated schema seede assert.equal(legacyVenue.name, 'Royal Heritage Ballroom'); // 3. Apply migration 031 using the actual migration runner (not executing SQL directly) - const mig031Ran = await migrate({ client, log: false }); + const mig031Ran = await migrate({ client, target: '031_venue_self_service_onboarding.sql', log: false }); assert.deepEqual(mig031Ran, ['031_venue_self_service_onboarding.sql'], 'Migration runner must apply only 031'); // 4. Verify legacy venues retain their intended status and visibility @@ -1655,7 +1655,7 @@ test('H6. Migration 031 Pre-Migration State & Idempotency: isolated schema seede assert.equal(draftDiscovery.length, 0, 'New draft venue must be excluded from public discovery'); // 6. Run the migration runner a second time and verify it reports no pending migration and causes no schema/data changes - const secondRan = await migrate({ client, log: false }); + const secondRan = await migrate({ client, target: '031_venue_self_service_onboarding.sql', log: false }); assert.deepEqual(secondRan, [], 'Second migration run must report zero pending migrations'); // Verify data and schema remain identical after second run diff --git a/test/migrations.test.js b/test/migrations.test.js index 5a35208..7e9a212 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 29 migrations currently exist: 003 through 031 - assert.equal(files.length, 29, `expected 29 migration files, got ${files.length}: ${files.join(', ')}`); + // Exactly 30 migrations currently exist: 003 through 032 + assert.equal(files.length, 30, `expected 30 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_', '025_', '026_', '027_', '028_', '029_', '030_', '031_' + '009_', '010_', '011_', '012_', '013_', '014_', '015_', '016_', '017_', '018_', '019_', '020_', '021_', '022_', '023_', '024_', '025_', '026_', '027_', '028_', '029_', '030_', '031_', '032_' ]; 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 29 migrations in correct order', async () => { +test('schema_migrations table records all 30 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, 29); + assert.equal(rows.length, 30); 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 29 + // Total count in schema_migrations must remain exactly 30 const countRes = await db.one('SELECT count(*)::int AS n FROM schema_migrations'); - assert.equal(countRes.n, 29); + assert.equal(countRes.n, 30); }); test('migration policy respects environment boundaries', () => { @@ -559,3 +559,31 @@ test('migration 031: venue self-service onboarding schema objects exist', async assert.ok(claimsCols.includes('business_proof_type'), 'venue_claims must have business_proof_type'); assert.ok(claimsCols.includes('status'), 'venue_claims must have status'); }); + +test('migration 032: direct organiser upi payments schema objects exist', async () => { + const eventCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'events'` + )).rows.map((r) => r.column_name); + assert.ok(eventCols.includes('payment_method'), 'events must have payment_method'); + assert.ok(eventCols.includes('organiser_upi_id'), 'events must have organiser_upi_id'); + assert.ok(eventCols.includes('organiser_payee_name'), 'events must have organiser_payee_name'); + assert.ok(eventCols.includes('payment_instructions'), 'events must have payment_instructions'); + + const bookingCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'bookings'` + )).rows.map((r) => r.column_name); + assert.ok(bookingCols.includes('booking_ref'), 'bookings must have booking_ref'); + assert.ok(bookingCols.includes('direct_upi_status'), 'bookings must have direct_upi_status'); + assert.ok(bookingCols.includes('utr_reference'), 'bookings must have utr_reference'); + assert.ok(bookingCols.includes('payment_reported_at'), 'bookings must have payment_reported_at'); + assert.ok(bookingCols.includes('verified_by_user_id'), 'bookings must have verified_by_user_id'); + assert.ok(bookingCols.includes('verified_at'), 'bookings must have verified_at'); + + const auditCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'direct_upi_payment_audits'` + )).rows.map((r) => r.column_name); + assert.ok(auditCols.includes('booking_id'), 'direct_upi_payment_audits must have booking_id'); + assert.ok(auditCols.includes('event_id'), 'direct_upi_payment_audits must have event_id'); + assert.ok(auditCols.includes('actor_user_id'), 'direct_upi_payment_audits must have actor_user_id'); + assert.ok(auditCols.includes('to_status'), 'direct_upi_payment_audits must have to_status'); +});