diff --git a/e2e/multi-date-wizard.spec.js b/e2e/multi-date-wizard.spec.js index b26082a..6ffa259 100644 --- a/e2e/multi-date-wizard.spec.js +++ b/e2e/multi-date-wizard.spec.js @@ -86,7 +86,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () => // Verify Payment contradiction notice const payNotice = page.locator('.notice-warn'); await expect(payNotice).toBeVisible(); - await expect(payNotice).toContainText('Online payment is not configured yet'); + await expect(payNotice).toContainText(/Online payment is (?:pending gateway configuration|not configured yet)/); // Verify quick-add chips exist and are accessible const quickAddGeneral = page.locator('button.chip[data-act="add-tier"][data-preset="general"]'); @@ -101,7 +101,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () => // Check that paid tier displays draft indicator and warning const draftPill = page.locator('.pill-draft').first(); await expect(draftPill).toBeVisible(); - await expect(draftPill).toContainText('Draft — External Checkout Pending'); + await expect(draftPill).toContainText(/Paid \((?:Gateway Pending|Draft — External Checkout Pending)\)/); // Capture Step 2 evidence await page.screenshot({ path: path.join(ARTIFACT_DIR, 'multi-date-tickets-draft-state.png'), fullPage: true }); diff --git a/lib/admin-roles.js b/lib/admin-roles.js index 566c6c6..fbd59c1 100644 --- a/lib/admin-roles.js +++ b/lib/admin-roles.js @@ -26,6 +26,7 @@ export const ADMIN_TABS = [ ['insights', 'Insights', R.INSIGHTS], ['discovery', 'Discovery', R.DISCOVERY], ['events', 'Events', R.ANY], + ['finance', 'Finance & Fees', R.FINANCE_VIEW], ['bookings', 'Bookings & payments', R.BOOKINGS], ['orders', 'Orders (SuperProfile)', R.ORDERS], ['memberships', 'Memberships', R.MEMBERSHIPS], diff --git a/lib/handlers/admin.js b/lib/handlers/admin.js index 06ceb4e..8133465 100644 --- a/lib/handlers/admin.js +++ b/lib/handlers/admin.js @@ -30,6 +30,18 @@ import { getSuppressionsList } from '../services/notification-dispatcher.js'; import { listOnboardingAudits } from '../services/community-onboarding.js'; +import { + getAdminFinanceOverview, + getVerificationQueue, + confirmFeePayment, + rejectFeePayment, + investigateFeePayment, + setFeeRule, + getActiveFeeRule, + extendPaymentDeadline, + generateAdminFinanceCsv +} from '../services/finance.js'; +import { uuid } from '../validate.js'; /** Resolve the admin for this request (bootstrapping the owner once), or throw 401/403. */ @@ -1284,4 +1296,152 @@ export async function updateCityStatus(ctx) { sendJson(ctx.res, 200, { ok: true, city }); } +// ---------- NIGHTLIFEZ Admin Finance & Commission Infrastructure ---------- + +export async function adminFinanceOverview(ctx) { + await guard(ctx, R.FINANCE_VIEW); + const organiserId = ctx.query?.get?.('organiser_id') || null; + const eventId = ctx.query?.get?.('event_id') || null; + const status = ctx.query?.get?.('status') || null; + const minOutstanding = ctx.query?.get?.('min_outstanding') || null; + + const overview = await getAdminFinanceOverview({ + organiserId, + eventId, + status, + minOutstanding + }); + + const activeRule = await getActiveFeeRule(); + const rules = (await db.query( + `SELECT r.*, a.telegram_user_id AS created_by_tg + FROM infrastructure_fee_rules r + LEFT JOIN admin_users a ON a.id = r.created_by + ORDER BY r.effective_from DESC LIMIT 10` + )).rows; + + const auditLogs = (await db.query( + `SELECT * FROM finance_audit_logs ORDER BY created_at DESC LIMIT 30` + )).rows; + + sendJson(ctx.res, 200, { + ok: true, + ...overview, + activeRule, + rules, + auditLogs + }); +} + +export async function adminFinanceQueue(ctx) { + await guard(ctx, R.FINANCE_VIEW); + const status = ctx.query?.get?.('status') || 'pending'; + const organiserId = ctx.query?.get?.('organiser_id') || null; + const eventId = ctx.query?.get?.('event_id') || null; + + const queue = await getVerificationQueue({ status, organiserId, eventId }); + sendJson(ctx.res, 200, { ok: true, queue }); +} + +const ConfirmPaymentBody = z.object({ + submissionId: uuid, + bankTxId: z.string().min(4).max(80), + verifiedAmountPaise: z.coerce.number().int().positive().nullable().optional(), + notes: z.string().max(500).default(''), + allocations: z.array(z.object({ + invoiceId: uuid, + amountPaise: z.coerce.number().int().positive() + })).optional() +}).strict(); + +export async function adminConfirmPayment(ctx) { + const a = await guard(ctx, R.FINANCE_VIEW, { write: true }); + const body = parse(ConfirmPaymentBody, await readJson(ctx.req)); + const result = await confirmFeePayment({ + submissionId: body.submissionId, + bankTxId: body.bankTxId, + verifiedAmountPaise: body.verifiedAmountPaise, + notes: body.notes, + adminUser: a.admin, + allocations: body.allocations || [] + }); + sendJson(ctx.res, 200, { ok: true, ...result }); +} + +const RejectPaymentBody = z.object({ + submissionId: uuid, + reason: z.string().min(5).max(500) +}).strict(); + +export async function adminRejectPayment(ctx) { + const a = await guard(ctx, R.FINANCE_VIEW, { write: true }); + const body = parse(RejectPaymentBody, await readJson(ctx.req)); + const result = await rejectFeePayment({ + submissionId: body.submissionId, + reason: body.reason, + adminUser: a.admin + }); + sendJson(ctx.res, 200, { ok: true, ...result }); +} + +const InvestigatePaymentBody = z.object({ + submissionId: uuid, + notes: z.string().min(3).max(500) +}).strict(); + +export async function adminInvestigatePayment(ctx) { + const a = await guard(ctx, R.FINANCE_VIEW, { write: true }); + const body = parse(InvestigatePaymentBody, await readJson(ctx.req)); + const result = await investigateFeePayment({ + submissionId: body.submissionId, + notes: body.notes, + adminUser: a.admin + }); + sendJson(ctx.res, 200, { ok: true, ...result }); +} + +const SetFeeRuleBody = z.object({ + percentage: z.coerce.number().min(0).max(100), + name: z.string().max(100).default('Platform Infrastructure Fee'), + notes: z.string().max(500).default('') +}).strict(); + +export async function adminSetFeeRule(ctx) { + const a = await guard(ctx, R.FINANCE_VIEW, { write: true }); + const body = parse(SetFeeRuleBody, await readJson(ctx.req)); + const rule = await setFeeRule({ + percentage: body.percentage, + name: body.name, + notes: body.notes, + adminUser: a.admin + }); + sendJson(ctx.res, 201, { ok: true, rule }); +} + +const ExtendDeadlineBody = z.object({ + eventId: uuid, + newDeadline: z.string().min(10).max(80), + reason: z.string().min(5).max(500) +}).strict(); + +export async function adminExtendDeadline(ctx) { + const a = await guard(ctx, R.FINANCE_VIEW, { write: true }); + const body = parse(ExtendDeadlineBody, await readJson(ctx.req)); + const event = await extendPaymentDeadline({ + eventId: body.eventId, + newDeadline: body.newDeadline, + reason: body.reason, + adminUser: a.admin + }); + sendJson(ctx.res, 200, { ok: true, event }); +} + +export async function adminFinanceExport(ctx) { + await guard(ctx, R.FINANCE_VIEW); + const csv = await generateAdminFinanceCsv(); + ctx.res.setHeader('Content-Type', 'text/csv; charset=utf-8'); + ctx.res.setHeader('Content-Disposition', 'attachment; filename="nightlifez-admin-finance.csv"'); + ctx.res.end(csv); +} + diff --git a/lib/handlers/organiser.js b/lib/handlers/organiser.js index 7db1697..722645f 100644 --- a/lib/handlers/organiser.js +++ b/lib/handlers/organiser.js @@ -24,6 +24,11 @@ import { import { listEventAnnouncements, createEventAnnouncement } from '../services/event-announcements.js'; +import { + getOrganiserFinanceSummary, + submitFeePayment, + generateOrganiserStatementCsv +} from '../services/finance.js'; const id = (v) => { if (!uuid.safeParse(v).success) throw new HttpError(404, 'not_found', 'Not found'); @@ -63,6 +68,7 @@ function wizardConfig(user, draftId) { templates: Object.entries(O.TEMPLATES).map(([key, t]) => ({ key, label: t.label, hint: t.hint, defaults: O.initialDraftData(key) })), cities: CITIES.map((c) => c.name), ticketPresets: O.TICKET_PRESETS, + ticketCategories: O.TICKET_CATEGORIES, questionPresets: O.QUESTION_PRESETS, categories: Object.entries(CATEGORY_LABELS), timezones: TIMEZONES, @@ -478,3 +484,66 @@ export async function guestTicket(ctx) { const tickets = await getBookingTickets(id(ctx.params.id), user); sendJson(ctx.res, 200, { ok: true, tickets }); } + +// ---------- Organiser Finance & Infrastructure Fee ---------- + +export async function organiserFinance(ctx) { + const user = await organiser(ctx); + await rateLimit(`org:finance:${user.id}`, 60, 60); + const data = await getOrganiserFinanceSummary(user.id); + sendJson(ctx.res, 200, { ok: true, ...data }); +} + +export async function eventFinance(ctx) { + const user = await requireUser(ctx.req); + const eventId = id(ctx.params.id); + await authorize(user, 'event.manage', { eventId }); + await rateLimit(`org:evtfinance:${user.id}`, 60, 60); + const data = await getOrganiserFinanceSummary(user.id); + const eventData = data.events.find((e) => e.eventId === eventId); + if (!eventData) throw new HttpError(404, 'event_not_found', 'Event finance record not found'); + const submissions = data.submissions.filter((s) => s.payment_reference === eventData.paymentReference || s.invoice_number === eventData.invoiceNumber); + sendJson(ctx.res, 200, { + ok: true, + event: eventData, + account: data.account, + submissions, + platformUpi: data.platformUpi + }); +} + +const SubmitPaymentBody = z.object({ + invoiceId: uuid.nullable().optional(), + paymentReference: z.string().max(80).nullable().optional(), + amountPaise: z.coerce.number().int().positive(), + utrNumber: z.string().min(6).max(50), + payerUpiId: z.string().max(100).nullable().optional(), + notes: z.string().max(500).nullable().optional(), + screenshotUrl: z.string().max(2000).nullable().optional() +}).strict(); + +export async function submitOrganiserFeePayment(ctx) { + const user = await organiser(ctx, { write: true, scope: 'fee_payment' }); + await rateLimit(`org:feepay:${user.id}`, 20, 600); + const body = parse(SubmitPaymentBody, await readJson(ctx.req)); + const res = await submitFeePayment({ + organiserId: user.id, + invoiceId: body.invoiceId || null, + paymentReference: body.paymentReference || null, + amountPaise: body.amountPaise, + utrNumber: body.utrNumber, + payerUpiId: body.payerUpiId || null, + notes: body.notes || '', + screenshotUrl: body.screenshotUrl || null + }); + sendJson(ctx.res, 201, { ok: true, ...res }); +} + +export async function downloadOrganiserStatement(ctx) { + const user = await organiser(ctx); + await rateLimit(`org:statement:${user.id}`, 15, 60); + const csv = await generateOrganiserStatementCsv(user.id); + ctx.res.setHeader('Content-Type', 'text/csv; charset=utf-8'); + ctx.res.setHeader('Content-Disposition', 'attachment; filename="nightlifez-financial-statement.csv"'); + ctx.res.end(csv); +} diff --git a/lib/handlers/upi-checkout.js b/lib/handlers/upi-checkout.js index 430f9c7..c3741f2 100644 --- a/lib/handlers/upi-checkout.js +++ b/lib/handlers/upi-checkout.js @@ -49,13 +49,13 @@ export async function upiCheckoutPage({ req, res, params, query, ip }) { let tier; if (tierId) { tier = await db.one( - `SELECT id, name, kind, price_paise, max_per_booking FROM ticket_types + `SELECT id, name, kind, price_paise, max_per_booking, category, admit_count, session_id, valid_on FROM ticket_types WHERE id = $1 AND event_id = $2 AND active`, [tierId, event.id] ); } else { tier = await db.one( - `SELECT id, name, kind, price_paise, max_per_booking FROM ticket_types + `SELECT id, name, kind, price_paise, max_per_booking, category, admit_count, session_id, valid_on FROM ticket_types WHERE event_id = $1 AND active AND kind = 'paid' ORDER BY sort_order ASC, price_paise ASC LIMIT 1`, [event.id] diff --git a/lib/payments/availability.js b/lib/payments/availability.js index 840ce62..03e07d9 100644 --- a/lib/payments/availability.js +++ b/lib/payments/availability.js @@ -1,28 +1,72 @@ // lib/payments/availability.js - Can a guest buy a paid ticket for this event right now? // -// A paid ticket is bookable only when the event is linked to a SuperProfile product -// (checkout_mode = 'superprofile' and a superprofile_url). Linking is an admin action, so events -// created in the organiser wizard cannot take payments until an admin links a product. Nothing here -// can mark a payment as paid: bookings are confirmed only by a matched SuperProfile notification. +// Separates sandbox testing from production gateway checkout. +// Production paid checkout requires an independently verified live provider gateway and +// cannot be enabled through feature flags alone. Free ticket booking is unaffected. -import { livePayments, upiCheckoutEnabled } from '../config.js'; +import { livePayments, upiCheckoutEnabled, env, isProductionRuntime } from '../config.js'; // Paid checkout stays off in Preview unless an approved test mode is explicitly enabled. -const PREVIEW_BLOCKED = Object.freeze({ available: false, reason: 'preview_paid_checkout_disabled', message: 'Paid checkout is disabled in Preview deployments.' }); +const PREVIEW_BLOCKED = Object.freeze({ + available: false, + reason: 'preview_paid_checkout_disabled', + message: 'Paid checkout is disabled in Preview deployments.' +}); + function previewPaidCheckoutBlocked() { return process.env.VERCEL_ENV === 'preview' && process.env.ALLOW_PREVIEW_PAID_CHECKOUT !== 'true'; } +/** + * Checks whether an approved live payment gateway is configured with verified production credentials. + * Sandbox credentials (PGTESTPAYUAT / preprod / sandbox URLs / placeholder VPAs) are strictly NOT live gateways. + */ +export function isLiveGatewayConfigured() { + const mId = env('PHONEPE_MERCHANT_ID', ''); + const host = env('PHONEPE_HOST_URL', ''); + const salt = env('PHONEPE_SALT_KEY', ''); + + // Fail-closed against sandbox/test/mock credentials or missing configuration + if (!mId || mId === 'PGTESTPAYUAT' || mId.includes('TEST') || mId.includes('MOCK') || mId.includes('SANDBOX')) { + return false; + } + if (!host || host.includes('sandbox') || host.includes('preprod')) { + return false; + } + if (!salt || salt === '099eb0cd-0252-4e2a-8aca-eb3c6bd470f1') { + return false; + } + return true; +} + /** Per-event checkout availability. `row` is an events row (or anything with the same columns). */ export function checkoutForEvent(row) { - // UPI/PhonePe events are gated by UPI_CHECKOUT_ENABLED alone; ENABLE_LIVE_PAYMENTS never opens them. + // UPI/PhonePe events are gated by UPI_CHECKOUT_ENABLED; ENABLE_LIVE_PAYMENTS never opens them. if (row?.checkout_mode === 'upi_direct') { if (!upiCheckoutEnabled()) { return { available: false, reason: 'upi_checkout_disabled', message: 'Paid ticket checkout is currently disabled.' }; } if (previewPaidCheckoutBlocked()) return PREVIEW_BLOCKED; - return { available: true, reason: 'upi_direct', provider: 'phonepe', message: '' }; + + // In production, paid checkout CANNOT run on sandbox credentials or feature flag alone + if (isProductionRuntime() && !isLiveGatewayConfigured()) { + return { + available: false, + reason: 'gateway_pending_configuration', + message: 'Online paid checkout is pending gateway activation. Free tickets can be booked immediately.' + }; + } + + const isSandbox = !isLiveGatewayConfigured(); + return { + available: true, + reason: isSandbox ? 'upi_sandbox' : 'upi_direct', + provider: isSandbox ? 'phonepe_sandbox' : 'phonepe', + isSandbox, + message: isSandbox ? 'Sandbox test checkout active.' : '' + }; } + // ENABLE_LIVE_PAYMENTS gates only the SuperProfile hosted link-out. if (!livePayments()) { return { available: false, reason: 'live_payments_disabled', message: 'Paid ticket checkout is currently disabled.' }; @@ -34,11 +78,29 @@ export function checkoutForEvent(row) { : { available: false, reason: 'no_superprofile_product', message: 'Online booking is not available for this event yet.' }; } -/** Status used by the organiser wizard, which has no SuperProfile product to attach. */ +/** Status used by the organiser wizard to determine online checkout availability. */ export function ticketCheckoutStatus() { + // If an approved live gateway is configured and live UPI is enabled + if (isLiveGatewayConfigured() && upiCheckoutEnabled()) { + if (previewPaidCheckoutBlocked()) return PREVIEW_BLOCKED; + return { available: true, reason: 'upi_direct', provider: 'phonepe', isSandbox: false, message: '' }; + } + + // Sandbox / testing mode is strictly isolated to non-production environments with explicit testing flags + if (!isProductionRuntime() && (process.env.ALLOW_PREVIEW_PAID_CHECKOUT === 'true' || process.env.NODE_ENV === 'test') && upiCheckoutEnabled()) { + return { + available: true, + reason: 'upi_sandbox', + provider: 'phonepe_sandbox', + isSandbox: true, + message: 'Sandbox UPI testing active.' + }; + } + + // Safe fail-closed pending-configuration experience return { available: false, - reason: 'admin_link_required', - message: 'Paid tickets are bought on SuperProfile and need a product linked by the NIGHTLIFEZ team. Until then guests can only book free tickets.' + reason: 'gateway_pending_configuration', + message: 'Online paid ticket checkout is pending production gateway onboarding. Free tickets remain active and bookable.' }; } diff --git a/lib/router.js b/lib/router.js index 7ee34aa..8b6bb74 100644 --- a/lib/router.js +++ b/lib/router.js @@ -215,6 +215,10 @@ const ROUTES = [ ['POST', '/api/organiser/tickets/:id/reissue', h('organiser', 'reissueTicketHandler')], ['POST', '/api/organiser/tickets/:id/revoke', h('organiser', 'revokeTicketHandler')], ['GET', '/api/me/bookings/:id/ticket', h('organiser', 'guestTicket')], + ['GET', '/api/organiser/finance', h('organiser', 'organiserFinance')], + ['GET', '/api/organiser/events/:id/finance', h('organiser', 'eventFinance')], + ['POST', '/api/organiser/finance/submit-payment', h('organiser', 'submitOrganiserFeePayment')], + ['GET', '/api/organiser/finance/statement', h('organiser', 'downloadOrganiserStatement')], // Event Promotional Campaigns (Opt-in WhatsApp Marketing) ['POST', '/api/campaigns/preview', h('campaigns', 'previewCampaignHandler')], @@ -260,6 +264,14 @@ const ROUTES = [ ['POST', '/api/admin/events/:id/status', h('admin', 'setEventStatus')], ['GET', '/api/admin/events/:id/attendees', h('admin', 'attendees')], ['POST', '/api/admin/bookings/:id/check-in', h('admin', 'checkIn')], + ['GET', '/api/admin/finance/overview', h('admin', 'adminFinanceOverview')], + ['GET', '/api/admin/finance/queue', h('admin', 'adminFinanceQueue')], + ['POST', '/api/admin/finance/confirm-payment', h('admin', 'adminConfirmPayment')], + ['POST', '/api/admin/finance/reject-payment', h('admin', 'adminRejectPayment')], + ['POST', '/api/admin/finance/investigate-payment', h('admin', 'adminInvestigatePayment')], + ['POST', '/api/admin/finance/rules', h('admin', 'adminSetFeeRule')], + ['POST', '/api/admin/finance/extend-deadline', h('admin', 'adminExtendDeadline')], + ['GET', '/api/admin/finance/export', h('admin', 'adminFinanceExport')], ['GET', '/api/admin/bookings', h('admin', 'listBookings')], ['GET', '/api/admin/orders', h('admin', 'listOrders')], ['POST', '/api/admin/orders/:id/link', h('admin', 'linkOrder')], diff --git a/lib/services/bookings.js b/lib/services/bookings.js index 89b57f4..2d27d27 100644 --- a/lib/services/bookings.js +++ b/lib/services/bookings.js @@ -11,7 +11,10 @@ import { calculateRefundEligibility, resolveCancellationPolicy } from './cancell export async function seatsTaken(c, eventId, excludeBookingId = null) { const { rows } = await c.query( - `SELECT COALESCE(sum(b.quantity), 0)::int AS n FROM bookings b WHERE b.event_id = $1 AND ${SEAT_HOLDING_SQL} AND ($2::uuid IS NULL OR b.id <> $2)`, + `SELECT COALESCE(sum(b.quantity * COALESCE(b.admit_count, tt.admit_count, 1)), 0)::int AS n + FROM bookings b + LEFT JOIN ticket_types tt ON tt.id = b.ticket_type_id + WHERE b.event_id = $1 AND ${SEAT_HOLDING_SQL} AND ($2::uuid IS NULL OR b.id <> $2)`, [eventId, excludeBookingId]); return rows[0].n; } @@ -93,10 +96,14 @@ export async function getUserBooking(userId, bookingId) { const b = await db.one( `SELECT b.*, e.title, e.city, e.start_at, e.timezone, e.venue_private, e.venue_privacy, e.area_public, e.maps_url, e.slug, e.pickup_points, e.contact_name, e.contact_phone, e.features, e.refund_policy, t.name AS ticket_name, t.kind AS ticket_kind, - eo.status AS payment_status + eo.status AS payment_status, + es.id AS session_record_id, es.session_index, es.session_date AS session_rec_date, es.label AS session_label, + es.venue_name AS session_venue_name, es.venue_address AS session_venue_address, es.city AS session_city, + es.maps_url AS session_maps_url, es.start_at AS session_start_at FROM bookings b JOIN events e ON e.id = b.event_id LEFT JOIN ticket_types t ON t.id = b.ticket_type_id LEFT JOIN external_orders eo ON eo.matched_booking_id = b.id + LEFT JOIN event_sessions es ON es.id = b.session_id OR (es.event_id = b.event_id AND es.session_date = b.session_date) WHERE b.id = $1 AND b.user_id = $2`, [bookingId, userId]); if (!b) return null; const confirmed = ['confirmed', 'checked_in'].includes(b.status); @@ -118,13 +125,27 @@ export async function getUserBooking(userId, bookingId) { const features = (typeof b.features === 'object' && b.features !== null) ? b.features : {}; const policySnapshot = answers.policy_snapshot || features.cancellationPolicy || resolveCancellationPolicy({ refundPolicy: b.refund_policy }).snapshot; + const sessionVenue = b.session_venue_address || b.session_venue_name; + const effectiveVenue = confirmed ? (sessionVenue || b.venue_private || null) : null; + const effectiveMapsUrl = confirmed || b.venue_privacy === 'public' ? (b.session_maps_url || b.maps_url || null) : null; + const effectiveCity = b.session_city || b.city; + const effectiveStartAt = b.session_start_at || b.start_at; + return { - id: b.id, status: b.status, title: b.title, city: b.city, startAt: b.start_at, timezone: b.timezone, + id: b.id, status: b.status, title: b.title, city: effectiveCity, startAt: effectiveStartAt, timezone: b.timezone, slug: b.slug, eventId: b.event_id, - venue: confirmed ? (b.venue_private || null) : null, - mapsUrl: confirmed || b.venue_privacy === 'public' ? (b.maps_url || null) : null, - ticket: b.ticket_name ? { name: b.ticket_name, kind: b.ticket_kind, quantity: b.quantity } : null, + venue: effectiveVenue, + mapsUrl: effectiveMapsUrl, + session: b.session_record_id ? { + id: b.session_record_id, + index: b.session_index, + date: b.session_rec_date, + label: b.session_label, + venueName: b.session_venue_name, + city: b.session_city + } : null, + ticket: b.ticket_name ? { name: b.ticket_name, kind: b.ticket_kind, quantity: b.quantity, admitCount: b.admit_count || 1 } : null, tickets, isCheckedIn: b.status === 'checked_in' || Boolean(checkedInTicket), checkedInAt: checkedInTicket?.checkedInAt || (b.status === 'checked_in' ? b.updated_at : null), diff --git a/lib/services/event-schedule.js b/lib/services/event-schedule.js index 2c7606c..364b1c2 100644 --- a/lib/services/event-schedule.js +++ b/lib/services/event-schedule.js @@ -8,18 +8,28 @@ export const ScheduleDateItem = z.object({ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD'), startLocal: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/, 'Start time must be YYYY-MM-DDTHH:mm'), endLocal: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/, 'End time must be YYYY-MM-DDTHH:mm'), - label: z.string().max(80).optional().default('') + label: z.string().max(80).optional().default(''), + venueId: z.string().uuid().nullable().optional(), + venueName: z.string().max(120).optional().default(''), + venueAddress: z.string().max(255).optional().default(''), + city: z.string().max(80).optional().default(''), + mapsUrl: z.string().max(500).optional().default(''), + lat: z.number().nullable().optional(), + lng: z.number().nullable().optional(), + timezone: z.string().max(50).optional().default('Asia/Kolkata') }).strict(); export const EventScheduleDraft = z.object({ type: z.enum(SCHEDULE_TYPES).default('single'), + venueArrangement: z.enum(['same', 'different']).default('same'), dates: z.array(ScheduleDateItem).max(30).default([]), recurring: z.object({ frequency: z.enum(['weekly', 'biweekly', 'daily']).default('weekly'), daysOfWeek: z.array(z.number().int().min(0).max(6)).default([]), // 0=Sun, 1=Mon, ..., 6=Sat occurrences: z.number().int().min(1).max(20).default(4), startTime: z.string().regex(/^\d{2}:\d{2}$/).default('19:00'), - endTime: z.string().regex(/^\d{2}:\d{2}$/).default('22:00') + endTime: z.string().regex(/^\d{2}:\d{2}$/).default('22:00'), + venueArrangement: z.enum(['same', 'different']).default('same') }).optional() }).strict(); @@ -63,7 +73,15 @@ export function normalizeSchedule(inputSchedule, defaultStartLocal, defaultEndLo date: d.date, startLocal, endLocal, - label: String(d.label || '').trim().slice(0, 80) + label: String(d.label || '').trim().slice(0, 80), + venueId: d.venueId || null, + venueName: String(d.venueName || '').trim().slice(0, 120), + venueAddress: String(d.venueAddress || '').trim().slice(0, 255), + city: String(d.city || '').trim().slice(0, 80), + mapsUrl: String(d.mapsUrl || '').trim().slice(0, 500), + lat: typeof d.lat === 'number' ? d.lat : null, + lng: typeof d.lng === 'number' ? d.lng : null, + timezone: String(d.timezone || 'Asia/Kolkata').trim().slice(0, 50) }); } @@ -77,12 +95,21 @@ export function normalizeSchedule(inputSchedule, defaultStartLocal, defaultEndLo date: datePart, startLocal: defaultStartLocal, endLocal: defaultEndLocal || defaultStartLocal, - label: '' + label: '', + venueId: null, + venueName: '', + venueAddress: '', + city: '', + mapsUrl: '', + lat: null, + lng: null, + timezone: 'Asia/Kolkata' }); } return { type, + venueArrangement: inputSchedule.venueArrangement || inputSchedule.recurring?.venueArrangement || 'same', dates: dedupedDates, recurring: inputSchedule.recurring }; @@ -92,7 +119,16 @@ export function normalizeSchedule(inputSchedule, defaultStartLocal, defaultEndLo * Generates preview occurrences for a recurring schedule. * Does not mutate DB; purely deterministic generator. */ -export function generateRecurringOccurrences({ startDate, daysOfWeek = [6], occurrences = 4, startTime = '19:00', endTime = '22:00', labelPrefix = 'Session' }) { +export function generateRecurringOccurrences({ + startDate, + daysOfWeek = [6], + occurrences = 4, + startTime = '19:00', + endTime = '22:00', + labelPrefix = 'Session', + venueArrangement = 'same', + defaultVenue = null +}) { const result = []; if (!startDate) return result; @@ -107,11 +143,20 @@ export function generateRecurringOccurrences({ startDate, daysOfWeek = [6], occu if (daysOfWeek.includes(day)) { count++; const ymd = current.toISOString().slice(0, 10); + const occVenue = (venueArrangement === 'same' && defaultVenue) ? defaultVenue : {}; result.push({ date: ymd, startLocal: `${ymd}T${startTime}`, endLocal: `${ymd}T${endTime}`, - label: `${labelPrefix} ${count}` + label: `${labelPrefix} ${count}`, + venueId: occVenue.venueId || null, + venueName: occVenue.venueName || '', + venueAddress: occVenue.venueAddress || '', + city: occVenue.city || '', + mapsUrl: occVenue.mapsUrl || '', + lat: occVenue.lat || null, + lng: occVenue.lng || null, + timezone: occVenue.timezone || 'Asia/Kolkata' }); } current.setUTCDate(current.getUTCDate() + 1); diff --git a/lib/services/events.js b/lib/services/events.js index b82bb92..3bb9070 100644 --- a/lib/services/events.js +++ b/lib/services/events.js @@ -122,8 +122,8 @@ function list(v) { /** Public view of one ticket tier. `sold` = confirmed seats, `held` = live checkout holds. */ export function toPublicTier(t, { checkout, showCounts = false, requiresApproval = false } = {}) { const free = t.kind === 'free'; - // A paid ticket is sold by SuperProfile, which owns its stock; our own booking counts say nothing about it. - const sellsOnSuperprofile = !free && Boolean(checkout?.available); + // A paid ticket is sold by SuperProfile only when provider is superprofile_link; UPI PhonePe checkout uses internal stock. + const sellsOnSuperprofile = !free && Boolean(checkout?.available) && checkout?.provider === 'superprofile_link'; const used = sellsOnSuperprofile ? 0 : Number(t.sold || 0) + Number(t.held || 0); const remaining = Math.max(0, t.quantity - used); let unavailable = null; @@ -133,10 +133,15 @@ export function toPublicTier(t, { checkout, showCounts = false, requiresApproval unavailable = 'Online payment not available yet (Paid ticket — external checkout not configured)'; } else if (!free && requiresApproval) { unavailable = 'Paid tickets can’t be approval-only yet'; + } else if (t.sales_start_at && new Date(t.sales_start_at) > new Date()) { + unavailable = 'Sales have not started yet'; + } else if (t.sales_end_at && new Date(t.sales_end_at) < new Date()) { + unavailable = 'Sales have ended'; } return { id: t.id, name: t.name, + category: t.category || 'general', kind: t.kind, pricePaise: free ? 0 : t.price_paise, priceLabel: free ? 'Free' : formatPaise(t.price_paise), @@ -144,7 +149,10 @@ export function toPublicTier(t, { checkout, showCounts = false, requiresApproval remaining, remainingLabel: showCounts && !sellsOnSuperprofile ? `${remaining} of ${t.quantity} left` : null, maxPerBooking: t.max_per_booking, + minPerBooking: t.min_per_booking || 1, + admitCount: t.admit_count || (t.category === 'couple' ? 2 : t.category === 'group' ? 4 : 1), validOn: t.valid_on ? String(t.valid_on).slice(0, 10) : null, + sessionId: t.session_id || null, eligibility: t.eligibility || null, available: !unavailable, unavailable @@ -235,7 +243,7 @@ export function toPublicEvent(row, { checkout = checkoutForEvent(row) } = {}) { balance: Boolean(features.balance), organiserManaged: Boolean(row.organiser_user_id), checkoutAvailable: Boolean(checkout?.available), - checkoutMode: sp ? (checkout.provider === 'phonepe' ? 'upi_direct' : 'superprofile') : (row.checkout_mode === 'upi_direct' ? 'upi_direct' : 'none'), + 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, inclusions: arr(row.inclusions), exclusions: arr(row.exclusions), @@ -264,14 +272,17 @@ export function toPublicEvent(row, { checkout = checkoutForEvent(row) } = {}) { /** SQL expression: an event's active tiers with confirmed (`sold`) and live-hold (`held`) seats. */ export const TIERS_SQL = `(SELECT COALESCE(json_agg(json_build_object( 'id', t.id, 'name', t.name, 'kind', t.kind, 'price_paise', t.price_paise, 'quantity', t.quantity, - 'max_per_booking', t.max_per_booking, 'valid_on', t.valid_on, 'eligibility', t.eligibility, + 'max_per_booking', t.max_per_booking, 'min_per_booking', COALESCE(t.min_per_booking, 1), + 'admit_count', COALESCE(t.admit_count, 1), 'category', COALESCE(t.category, 'general'), + 'valid_on', t.valid_on, 'session_id', t.session_id, 'eligibility', t.eligibility, + 'sales_start_at', t.sales_start_at, 'sales_end_at', t.sales_end_at, 'sold', (SELECT COALESCE(sum(b.quantity), 0) FROM bookings b WHERE b.ticket_type_id = t.id AND b.status IN ('confirmed', 'checked_in')), 'held', (SELECT COALESCE(sum(b.quantity), 0) FROM bookings b WHERE b.ticket_type_id = t.id AND b.status = 'pending_payment' AND b.hold_expires_at > now()) ) ORDER BY t.sort_order), '[]'::json) FROM ticket_types t WHERE t.event_id = e.id AND t.active)`; const PUBLIC_SELECT = ` SELECT e.*, - (SELECT COALESCE(sum(b.quantity), 0)::int FROM bookings b WHERE b.event_id = e.id AND ${SEAT_HOLDING_SQL}) AS seats_taken, + (SELECT COALESCE(sum(b.quantity * COALESCE(b.admit_count, 1)), 0)::int FROM bookings b WHERE b.event_id = e.id AND ${SEAT_HOLDING_SQL}) AS seats_taken, (SELECT m.url FROM media m WHERE m.id = e.cover_media_id AND m.authorized_by_owner AND m.visible) AS cover_url, ${TIERS_SQL} AS tiers FROM events e`; diff --git a/lib/services/finance.js b/lib/services/finance.js new file mode 100644 index 0000000..24ad129 --- /dev/null +++ b/lib/services/finance.js @@ -0,0 +1,1429 @@ +// lib/services/finance.js - NIGHTLIFEZ Infrastructure Fee & Organiser Commission Accounting. +// Zero-trust financial integrity: integer paise arithmetic, database transactions, +// append-only immutable history, strict role enforcement, and duplicate protection. + +import crypto from 'node:crypto'; +import { db } from '../db.js'; +import { HttpError } from '../http.js'; +import { logger } from '../logger.js'; +import { env, isProductionRuntime } from '../config.js'; + +export const DEFAULT_FEE_PERCENTAGE = 5.00; + +export function getPlatformFinanceUpi() { + const configured = env('NIGHTLIFEZ_FINANCE_UPI_ID'); + if (isProductionRuntime()) { + // In production runtime, development fallback, placeholder, mock, or test VPAs are strictly prohibited. + if (!configured || configured === 'nightlifez.finance@icici') return null; + if (/^(test|dummy|mock|placeholder|fake|none|null)/i.test(configured)) return null; + return configured; + } + return configured || 'nightlifez.finance@icici'; +} + +export function getPlatformFinanceName() { + const configured = env('NIGHTLIFEZ_FINANCE_NAME'); + if (isProductionRuntime()) { + // In production, do not silently fabricate a legal entity name + return configured || null; + } + return configured || 'NIGHTLIFEZ Experiences Private Limited'; +} + +/** + * Validates external bank transaction or UTR reference. + * Must be 6-50 chars, alphanumeric, not placeholder or repeated characters. + */ +export function isValidUtr(ref) { + if (!ref || typeof ref !== 'string') return false; + const trimmed = ref.trim(); + if (trimmed.length < 6 || trimmed.length > 50) return false; + if (/^(manual|dummy|test|placeholder|none|null|n\/?a|fake|temp|xxx)/i.test(trimmed)) return false; + if (/^(.)\1{4,}$/.test(trimmed)) return false; + if (!/^[A-Za-z0-9][A-Za-z0-9_.\-/:]{4,48}[A-Za-z0-9]$/.test(trimmed)) return false; + return true; +} + +/** + * Validates screenshot or evidence proof URLs. + * Allows valid https:// URLs or local relative paths in /uploads/ or /media/. + * Strictly forbids javascript:, data:, file:, and control characters. + */ +export function isValidEvidenceUrl(url) { + if (!url || typeof url !== 'string') return false; + const trimmed = url.trim(); + if (trimmed.length > 2048) return false; + if (/[\r\n\t\0]/.test(trimmed)) return false; + if (/^(javascript|data|file|vbscript):/i.test(trimmed)) return false; + + // Allow relative upload paths e.g. /uploads/evidence.jpg + if (/^\/(uploads|media|assets)\/[A-Za-z0-9_\-./]+$/.test(trimmed)) { + if (trimmed.includes('..')) return false; + return true; + } + + // Allow absolute https URLs + try { + const parsed = new URL(trimmed); + return parsed.protocol === 'https:' && !parsed.username && !parsed.password; + } catch { + return false; + } +} + +/** + * Verifies finance or super_admin authorization from an active admin_users row. + */ +export async function assertFinanceAuthorization(adminUser, c = db) { + if (!adminUser) { + throw new HttpError(403, 'forbidden', 'Admin authorization required'); + } + const row = (await c.query( + `SELECT a.id, a.role, a.active + FROM admin_users a + WHERE a.active = true + AND ( + a.id = $1 + OR a.telegram_user_id = $2 + OR a.telegram_user_id = (SELECT telegram_user_id FROM users WHERE id = $1) + ) + LIMIT 1`, + [adminUser.id || null, adminUser.telegram_user_id || adminUser.tgId || null] + )).rows[0]; + if (!row || !['super_admin', 'finance'].includes(row.role)) { + throw new HttpError(403, 'forbidden_role', 'Only finance administrators or super admins can perform this action'); + } + return row; +} + +/** + * Calculates infrastructure fee using integer paise. + * Default 5% (500 bps). + */ +export function calculateInfrastructureFee(basePaise, customPercentage = null) { + const base = Math.max(0, parseInt(basePaise, 10) || 0); + const pct = customPercentage !== null && customPercentage !== undefined + ? Number(Number(customPercentage).toFixed(2)) + : DEFAULT_FEE_PERCENTAGE; + + if (base === 0 || pct === 0) { + return { + basePaise: base, + feePaise: 0, + totalPaise: base, + feePercentage: pct + }; + } + + // Calculate using integer paise rounding + const feePaise = Math.round((base * pct) / 100); + const totalPaise = base + feePaise; + + return { + basePaise: base, + feePaise, + totalPaise, + feePercentage: pct + }; +} + +/** + * Retrieves the current active infrastructure fee rule. + */ +export async function getActiveFeeRule(c = db) { + const row = (await c.query( + `SELECT * FROM infrastructure_fee_rules + WHERE is_active = true + ORDER BY effective_from DESC + LIMIT 1` + )).rows[0]; + + if (!row) { + return { + id: null, + name: 'Default 5% Rule', + fee_percentage: '5.00', + is_active: true + }; + } + + return row; +} + +/** + * Updates or sets a new infrastructure fee rule. + * Deactivates prior rules and logs the commission change in the audit trail. + */ +export async function setFeeRule({ percentage, name = 'Platform Infrastructure Fee', notes = '', adminUser }, c = db) { + const verifiedAdmin = await assertFinanceAuthorization(adminUser, c); + + const pct = Number(percentage); + if (isNaN(pct) || pct < 0 || pct > 100) { + throw new HttpError(400, 'validation', 'Fee percentage must be between 0% and 100%'); + } + + return c.tx(async (tx) => { + // 1. Get current active rule for audit diff + const prevRule = await getActiveFeeRule(tx); + + // 2. Deactivate existing active rules + await tx.query( + `UPDATE infrastructure_fee_rules + SET is_active = false, effective_until = now(), updated_at = now() + WHERE is_active = true` + ); + + // 3. Insert new rule + const newRule = (await tx.query( + `INSERT INTO infrastructure_fee_rules (name, fee_percentage, effective_from, is_active, created_by, notes) + VALUES ($1, $2, now(), true, $3, $4) + RETURNING *`, + [name, pct.toFixed(2), verifiedAdmin.id, notes] + )).rows[0]; + + // 4. Log commission rule change in audit trail + await tx.query( + `INSERT INTO finance_audit_logs (entity_type, entity_id, action, actor_type, actor_id, before_state, after_state, notes) + VALUES ('rule', $1, 'rule_updated', 'admin', $2, $3, $4, $5)`, + [ + newRule.id, + verifiedAdmin.id, + JSON.stringify(prevRule || {}), + JSON.stringify(newRule), + `Commission rule updated to ${pct.toFixed(2)}%` + ] + ); + + return newRule; + }); +} + +/** + * Helper: generates a unique invoice number. + */ +export function generateInvoiceNumber(eventSlug = '') { + const prefix = eventSlug ? eventSlug.slice(0, 4).toUpperCase().replace(/[^A-Z0-9]/g, 'X') : 'NLZ'; + const yymm = new Date().toISOString().slice(2, 7).replace('-', ''); + const rand = crypto.randomBytes(3).toString('hex').toUpperCase(); + return `INV-${yymm}-${prefix}-${rand}`; +} + +/** + * Helper: generates a unique payment reference. + */ +export function generatePaymentReference() { + const yymm = new Date().toISOString().slice(2, 7).replace('-', ''); + const rand = crypto.randomBytes(4).toString('hex').toUpperCase(); + return `PAYREF-${yymm}-${rand}`; +} + +/** + * Helper: generates a unique receipt number. + */ +export function generateReceiptNumber() { + const yymm = new Date().toISOString().slice(2, 7).replace('-', ''); + const rand = crypto.randomBytes(3).toString('hex').toUpperCase(); + return `REC-${yymm}-${rand}`; +} + +/** + * Helper: generates a unique credit note number. + */ +export function generateCreditNoteNumber() { + const yymm = new Date().toISOString().slice(2, 7).replace('-', ''); + const rand = crypto.randomBytes(3).toString('hex').toUpperCase(); + return `CN-${yymm}-${rand}`; +} + +/** + * Records an infrastructure fee entry when a paid ticket booking occurs. + * Automatically manages: + * - infrastructure_fee_entries + * - organiser_fee_accounts + * - organiser_fee_invoices + * - organiser_fee_invoice_lines + * - finance_audit_logs + */ +export async function recordBookingFeeEntry(booking, event, tier, c = db) { + if (!booking || !event || !tier || tier.kind !== 'paid') { + return null; // Free bookings do not accrue infrastructure fees + } + + const qty = booking.quantity || 1; + const basePaise = Number(tier.price_paise) * qty; + const activeRule = await getActiveFeeRule(c); + const feePct = Number(activeRule.fee_percentage || DEFAULT_FEE_PERCENTAGE); + const calc = calculateInfrastructureFee(basePaise, feePct); + + const organiserId = event.organiser_user_id; + if (!organiserId) { + // Internal/feed events without organiser profile + return null; + } + + // 0. Upfront Idempotency Check: if an entry already exists for this booking, return immediately + const existingEntry = (await c.query( + `SELECT * FROM infrastructure_fee_entries WHERE booking_id = $1`, + [booking.id] + )).rows[0]; + if (existingEntry) { + return { feeEntry: existingEntry, duplicate: true }; + } + + const snapshot = { + ruleId: activeRule.id, + feePercentage: feePct, + baseAmountPaise: calc.basePaise, + feePaise: calc.feePaise, + totalCollectedPaise: calc.totalPaise, + ticketTypeId: tier.id, + tierName: tier.name, + quantity: qty, + calculatedAt: new Date().toISOString() + }; + + // 1. Update booking with fee details + await c.query( + `UPDATE bookings SET + base_price_paise = $2, + infrastructure_fee_paise = $3, + fee_percentage = $4, + fee_rule_id = $5, + fee_calculation_snapshot = $6 + WHERE id = $1`, + [booking.id, calc.basePaise, calc.feePaise, feePct, activeRule.id, JSON.stringify(snapshot)] + ); + + // 2. Upsert Organiser Fee Account + const account = (await c.query( + `INSERT INTO organiser_fee_accounts ( + organiser_id, total_fee_payable_paise, outstanding_balance_paise + ) VALUES ($1, $2, $2) + ON CONFLICT (organiser_id) DO UPDATE SET + total_fee_payable_paise = organiser_fee_accounts.total_fee_payable_paise + EXCLUDED.total_fee_payable_paise, + outstanding_balance_paise = (organiser_fee_accounts.total_fee_payable_paise + EXCLUDED.total_fee_payable_paise) + - organiser_fee_accounts.total_fee_paid_paise + - organiser_fee_accounts.total_fee_reversal_paise, + status = CASE + WHEN (organiser_fee_accounts.total_fee_payable_paise + EXCLUDED.total_fee_payable_paise) + - organiser_fee_accounts.total_fee_paid_paise + - organiser_fee_accounts.total_fee_reversal_paise <= 0 THEN 'settled' + ELSE 'active' + END, + updated_at = now() + RETURNING *`, + [organiserId, calc.feePaise] + )).rows[0]; + + // 3. Insert Infrastructure Fee Entry (Unique on booking_id prevents duplicate entry) + const feeEntry = (await c.query( + `INSERT INTO infrastructure_fee_entries ( + account_id, organiser_id, event_id, booking_id, ticket_type_id, + base_amount_paise, fee_percentage, fee_amount_paise, total_collected_paise, + rule_id, calculation_snapshot, status + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, 'accrued') + ON CONFLICT (booking_id) DO UPDATE SET + updated_at = now() + RETURNING *`, + [ + account.id, + organiserId, + event.id, + booking.id, + tier.id, + calc.basePaise, + feePct, + calc.feePaise, + calc.totalPaise, + activeRule.id, + JSON.stringify(snapshot) + ] + )).rows[0]; + + // 4. Find or Create Organiser Fee Invoice for this event settlement + let invoice = (await c.query( + `SELECT * FROM organiser_fee_invoices + WHERE event_id = $1 AND status IN ('pending', 'payment_submitted', 'under_verification', 'partially_settled') + ORDER BY created_at DESC + LIMIT 1 + FOR UPDATE`, + [event.id] + )).rows[0]; + + const defaultDueDate = event.infrastructure_fee_deadline + ? new Date(event.infrastructure_fee_deadline) + : (event.start_at ? new Date(event.start_at) : new Date(Date.now() + 7 * 864e5)); + + if (!invoice) { + const invNumber = generateInvoiceNumber(event.slug || ''); + const payRef = generatePaymentReference(); + invoice = (await c.query( + `INSERT INTO organiser_fee_invoices ( + invoice_number, payment_reference, account_id, organiser_id, event_id, + billing_period_start, billing_period_end, due_date, + tickets_count, gross_ticket_value_paise, fee_amount_paise, + net_fee_payable_paise, outstanding_amount_paise, status + ) VALUES ($1, $2, $3, $4, $5, now(), now(), $6, $7, $8, $9, $9, $9, 'pending') + RETURNING *`, + [ + invNumber, + payRef, + account.id, + organiserId, + event.id, + defaultDueDate.toISOString(), + qty, + calc.basePaise, + calc.feePaise + ] + )).rows[0]; + } else { + invoice = (await c.query( + `UPDATE organiser_fee_invoices SET + tickets_count = tickets_count + $2, + gross_ticket_value_paise = gross_ticket_value_paise + $3, + fee_amount_paise = fee_amount_paise + $4, + net_fee_payable_paise = net_fee_payable_paise + $4, + outstanding_amount_paise = net_fee_payable_paise + $4 - amount_paid_paise - reversals_paise, + billing_period_end = now(), + updated_at = now() + WHERE id = $1 + RETURNING *`, + [invoice.id, qty, calc.basePaise, calc.feePaise] + )).rows[0]; + } + + // 5. Add invoice line + await c.query( + `INSERT INTO organiser_fee_invoice_lines ( + invoice_id, fee_entry_id, description, quantity, + base_amount_paise, rate_percent, line_total_paise + ) VALUES ($1, $2, $3, $4, $5, $6, $7)`, + [ + invoice.id, + feeEntry.id, + `${tier.name} — ${qty} ticket${qty === 1 ? '' : 's'} (5% platform fee)`, + qty, + calc.basePaise, + feePct, + calc.feePaise + ] + ); + + // 6. Record in audit logs + await c.query( + `INSERT INTO finance_audit_logs ( + entity_type, entity_id, action, actor_type, actor_id, after_state, notes + ) VALUES ('fee_entry', $1, 'entry_accrued', 'system', $2, $3, $4)`, + [ + feeEntry.id, + booking.user_id ? `user:${booking.user_id}` : 'system', + JSON.stringify(snapshot), + `Infrastructure fee of ₹${(calc.feePaise / 100).toFixed(2)} accrued for booking ${booking.id}` + ] + ); + + return { feeEntry, account, invoice, calculation: calc }; +} + +/** + * Reverses or adjusts an infrastructure fee entry upon booking cancellation or refund. + * Generates an approved credit note and updates the invoice and account balances. + */ +export async function reverseBookingFeeEntry(bookingId, { reason = 'Booking cancelled / refunded', adminUser = null, actor = 'system' } = {}, c = db) { + const feeEntry = (await c.query( + `SELECT * FROM infrastructure_fee_entries WHERE booking_id = $1 FOR UPDATE`, + [bookingId] + )).rows[0]; + + if (!feeEntry || feeEntry.status === 'reversed') { + return null; // No entry or already reversed + } + + const creditNoteNum = generateCreditNoteNumber(); + + // 1. Create Credit Note / Adjustment + const adjustment = (await c.query( + `INSERT INTO infrastructure_fee_adjustments ( + credit_note_number, account_id, organiser_id, event_id, + fee_entry_id, booking_id, amount_paise, adjustment_type, reason, + status, approved_by + ) VALUES ( + $1, $2, $3, $4, $5, $6, $7, 'refund_reversal', $8, 'approved', + COALESCE($9, (SELECT id FROM admin_users WHERE role = 'super_admin' AND active LIMIT 1)) + ) RETURNING *`, + [ + creditNoteNum, + feeEntry.account_id, + feeEntry.organiser_id, + feeEntry.event_id, + feeEntry.id, + bookingId, + feeEntry.fee_amount_paise, + reason, + adminUser?.id || null + ] + )).rows[0]; + + // 2. Mark fee entry as reversed + await c.query( + `UPDATE infrastructure_fee_entries SET status = 'reversed', updated_at = now() WHERE id = $1`, + [feeEntry.id] + ); + + // 3. Update Organiser Fee Account + if (feeEntry.account_id) { + await c.query( + `UPDATE organiser_fee_accounts SET + total_fee_reversal_paise = total_fee_reversal_paise + $2, + outstanding_balance_paise = total_fee_payable_paise - total_fee_paid_paise - (total_fee_reversal_paise + $2), + status = CASE + WHEN total_fee_payable_paise - total_fee_paid_paise - (total_fee_reversal_paise + $2) <= 0 THEN 'settled' + ELSE status + END, + updated_at = now() + WHERE id = $1`, + [feeEntry.account_id, feeEntry.fee_amount_paise] + ); + } + + // 4. Update Organiser Fee Invoice + const invoice = (await c.query( + `SELECT * FROM organiser_fee_invoices + WHERE event_id = $1 AND status NOT IN ('cancelled') + ORDER BY created_at DESC LIMIT 1 FOR UPDATE`, + [feeEntry.event_id] + )).rows[0]; + + if (invoice) { + await c.query( + `UPDATE organiser_fee_invoices SET + reversals_paise = reversals_paise + $2, + outstanding_amount_paise = GREATEST(0, net_fee_payable_paise - amount_paid_paise - (reversals_paise + $2)), + status = CASE + WHEN net_fee_payable_paise - amount_paid_paise - (reversals_paise + $2) <= 0 THEN 'fully_settled' + ELSE status + END, + updated_at = now() + WHERE id = $1`, + [invoice.id, feeEntry.fee_amount_paise] + ); + } + + // 5. Audit Log + await c.query( + `INSERT INTO finance_audit_logs ( + entity_type, entity_id, action, actor_type, actor_id, after_state, notes + ) VALUES ('credit_note', $1, 'fee_reversed', $2, $3, $4, $5)`, + [ + adjustment.id, + adminUser ? 'admin' : 'system', + adminUser?.id || actor, + JSON.stringify(adjustment), + `Infrastructure fee reversal of ₹${(feeEntry.fee_amount_paise / 100).toFixed(2)}: ${reason}` + ] + ); + + return { feeEntry, adjustment }; +} + +/** + * Organiser submits a payment claim. + * IMPORTANT: This is a submission claim only; it does NOT clear the outstanding balance. + */ +export async function submitFeePayment({ + organiserId, + invoiceId = null, + paymentReference = null, + amountPaise, + utrNumber, + payerUpiId = null, + notes = '', + screenshotUrl = null +}, c = db) { + const amt = parseInt(amountPaise, 10); + if (isNaN(amt) || amt <= 0) { + throw new HttpError(400, 'validation', 'Submitted amount must be greater than zero'); + } + + if (isProductionRuntime() && !getPlatformFinanceUpi()) { + throw new HttpError(503, 'platform_upi_not_configured', 'Official platform settlement UPI is not configured. Direct fee submission claims are disabled until the official platform account is active.'); + } + + const cleanUtr = String(utrNumber || '').trim(); + if (!isValidUtr(cleanUtr)) { + throw new HttpError(400, 'validation', 'Please enter a valid 12-character bank UTR reference number'); + } + + let cleanScreenshotUrl = null; + if (screenshotUrl) { + cleanScreenshotUrl = String(screenshotUrl).trim(); + if (!isValidEvidenceUrl(cleanScreenshotUrl)) { + throw new HttpError(400, 'validation', 'Invalid screenshot URL: only HTTPS or safe upload paths are permitted'); + } + } + + return c.tx(async (tx) => { + // 1. Prevent duplicate UTR + const dupSubmission = (await tx.query( + `SELECT id, status FROM organiser_fee_payment_submissions WHERE utr_number = $1`, + [cleanUtr] + )).rows[0]; + if (dupSubmission) { + throw new HttpError(409, 'duplicate_utr', `A payment claim with UTR "${cleanUtr}" has already been submitted.`); + } + + const dupBank = (await tx.query( + `SELECT id FROM nightlifez_bank_transactions WHERE utr_number = $1`, + [cleanUtr] + )).rows[0]; + if (dupBank) { + throw new HttpError(409, 'duplicate_utr', `A bank credit with UTR "${cleanUtr}" is already recorded in the system.`); + } + + // 2. Fetch invoice if given or resolve by paymentReference + let inv = null; + if (invoiceId) { + inv = (await tx.query( + `SELECT * FROM organiser_fee_invoices WHERE id = $1 AND organiser_id = $2`, + [invoiceId, organiserId] + )).rows[0]; + if (!inv) { + throw new HttpError(404, 'invoice_not_found', 'Invoice not found or does not belong to this organiser'); + } + } else if (paymentReference) { + inv = (await tx.query( + `SELECT * FROM organiser_fee_invoices WHERE payment_reference = $1 AND organiser_id = $2`, + [paymentReference, organiserId] + )).rows[0]; + if (!inv) { + throw new HttpError(404, 'invoice_not_found', 'Payment reference not found or does not belong to this organiser'); + } + } + + const ref = inv?.payment_reference || paymentReference || generatePaymentReference(); + + // 3. Fetch account + const account = (await tx.query( + `SELECT * FROM organiser_fee_accounts WHERE organiser_id = $1`, + [organiserId] + )).rows[0]; + + // 4. Insert submission + const submission = (await tx.query( + `INSERT INTO organiser_fee_payment_submissions ( + account_id, organiser_id, invoice_id, payment_reference, + amount_paise, utr_number, payer_upi_id, submission_notes, + screenshot_url, status + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'submitted') + RETURNING *`, + [ + account?.id || null, + organiserId, + inv?.id || null, + ref, + amt, + cleanUtr, + payerUpiId ? String(payerUpiId).trim() : null, + notes ? String(notes).trim() : null, + cleanScreenshotUrl + ] + )).rows[0]; + + // 5. Update invoice status to 'under_verification' (Outstanding balance is UNCHANGED) + if (inv) { + await tx.query( + `UPDATE organiser_fee_invoices SET + status = CASE WHEN status = 'pending' THEN 'under_verification' ELSE status END, + updated_at = now() + WHERE id = $1`, + [inv.id] + ); + } + + // 6. Record audit log + await tx.query( + `INSERT INTO finance_audit_logs ( + entity_type, entity_id, action, actor_type, actor_id, after_state, notes + ) VALUES ('payment_submission', $1, 'payment_submitted', 'organiser', $2, $3, $4)`, + [ + submission.id, + `user:${organiserId}`, + JSON.stringify({ id: submission.id, utrNumber: cleanUtr, amountPaise: amt, paymentReference: ref }), + `Payment claim of ₹${(amt / 100).toFixed(2)} submitted with UTR ${cleanUtr}. Pending bank verification.` + ] + ); + + return { + submission, + message: 'Payment claim submitted. Our finance team will verify the bank transaction before clearing the balance.' + }; + }); +} + +/** + * Admin confirms receipt of organiser fee payment after verifying the incoming bank credit. + * ONLY finance or super_admin roles can confirm payments. + * Clears the outstanding balance ONLY for the verified amount. + */ +export async function confirmFeePayment({ + submissionId, + bankTxId, + verifiedAmountPaise = null, + notes = '', + adminUser, + allocations = [] +}, c = db) { + const verifiedAdmin = await assertFinanceAuthorization(adminUser, c); + + const cleanBankTxId = String(bankTxId || '').trim(); + if (!cleanBankTxId || cleanBankTxId.length < 4) { + throw new HttpError(400, 'validation', 'A valid bank transaction ID is required for verification'); + } + + return c.tx(async (tx) => { + // 1. Fetch submission and lock row + const submission = (await tx.query( + `SELECT s.*, i.outstanding_amount_paise, i.net_fee_payable_paise, i.event_id + FROM organiser_fee_payment_submissions s + LEFT JOIN organiser_fee_invoices i ON i.id = s.invoice_id + WHERE s.id = $1 + FOR UPDATE OF s`, + [submissionId] + )).rows[0]; + + if (!submission) { + throw new HttpError(404, 'not_found', 'Payment submission not found'); + } + + if (submission.status === 'verified') { + throw new HttpError(409, 'already_verified', 'This payment submission has already been verified and confirmed'); + } + + if (submission.status === 'rejected') { + throw new HttpError(409, 'already_rejected', 'Cannot confirm a rejected payment submission'); + } + + const verifiedPaise = verifiedAmountPaise !== null && verifiedAmountPaise !== undefined + ? parseInt(verifiedAmountPaise, 10) + : submission.amount_paise; + + if (isNaN(verifiedPaise) || verifiedPaise <= 0) { + throw new HttpError(400, 'validation', 'Verified amount must be greater than zero'); + } + + // 2. Fetch or create Bank Transaction + let bankTx = (await tx.query( + `SELECT * FROM nightlifez_bank_transactions WHERE bank_tx_id = $1 FOR UPDATE`, + [cleanBankTxId] + )).rows[0]; + + if (!bankTx) { + // Check duplicate UTR on bank transactions + const dupBankUtr = (await tx.query( + `SELECT id FROM nightlifez_bank_transactions WHERE utr_number = $1`, + [submission.utr_number] + )).rows[0]; + + if (dupBankUtr) { + throw new HttpError(409, 'duplicate_bank_transaction', `Bank transaction with UTR "${submission.utr_number}" already exists.`); + } + + bankTx = (await tx.query( + `INSERT INTO nightlifez_bank_transactions ( + bank_tx_id, utr_number, amount_paise, allocated_amount_paise, + unallocated_amount_paise, payer_vpa, verification_notes, verified_by, status + ) VALUES ($1, $2, $3, 0, $3, $4, $5, $6, 'unallocated') + RETURNING *`, + [ + cleanBankTxId, + submission.utr_number, + verifiedPaise, + submission.payer_upi_id, + notes, + verifiedAdmin.id + ] + )).rows[0]; + } + + // 3. Invariant: One bank credit must never be allocated to multiple invoices beyond its actual amount + if (bankTx.unallocated_amount_paise < verifiedPaise) { + throw new HttpError(409, 'insufficient_bank_credit', + `Bank transaction ${cleanBankTxId} only has ₹${(bankTx.unallocated_amount_paise / 100).toFixed(2)} unallocated, but ₹${(verifiedPaise / 100).toFixed(2)} was requested.` + ); + } + + // 4. Resolve Invoices for Allocation + const allocationPlan = []; + if (Array.isArray(allocations) && allocations.length > 0) { + let sum = 0; + for (const a of allocations) { + const amt = parseInt(a.amountPaise, 10); + if (isNaN(amt) || amt <= 0) throw new HttpError(400, 'validation', 'Allocation amounts must be positive'); + sum += amt; + allocationPlan.push({ invoiceId: a.invoiceId, amountPaise: amt }); + } + if (sum !== verifiedPaise) { + throw new HttpError(400, 'validation', `Allocation breakdown (₹${(sum / 100).toFixed(2)}) must match verified total (₹${(verifiedPaise / 100).toFixed(2)})`); + } + } else if (submission.invoice_id) { + allocationPlan.push({ invoiceId: submission.invoice_id, amountPaise: verifiedPaise }); + } else { + // Allocate to oldest pending invoice of this organiser + const openInvoices = (await tx.query( + `SELECT id, outstanding_amount_paise FROM organiser_fee_invoices + WHERE organiser_id = $1 AND outstanding_amount_paise > 0 + ORDER BY due_date ASC + FOR UPDATE`, + [submission.organiser_id] + )).rows; + + let remaining = verifiedPaise; + for (const inv of openInvoices) { + if (remaining <= 0) break; + const alloc = Math.min(remaining, inv.outstanding_amount_paise); + allocationPlan.push({ invoiceId: inv.id, amountPaise: alloc }); + remaining -= alloc; + } + + if (remaining > 0) { + throw new HttpError(400, 'excess_allocation', `Verified amount exceeds total outstanding balance across invoices by ₹${(remaining / 100).toFixed(2)}`); + } + } + + // 5. Execute Invoice Allocations + const receiptNumbers = []; + for (const alloc of allocationPlan) { + const inv = (await tx.query( + `SELECT * FROM organiser_fee_invoices WHERE id = $1 FOR UPDATE`, + [alloc.invoiceId] + )).rows[0]; + + if (!inv) throw new HttpError(404, 'invoice_not_found', `Invoice ${alloc.invoiceId} not found`); + + if (inv.organiser_id !== submission.organiser_id) { + throw new HttpError(400, 'cross_organiser_allocation', `Invoice ${inv.invoice_number} does not belong to the payment organiser`); + } + + if (inv.status === 'cancelled') { + throw new HttpError(400, 'invalid_invoice_status', `Cannot allocate payment to cancelled invoice ${inv.invoice_number}`); + } + + if (alloc.amountPaise > inv.outstanding_amount_paise) { + throw new HttpError(400, 'excess_allocation', `Allocation of ₹${(alloc.amountPaise / 100).toFixed(2)} exceeds invoice ${inv.invoice_number} outstanding amount of ₹${(inv.outstanding_amount_paise / 100).toFixed(2)}`); + } + + const receiptNum = generateReceiptNumber(); + receiptNumbers.push(receiptNum); + + // Insert Allocation + await tx.query( + `INSERT INTO organiser_fee_payment_allocations ( + bank_transaction_id, submission_id, invoice_id, + allocated_amount_paise, receipt_number, allocated_by, allocation_notes + ) VALUES ($1, $2, $3, $4, $5, $6, $7)`, + [ + bankTx.id, + submission.id, + inv.id, + alloc.amountPaise, + receiptNum, + verifiedAdmin.id, + notes + ] + ); + + // Update Invoice + const newPaid = inv.amount_paid_paise + alloc.amountPaise; + const newOutstanding = Math.max(0, inv.net_fee_payable_paise - newPaid - inv.reversals_paise); + const newStatus = newOutstanding === 0 ? 'fully_settled' : 'partially_settled'; + + await tx.query( + `UPDATE organiser_fee_invoices SET + amount_paid_paise = $2, + outstanding_amount_paise = $3, + status = $4, + updated_at = now() + WHERE id = $1`, + [inv.id, newPaid, newOutstanding, newStatus] + ); + } + + // 6. Update Bank Transaction + const newAllocated = bankTx.allocated_amount_paise + verifiedPaise; + const newUnallocated = bankTx.amount_paise - newAllocated; + const newBankStatus = newUnallocated === 0 ? 'fully_allocated' : 'partially_allocated'; + + await tx.query( + `UPDATE nightlifez_bank_transactions SET + allocated_amount_paise = $2, + unallocated_amount_paise = $3, + status = $4, + updated_at = now() + WHERE id = $1`, + [bankTx.id, newAllocated, newUnallocated, newBankStatus] + ); + + // 7. Update Organiser Fee Account + const acc = (await tx.query( + `UPDATE organiser_fee_accounts SET + total_fee_paid_paise = total_fee_paid_paise + $2, + outstanding_balance_paise = total_fee_payable_paise - (total_fee_paid_paise + $2) - total_fee_reversal_paise, + status = CASE + WHEN total_fee_payable_paise - (total_fee_paid_paise + $2) - total_fee_reversal_paise <= 0 THEN 'settled' + ELSE 'active' + END, + last_settled_at = now(), + updated_at = now() + WHERE organiser_id = $1 + RETURNING *`, + [submission.organiser_id, verifiedPaise] + )).rows[0]; + + // 8. Update Payment Submission status + const verifiedSub = (await tx.query( + `UPDATE organiser_fee_payment_submissions SET + status = 'verified', + verified_by = $2, + verified_at = now(), + bank_transaction_id = $3, + updated_at = now() + WHERE id = $1 + RETURNING *`, + [submission.id, verifiedAdmin.id, bankTx.id] + )).rows[0]; + + // 9. Immutable Audit Log + await tx.query( + `INSERT INTO finance_audit_logs ( + entity_type, entity_id, action, actor_type, actor_id, before_state, after_state, notes + ) VALUES ('payment_submission', $1, 'payment_confirmed', 'admin', $2, $3, $4, $5)`, + [ + submission.id, + verifiedAdmin.id, + JSON.stringify(submission), + JSON.stringify({ verifiedSub, receiptNumbers, verifiedPaise, bankTxId: cleanBankTxId }), + `Payment of ₹${(verifiedPaise / 100).toFixed(2)} verified against bank credit ${cleanBankTxId}. Receipts: ${receiptNumbers.join(', ')}` + ] + ); + + return { + submission: verifiedSub, + receiptNumbers, + verifiedAmountPaise: verifiedPaise, + outstandingBalancePaise: acc ? acc.outstanding_balance_paise : 0 + }; + }); +} + +/** + * Admin rejects a payment claim with a mandatory reason. + * The outstanding balance remains unchanged. + */ +export async function rejectFeePayment({ submissionId, reason, adminUser }, c = db) { + const verifiedAdmin = await assertFinanceAuthorization(adminUser, c); + + const cleanReason = String(reason || '').trim(); + if (!cleanReason || cleanReason.length < 5) { + throw new HttpError(400, 'validation', 'A mandatory rejection reason (at least 5 characters) is required'); + } + + return c.tx(async (tx) => { + const sub = (await tx.query( + `SELECT * FROM organiser_fee_payment_submissions WHERE id = $1 FOR UPDATE`, + [submissionId] + )).rows[0]; + + if (!sub) { + throw new HttpError(404, 'not_found', 'Payment submission not found'); + } + + if (sub.status === 'verified') { + throw new HttpError(409, 'already_verified', 'Cannot reject an already confirmed and verified payment'); + } + + if (sub.status === 'rejected') { + throw new HttpError(409, 'already_rejected', 'This payment submission has already been rejected'); + } + + const updated = (await tx.query( + `UPDATE organiser_fee_payment_submissions SET + status = 'rejected', + rejection_reason = $2, + rejected_by = $3, + rejected_at = now(), + updated_at = now() + WHERE id = $1 + RETURNING *`, + [submissionId, cleanReason, verifiedAdmin.id] + )).rows[0]; + + // Update invoice status if under verification + if (sub.invoice_id) { + await tx.query( + `UPDATE organiser_fee_invoices SET + status = CASE WHEN status = 'under_verification' THEN 'rejected' ELSE status END, + updated_at = now() + WHERE id = $1`, + [sub.invoice_id] + ); + } + + // Audit log + await tx.query( + `INSERT INTO finance_audit_logs ( + entity_type, entity_id, action, actor_type, actor_id, before_state, after_state, notes + ) VALUES ('payment_submission', $1, 'payment_rejected', 'admin', $2, $3, $4, $5)`, + [ + sub.id, + verifiedAdmin.id, + JSON.stringify(sub), + JSON.stringify(updated), + `Payment claim rejected: ${cleanReason}` + ] + ); + + return { submission: updated }; + }); +} + +/** + * Admin marks a payment submission for further investigation. + */ +export async function investigateFeePayment({ submissionId, notes, adminUser }, c = db) { + const verifiedAdmin = await assertFinanceAuthorization(adminUser, c); + + const cleanNotes = String(notes || '').trim(); + if (!cleanNotes) { + throw new HttpError(400, 'validation', 'Investigation notes are required'); + } + + return c.tx(async (tx) => { + const sub = (await tx.query( + `SELECT * FROM organiser_fee_payment_submissions WHERE id = $1 FOR UPDATE`, + [submissionId] + )).rows[0]; + + if (!sub) { + throw new HttpError(404, 'not_found', 'Payment submission not found'); + } + + if (sub.status === 'verified') { + throw new HttpError(409, 'already_verified', 'Cannot investigate an already verified and settled payment'); + } + + if (sub.status === 'rejected') { + throw new HttpError(409, 'already_rejected', 'Cannot investigate an already rejected payment'); + } + + const updated = (await tx.query( + `UPDATE organiser_fee_payment_submissions SET + status = 'under_investigation', + investigation_notes = $2, + updated_at = now() + WHERE id = $1 + RETURNING *`, + [submissionId, cleanNotes] + )).rows[0]; + + await tx.query( + `INSERT INTO finance_audit_logs ( + entity_type, entity_id, action, actor_type, actor_id, after_state, notes + ) VALUES ('payment_submission', $1, 'marked_for_investigation', 'admin', $2, $3, $4)`, + [ + sub.id, + verifiedAdmin.id, + JSON.stringify(updated), + `Payment marked for investigation: ${cleanNotes}` + ] + ); + + return { submission: updated }; + }); +} + +/** + * Extends the infrastructure fee payment deadline for an event. + */ +export async function extendPaymentDeadline({ eventId, newDeadline, reason, adminUser }, c = db) { + const verifiedAdmin = await assertFinanceAuthorization(adminUser, c); + + const parsedDeadline = new Date(newDeadline); + if (isNaN(parsedDeadline.getTime())) { + throw new HttpError(400, 'validation', 'Invalid deadline timestamp'); + } + + const cleanReason = String(reason || '').trim(); + if (!cleanReason || cleanReason.length < 5) { + throw new HttpError(400, 'validation', 'A reason of at least 5 characters is required for deadline extension'); + } + + return c.tx(async (tx) => { + const event = (await tx.query( + `SELECT id, title, infrastructure_fee_deadline FROM events WHERE id = $1 FOR UPDATE`, + [eventId] + )).rows[0]; + + if (!event) throw new HttpError(404, 'not_found', 'Event not found'); + + const updated = (await tx.query( + `UPDATE events SET + infrastructure_fee_deadline = $2, + infrastructure_fee_extension_granted_by = $3, + infrastructure_fee_extension_reason = $4, + updated_at = now() + WHERE id = $1 + RETURNING id, title, infrastructure_fee_deadline`, + [eventId, parsedDeadline.toISOString(), verifiedAdmin.id, cleanReason] + )).rows[0]; + + // Update invoice due dates + await tx.query( + `UPDATE organiser_fee_invoices SET + due_date = $2, + status = CASE WHEN status = 'overdue' THEN 'pending' ELSE status END, + updated_at = now() + WHERE event_id = $1 AND status != 'cancelled'`, + [eventId, parsedDeadline.toISOString()] + ); + + await tx.query( + `INSERT INTO finance_audit_logs ( + entity_type, entity_id, action, actor_type, actor_id, before_state, after_state, notes + ) VALUES ('event', $1, 'fee_deadline_extended', 'admin', $2, $3, $4, $5)`, + [ + eventId, + verifiedAdmin.id, + JSON.stringify({ deadline: event.infrastructure_fee_deadline }), + JSON.stringify(updated), + `Fee deadline extended to ${parsedDeadline.toISOString()}: ${cleanReason}` + ] + ); + + return updated; + }); +} + +/** + * Computes event-wise accounting and summary for an organiser. + */ +export async function getOrganiserFinanceSummary(organiserId, c = db) { + // 1. Account details + let account = (await c.query( + `SELECT * FROM organiser_fee_accounts WHERE organiser_id = $1`, + [organiserId] + )).rows[0]; + + if (!account) { + account = { + total_fee_payable_paise: 0, + total_fee_paid_paise: 0, + total_fee_reversal_paise: 0, + outstanding_balance_paise: 0, + status: 'active' + }; + } + + // 2. Event-wise breakdown + const events = (await c.query( + `SELECT + e.id AS event_id, + e.title AS event_title, + e.slug AS event_slug, + e.start_at, + e.infrastructure_fee_deadline, + COALESCE(SUM(b.quantity), 0)::int AS tickets_sold, + COALESCE(SUM(b.base_price_paise), 0)::bigint AS organiser_base_revenue_paise, + COALESCE(SUM(fe.fee_amount_paise), 0)::bigint AS total_fee_payable_paise, + COALESCE(SUM(CASE WHEN fe.status = 'reversed' THEN fe.fee_amount_paise ELSE 0 END), 0)::bigint AS refunds_adjustments_paise, + COALESCE(inv.amount_paid_paise, 0)::bigint AS fee_payment_confirmed_paise, + GREATEST(0, COALESCE(SUM(fe.fee_amount_paise), 0)::bigint + - COALESCE(inv.amount_paid_paise, 0)::bigint + - COALESCE(SUM(CASE WHEN fe.status = 'reversed' THEN fe.fee_amount_paise ELSE 0 END), 0)::bigint + )::bigint AS outstanding_paise, + COALESCE(inv.status, 'pending') AS settlement_status, + inv.id AS invoice_id, + inv.invoice_number, + inv.payment_reference, + inv.due_date + FROM events e + LEFT JOIN bookings b ON b.event_id = e.id AND b.status IN ('confirmed', 'checked_in') + LEFT JOIN infrastructure_fee_entries fe ON fe.booking_id = b.id + LEFT JOIN organiser_fee_invoices inv ON inv.event_id = e.id + WHERE e.organiser_user_id = $1 + GROUP BY e.id, e.title, e.slug, e.start_at, e.infrastructure_fee_deadline, inv.id, inv.amount_paid_paise, inv.status, inv.invoice_number, inv.payment_reference, inv.due_date + ORDER BY e.start_at DESC`, + [organiserId] + )).rows; + + const now = new Date(); + const eventSummaries = events.map((ev) => { + const isOverdue = ev.outstanding_paise > 0 && ev.due_date && new Date(ev.due_date) < now; + let labelStatus = ev.settlement_status; + if (isOverdue) labelStatus = 'overdue'; + else if (ev.settlement_status === 'under_verification') labelStatus = 'under_admin_verification'; + + return { + eventId: ev.event_id, + eventTitle: ev.event_title, + eventSlug: ev.event_slug, + ticketsSold: ev.tickets_sold, + organiserRevenuePaise: ev.organiser_base_revenue_paise, + infrastructureFeePaise: ev.total_fee_payable_paise, + refundsAdjustmentsPaise: ev.refunds_adjustments_paise, + totalFeePayablePaise: ev.total_fee_payable_paise, + amountAlreadyPaidPaise: ev.fee_payment_confirmed_paise, + outstandingPaise: ev.outstanding_paise, + settlementStatus: labelStatus, + invoiceId: ev.invoice_id, + invoiceNumber: ev.invoice_number, + paymentReference: ev.payment_reference, + dueDate: ev.due_date, + isOverdue + }; + }); + + // 3. Submissions History + const submissions = (await c.query( + `SELECT + s.id, + s.payment_reference, + s.amount_paise, + s.utr_number, + s.payer_upi_id, + s.status, + s.submission_notes, + s.screenshot_url, + s.rejection_reason, + s.created_at, + s.verified_at, + i.invoice_number, + e.title AS event_title + FROM organiser_fee_payment_submissions s + LEFT JOIN organiser_fee_invoices i ON i.id = s.invoice_id + LEFT JOIN events e ON e.id = i.event_id + WHERE s.organiser_id = $1 + ORDER BY s.created_at DESC`, + [organiserId] + )).rows; + + return { + account: { + totalFeePayablePaise: Number(account.total_fee_payable_paise), + totalFeePaidPaise: Number(account.total_fee_paid_paise), + totalFeeReversalPaise: Number(account.total_fee_reversal_paise), + outstandingBalancePaise: Number(account.outstanding_balance_paise), + status: account.status + }, + events: eventSummaries, + submissions, + platformUpi: { + vpa: getPlatformFinanceUpi(), + name: getPlatformFinanceName(), + instructions: getPlatformFinanceUpi() ? [ + '1. Transfer the exact fee amount via UPI or Net Banking to our official NIGHTLIFEZ UPI ID.', + '2. Add your unique Payment Reference in the transaction remarks/notes.', + '3. Enter the 12-digit bank UTR reference number below and submit your claim.', + '4. Our finance team verifies the incoming credit with our bank before marking the invoice settled.' + ] : [] + } + }; +} + +/** + * Central Finance Management Overview for NIGHTLIFEZ Finance Administrators. + */ +export async function getAdminFinanceOverview(filters = {}, c = db) { + const { organiserId, eventId, status, minOutstanding } = filters; + + // 1. Aggregated Platform Metrics + const metrics = (await c.query( + `SELECT + COALESCE(SUM(gross_ticket_value_paise), 0)::bigint AS gross_ticket_value_paise, + COALESCE(SUM(fee_amount_paise), 0)::bigint AS total_fees_earned_paise, + COALESCE(SUM(amount_paid_paise), 0)::bigint AS confirmed_payments_paise, + COALESCE(SUM(outstanding_amount_paise), 0)::bigint AS outstanding_balances_paise, + COALESCE(SUM(reversals_paise), 0)::bigint AS refund_adjustment_totals_paise, + COALESCE(SUM(CASE WHEN due_date < now() AND outstanding_amount_paise > 0 THEN outstanding_amount_paise ELSE 0 END), 0)::bigint AS overdue_balances_paise + FROM organiser_fee_invoices` + )).rows[0]; + + const pendingSubmissionsCount = (await c.query( + `SELECT + COUNT(*)::int AS count, + COALESCE(SUM(amount_paise), 0)::bigint AS total_paise + FROM organiser_fee_payment_submissions + WHERE status IN ('submitted', 'under_investigation')` + )).rows[0]; + + // 2. Filtered Invoices and Organisers + const whereClauses = []; + const params = []; + + if (organiserId) { + params.push(organiserId); + whereClauses.push(`i.organiser_id = $${params.length}`); + } + if (eventId) { + params.push(eventId); + whereClauses.push(`i.event_id = $${params.length}`); + } + if (status && status !== 'all') { + params.push(status); + whereClauses.push(`i.status = $${params.length}`); + } + if (minOutstanding) { + params.push(parseInt(minOutstanding, 10)); + whereClauses.push(`i.outstanding_amount_paise >= $${params.length}`); + } + + const whereSql = whereClauses.length ? `WHERE ${whereClauses.join(' AND ')}` : ''; + + const invoices = (await c.query( + `SELECT + i.*, + u.alias AS organiser_alias, + u.telegram_user_id AS organiser_tg_id, + e.title AS event_title, + e.slug AS event_slug, + e.start_at AS event_start_at + FROM organiser_fee_invoices i + JOIN users u ON u.id = i.organiser_id + JOIN events e ON e.id = i.event_id + ${whereSql} + ORDER BY i.created_at DESC + LIMIT 200`, + params + )).rows; + + return { + kpis: { + grossTicketValuePaise: Number(metrics.gross_ticket_value_paise), + totalFeesEarnedPaise: Number(metrics.total_fees_earned_paise), + confirmedPaymentsPaise: Number(metrics.confirmed_payments_paise), + outstandingBalancesPaise: Number(metrics.outstanding_balances_paise), + overdueBalancesPaise: Number(metrics.overdue_balances_paise), + refundAdjustmentTotalsPaise: Number(metrics.refund_adjustment_totals_paise), + paymentsAwaitingVerificationPaise: Number(pendingSubmissionsCount.total_paise), + pendingVerificationCount: pendingSubmissionsCount.count + }, + invoices + }; +} + +/** + * Verification queue for admin review of organiser payment claims. + */ +export async function getVerificationQueue(filters = {}, c = db) { + const { status = 'pending', organiserId, eventId } = filters; + + const whereClauses = []; + const params = []; + + if (status === 'pending') { + whereClauses.push(`s.status IN ('submitted', 'under_investigation')`); + } else if (status && status !== 'all') { + params.push(status); + whereClauses.push(`s.status = $${params.length}`); + } + + if (organiserId) { + params.push(organiserId); + whereClauses.push(`s.organiser_id = $${params.length}`); + } + if (eventId) { + params.push(eventId); + whereClauses.push(`i.event_id = $${params.length}`); + } + + const whereSql = whereClauses.length ? `WHERE ${whereClauses.join(' AND ')}` : ''; + + const queue = (await c.query( + `SELECT + s.*, + u.alias AS organiser_alias, + u.telegram_user_id AS organiser_tg_id, + i.invoice_number, + i.outstanding_amount_paise AS outstanding_before_confirmation_paise, + e.title AS event_title, + e.id AS event_id, + bt.bank_tx_id, + admin.telegram_user_id AS verified_by_tg_id + FROM organiser_fee_payment_submissions s + JOIN users u ON u.id = s.organiser_id + LEFT JOIN organiser_fee_invoices i ON i.id = s.invoice_id + LEFT JOIN events e ON e.id = i.event_id + LEFT JOIN nightlifez_bank_transactions bt ON bt.id = s.bank_transaction_id + LEFT JOIN admin_users admin ON admin.id = s.verified_by + ${whereSql} + ORDER BY s.created_at ASC + LIMIT 100`, + params + )).rows; + + return queue; +} + +/** + * Generates an event-wise financial statement CSV for an organiser. + */ +export async function generateOrganiserStatementCsv(organiserId, c = db) { + const data = await getOrganiserFinanceSummary(organiserId, c); + + const lines = [ + 'Event ID,Event Title,Status,Tickets Sold,Gross Ticket Value (INR),Infrastructure Fee (5%) (INR),Refunds & Adjustments (INR),Fee Payment Confirmed (INR),Outstanding to NIGHTLIFEZ (INR),Payment Reference,Due Date' + ]; + + for (const e of data.events) { + const row = [ + `"${e.eventId}"`, + `"${(e.eventTitle || '').replace(/"/g, '""')}"`, + `"${e.settlementStatus}"`, + e.ticketsSold, + (e.organiserRevenuePaise / 100).toFixed(2), + (e.infrastructureFeePaise / 100).toFixed(2), + (e.refundsAdjustmentsPaise / 100).toFixed(2), + (e.amountAlreadyPaidPaise / 100).toFixed(2), + (e.outstandingPaise / 100).toFixed(2), + `"${e.paymentReference || ''}"`, + `"${e.dueDate ? new Date(e.dueDate).toISOString() : ''}"` + ]; + lines.push(row.join(',')); + } + + return lines.join('\n'); +} + +/** + * Generates central admin financial accounting CSV. + */ +export async function generateAdminFinanceCsv(c = db) { + const { invoices } = await getAdminFinanceOverview({}, c); + + const lines = [ + 'Invoice Number,Payment Reference,Organiser ID,Organiser Alias,Event ID,Event Title,Tickets Count,Gross Value (INR),Fee Amount (INR),Reversals (INR),Net Payable (INR),Paid (INR),Outstanding (INR),Status,Due Date' + ]; + + for (const inv of invoices) { + const row = [ + `"${inv.invoice_number}"`, + `"${inv.payment_reference}"`, + `"${inv.organiser_id}"`, + `"${(inv.organiser_alias || '').replace(/"/g, '""')}"`, + `"${inv.event_id}"`, + `"${(inv.event_title || '').replace(/"/g, '""')}"`, + inv.tickets_count, + (inv.gross_ticket_value_paise / 100).toFixed(2), + (inv.fee_amount_paise / 100).toFixed(2), + (inv.reversals_paise / 100).toFixed(2), + (inv.net_fee_payable_paise / 100).toFixed(2), + (inv.amount_paid_paise / 100).toFixed(2), + (inv.outstanding_amount_paise / 100).toFixed(2), + `"${inv.status}"`, + `"${inv.due_date ? new Date(inv.due_date).toISOString() : ''}"` + ]; + lines.push(row.join(',')); + } + + return lines.join('\n'); +} diff --git a/lib/services/notification-dispatcher.js b/lib/services/notification-dispatcher.js index de071b6..39e0edc 100644 --- a/lib/services/notification-dispatcher.js +++ b/lib/services/notification-dispatcher.js @@ -110,6 +110,28 @@ export async function dispatchNotification({ // 5. Channel dispatch try { if (channel === 'whatsapp') { + const waConfig = getWhatsAppConfig(); + const isOtp = templateName === waConfig.otpTemplateName; + const isBookingApproved = process.env.WHATSAPP_BOOKING_TEMPLATE_APPROVED === 'true'; + + if (waConfig.isLive && process.env.NODE_ENV !== 'test' && !isOtp && !isBookingApproved) { + const errorMsg = `Template '${templateName}' is pending Meta WABA approval in WABA ${waConfig.businessAccountId || '1155371310259355'}. Outbox message held safely.`; + logger.warn('whatsapp dispatch held pending waba template approval', { + templateName, + recipient: maskPhone(recipient) + }); + const { rows: updated } = await db.query( + `UPDATE notification_messages + SET status = 'pending_template_approval', + last_error = $2, + updated_at = now() + WHERE id = $1 + RETURNING *`, + [messageRow.id, errorMsg] + ); + return updated[0]; + } + const provider = getWhatsAppProvider(); const sendResult = await provider.sendTemplate({ to: recipient, @@ -361,3 +383,67 @@ export async function getSuppressionsList({ limit = 50, offset = 0 } = {}) { : (r.destination.length > 6 ? `${r.destination.slice(0, 3)}****` : r.destination) })); } + +/** + * Retries failed or pending_template_approval notification messages idempotently. + */ +export async function retryFailedNotificationMessages({ limit = 20, maxAttempts = 5 } = {}) { + const { rows } = await db.query( + `SELECT * FROM notification_messages + WHERE status IN ('failed', 'pending_template_approval') + AND attempts < $1 + ORDER BY created_at ASC + LIMIT $2`, + [maxAttempts, limit] + ); + + const results = []; + for (const msg of rows) { + try { + if (msg.channel === 'whatsapp') { + const waConfig = getWhatsAppConfig(); + const isOtp = msg.template_name === waConfig.otpTemplateName; + const isBookingApproved = process.env.WHATSAPP_BOOKING_TEMPLATE_APPROVED === 'true'; + if (waConfig.isLive && process.env.NODE_ENV !== 'test' && !isOtp && !isBookingApproved) { + continue; + } + + const provider = getWhatsAppProvider(); + const components = msg.metadata?.templateComponents || []; + const sendResult = await provider.sendTemplate({ + to: msg.recipient, + templateName: msg.template_name || 'nightlifez_generic_notice', + language: 'en', + components + }); + + const { rows: updated } = await db.query( + `UPDATE notification_messages + SET status = 'sent', + provider_message_id = $2, + sent_at = now(), + attempts = attempts + 1, + last_error = NULL, + updated_at = now() + WHERE id = $1 + RETURNING *`, + [msg.id, sendResult.messageId] + ); + if (updated[0]) results.push(updated[0]); + } + } catch (err) { + const errorMsg = String(err.message || err).slice(0, 500); + const { rows: updated } = await db.query( + `UPDATE notification_messages + SET attempts = attempts + 1, + last_error = $2, + updated_at = now() + WHERE id = $1 + RETURNING *`, + [msg.id, errorMsg] + ); + if (updated[0]) results.push(updated[0]); + } + } + return results; +} diff --git a/lib/services/notifications.js b/lib/services/notifications.js index 417fccd..c28906c 100644 --- a/lib/services/notifications.js +++ b/lib/services/notifications.js @@ -3,9 +3,12 @@ import { db } from '../db.js'; import { tg, isUnreachableUser } from '../telegram/api.js'; import { inviteForBooking, inviteForEntitlement } from './invites.js'; -import { siteUrl, botUsername, chatIdFromEnv, livePayments } from '../config.js'; +import { siteUrl, botUsername, chatIdFromEnv, livePayments, env } from '../config.js'; import { logger } from '../logger.js'; import { formatPaise } from './events.js'; +import { getWhatsAppProvider } from './whatsapp-provider.js'; +import { dispatchNotification } from './notification-dispatcher.js'; +import { maskPhone } from './phone.js'; export const MAX_ATTEMPTS = 6; export const NON_URGENT_KINDS = new Set(['event_announcement', 'event_reminder', 'membership_renewed', 'expiry_reminder']); @@ -95,9 +98,18 @@ async function adminChatIds() { const HANDLERS = { async booking_confirmed(n) { const b = await db.one( - `SELECT b.id, b.amount_paise, b.payment_mode, e.title, e.start_at, e.city, e.area_public, e.venue_private, e.venue_privacy, e.organiser_user_id, - e.telegram_chat_id, u.telegram_user_id - FROM bookings b JOIN events e ON e.id = b.event_id JOIN users u ON u.id = b.user_id WHERE b.id = $1`, [n.booking_id]); + `SELECT b.id, b.user_id, b.event_id, b.amount_paise, b.payment_mode, b.session_id, b.session_date, b.admit_count, + e.title, e.start_at, e.city, e.area_public, e.venue_private, e.venue_privacy, e.organiser_user_id, + e.telegram_chat_id, u.telegram_user_id, u.phone AS user_phone, + es.venue_name AS session_venue_name, es.venue_address AS session_venue_address, es.city AS session_city, + es.start_at AS session_start_at, es.label AS session_label, + tt.name AS tier_name, tt.category AS tier_category + FROM bookings b + JOIN events e ON e.id = b.event_id + JOIN users u ON u.id = b.user_id + LEFT JOIN ticket_types tt ON tt.id = b.ticket_type_id + LEFT JOIN event_sessions es ON es.id = b.session_id OR (es.event_id = b.event_id AND es.session_date = b.session_date) + WHERE b.id = $1`, [n.booking_id]); if (!b) return; let invite = null; let inviteErr = null; @@ -106,20 +118,74 @@ const HANDLERS = { } catch (err) { inviteErr = err; } - const venue = b.venue_privacy === 'public' && b.venue_private ? b.venue_private : null; + const sessionVenue = b.session_venue_address || b.session_venue_name; + const effectiveCity = b.session_city || b.city; + const effectiveStartAt = b.session_start_at || b.start_at; + const venue = b.venue_privacy === 'public' && (sessionVenue || b.venue_private) ? (sessionVenue || b.venue_private) : null; const hasGroup = Boolean(b.telegram_chat_id); - const lines = [ - `You're booked! ${escHtml(b.title)}`, - `${escHtml(fmt(b.start_at))} · ${escHtml(b.area_public ? `${b.area_public}, ` : '')}${escHtml(b.city)}`, - venue ? `Venue: ${escHtml(venue)}` : hasGroup ? 'The exact venue is shared inside the private group.' : 'The exact venue is on your booking page.', - b.payment_mode === 'free' ? 'Free ticket — no payment needed.' : b.amount_paise ? `Paid: ${formatPaise(b.amount_paise)}${b.payment_mode === 'external' ? ' on SuperProfile' : livePayments() ? '' : ' (test mode)'}` : null, - `Booking ref: ${b.id.slice(0, 8)}`, - hasGroup ? (invite ? 'Your one-time group invite is below. It works once and expires in 24 hours.' : 'Your private group invite will follow shortly.') : null - ].filter(Boolean); - const buttons = []; - if (invite) buttons.push([{ text: 'Join the private group', url: invite.link }]); - buttons.push([{ text: 'View booking', url: `${siteUrl()}/bookings/${b.id}` }]); - await send(b.telegram_user_id, lines.join('\n'), buttons); + const passUrl = `${siteUrl()}/bookings/${b.id}`; + + // 1. Dispatch Telegram bot message if telegram_user_id exists + if (b.telegram_user_id) { + const lines = [ + `You're booked! ${escHtml(b.title)}`, + `${escHtml(fmt(effectiveStartAt))} · ${escHtml(b.area_public ? `${b.area_public}, ` : '')}${escHtml(effectiveCity)}`, + venue ? `Venue: ${escHtml(venue)}` : hasGroup ? 'The exact venue is shared inside the private group.' : 'The exact venue is on your booking page.', + b.payment_mode === 'free' ? 'Free ticket — no payment needed.' : b.amount_paise ? `Paid: ${formatPaise(b.amount_paise)}${b.payment_mode === 'external' ? ' on SuperProfile' : livePayments() ? '' : ' (test mode)'}` : null, + `Booking ref: ${b.id.slice(0, 8)}`, + hasGroup ? (invite ? 'Your one-time group invite is below. It works once and expires in 24 hours.' : 'Your private group invite will follow shortly.') : null + ].filter(Boolean); + const buttons = []; + if (invite) buttons.push([{ text: 'Join the private group', url: invite.link }]); + buttons.push([{ text: 'View booking', url: passUrl }]); + await send(b.telegram_user_id, lines.join('\n'), buttons).catch((err) => { + logger.warn('Failed to deliver Telegram booking confirmation', { error: err.message, bookingId: b.id }); + }); + } + + // 2. Dispatch WhatsApp confirmation if user_phone exists and user has consented + if (b.user_phone) { + try { + const dateStr = fmt(effectiveStartAt); + const venueStr = venue || (b.venue_privacy === 'public' ? effectiveCity : 'Mystery Venue (revealed on pass)'); + const admitCount = Number.isInteger(b.admit_count) && b.admit_count > 0 ? b.admit_count : 1; + const passDetails = `${b.tier_name || 'Pass'} · ${admitCount > 1 ? `Admits ${admitCount}` : '1 guest'}`; + const templateName = env('WHATSAPP_BOOKING_TEMPLATE_NAME', 'nightlifez_booking_confirmation'); + const templateComponents = [ + { + type: 'body', + parameters: [ + { type: 'text', text: b.title }, + { type: 'text', text: dateStr }, + { type: 'text', text: venueStr }, + { type: 'text', text: passDetails }, + { type: 'text', text: passUrl } + ] + } + ]; + + await dispatchNotification({ + notificationId: n.id, + userId: b.user_id, + recipient: b.user_phone, + channel: 'whatsapp', + purpose: 'transactional', + templateName, + templateComponents, + idempotencyKey: `wa:booking:${b.id}`, + metadata: { + bookingId: b.id, + eventId: b.event_id, + passUrl, + templateComponents + } + }); + logger.info('Recorded/dispatched WhatsApp booking confirmation', { bookingId: b.id, phone: maskPhone(b.user_phone) }); + } catch (waErr) { + logger.warn('Failed to deliver WhatsApp booking confirmation (persisted for retry)', { error: waErr.message, bookingId: b.id }); + } + } + if (inviteErr) throw inviteErr; // confirmation delivered; retry later for the invite }, diff --git a/lib/services/organiser.js b/lib/services/organiser.js index 11aca26..f129272 100644 --- a/lib/services/organiser.js +++ b/lib/services/organiser.js @@ -17,6 +17,7 @@ import { resolveCity } from './locations.js'; 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'; export const MAX_IMAGES = 5; export const MAX_TIERS = 10; @@ -30,13 +31,24 @@ const EVENT_ROLES = ['super_admin', 'event_manager']; // ---------- templates & presets (sent to the wizard as JSON; defaults only, all editable) ---------- export const TICKET_PRESETS = { - general: { name: 'General', kind: 'paid', maxPerBooking: 4 }, - early_bird: { name: 'Early bird', kind: 'paid', maxPerBooking: 2 }, - couple: { name: 'Couple', kind: 'paid', maxPerBooking: 1, eligibility: 'One ticket admits two people booking together' }, - vip: { name: 'VIP', kind: 'paid', maxPerBooking: 2 }, - free: { name: 'Free entry', kind: 'free', pricePaise: 0, maxPerBooking: 2 } + general: { name: 'General', kind: 'paid', category: 'general', admitCount: 1, maxPerBooking: 4 }, + early_bird: { name: 'Early bird', kind: 'paid', category: 'early_bird', admitCount: 1, maxPerBooking: 2 }, + couple: { name: 'Couple', kind: 'paid', category: 'couple', admitCount: 2, maxPerBooking: 1, eligibility: 'One ticket admits two people booking together' }, + vip: { name: 'VIP', kind: 'paid', category: 'vip', admitCount: 1, maxPerBooking: 2, eligibility: 'VIP access included' }, + free: { name: 'Free entry', kind: 'free', category: 'general', admitCount: 1, pricePaise: 0, maxPerBooking: 2 } }; +export const TICKET_CATEGORIES = [ + { id: 'general', label: 'General admission', defaultName: 'General Admission', defaultAdmitCount: 1 }, + { id: 'men', label: "Men's Pass", defaultName: "Men's Pass", defaultAdmitCount: 1, defaultEligibility: 'Valid for male attendees' }, + { id: 'women', label: "Women's Pass", defaultName: "Women's Pass", defaultAdmitCount: 1, defaultEligibility: 'Valid for female attendees' }, + { id: 'couple', label: 'Couple Pass', defaultName: 'Couple Pass', defaultAdmitCount: 2, defaultEligibility: 'One ticket admits two people booking together' }, + { id: 'group', label: 'Group Pass', defaultName: 'Group Pass (4 pax)', defaultAdmitCount: 4, defaultEligibility: 'One pass admits a group of up to 4 people' }, + { id: 'vip', label: 'VIP Pass', defaultName: 'VIP Pass', defaultAdmitCount: 1, defaultEligibility: 'VIP access' }, + { id: 'early_bird', label: 'Early Bird', defaultName: 'Early Bird Pass', defaultAdmitCount: 1 }, + { id: 'custom', label: 'Custom Category', defaultName: 'Special Pass', defaultAdmitCount: 1 } +]; + export const QUESTION_PRESETS = { instagram: { label: 'Instagram handle', type: 'short', required: false }, age: { label: 'I confirm I am 21 or older', type: 'single', options: ['Yes'], required: true }, @@ -71,12 +83,19 @@ const flag = z.boolean().optional(); const TicketDraft = z.object({ id, name: text(60), + category: z.string().max(40).optional(), kind: z.enum(['free', 'paid']), pricePaise: looseInt, quantity: looseInt, maxPerBooking: looseInt, + minPerBooking: looseInt, + admitCount: looseInt, + salesStartAt: text(30), + salesEndAt: text(30), validOn: text(10), - eligibility: text(120) + sessionId: z.string().uuid().nullable().optional(), + eligibility: text(120), + active: flag }).strict(); const QuestionDraft = z.object({ @@ -242,11 +261,38 @@ export function publishIssues(d, { checkout = ticketCheckoutStatus(), now = new else if (itemStart <= now) err('basics', `schedule.dates.${idx}`, `Session ${idx + 1}: start time is in the past.`); if (!itemEnd) err('basics', `schedule.dates.${idx}`, `Session ${idx + 1}: add an end time.`); else if (itemStart && itemEnd <= itemStart) err('basics', `schedule.dates.${idx}`, `Session ${idx + 1}: end time must be after start time.`); + + if (sched.venueArrangement === 'different') { + if (!clean(item.venueName) && !item.venueId) { + err('basics', `schedule.dates.${idx}.venueName`, `Session ${idx + 1} (${item.date}): select or enter a venue.`); + } + if (item.mapsUrl && !isMapsUrl(item.mapsUrl)) { + err('basics', `schedule.dates.${idx}.mapsUrl`, `Session ${idx + 1}: use a Google Maps link starting with https://`); + } + } }); } } else if (sched && sched.type === 'recurring') { if (!sched.dates || sched.dates.length < 1) { err('basics', 'schedule', 'Generate recurring occurrences before publishing.'); + } else { + sched.dates.forEach((item, idx) => { + const itemStart = zonedToUtc(item.startLocal, tz); + const itemEnd = zonedToUtc(item.endLocal, tz); + if (!itemStart) err('basics', `schedule.dates.${idx}`, `Session ${idx + 1}: add a start time.`); + else if (itemStart <= now) err('basics', `schedule.dates.${idx}`, `Session ${idx + 1}: start time is in the past.`); + if (!itemEnd) err('basics', `schedule.dates.${idx}`, `Session ${idx + 1}: add an end time.`); + else if (itemStart && itemEnd <= itemStart) err('basics', `schedule.dates.${idx}`, `Session ${idx + 1}: end time must be after start time.`); + + if (sched.venueArrangement === 'different') { + if (!clean(item.venueName) && !item.venueId) { + err('basics', `schedule.dates.${idx}.venueName`, `Session ${idx + 1} (${item.date}): select or enter a venue.`); + } + if (item.mapsUrl && !isMapsUrl(item.mapsUrl)) { + err('basics', `schedule.dates.${idx}.mapsUrl`, `Session ${idx + 1}: use a Google Maps link starting with https://`); + } + } + }); } } else if (start && effectiveMultiDay) { if (!end) err('basics', 'endLocal', 'A multi-day event needs an end date.'); @@ -499,8 +545,11 @@ export function draftToRow(d, { hostFallback = '' } = {}) { contact_phone: f.contact?.enabled ? normalizePhone(f.contact.phone) : null, tiers: tickets.map((t, i) => ({ id: t.id, name: clean(t.name) || `Ticket ${i + 1}`, kind: t.kind, price_paise: t.kind === 'free' ? 0 : t.pricePaise || 0, - quantity: t.quantity, max_per_booking: t.maxPerBooking || 1, valid_on: t.validOn && t.validOn !== 'all' ? t.validOn : null, - eligibility: f.balance?.enabled ? clean(t.eligibility) || null : null, sold: 0, held: 0 + category: t.category || 'general', admit_count: t.admitCount || (t.category === 'couple' ? 2 : t.category === 'group' ? 4 : 1), + quantity: t.quantity, max_per_booking: t.maxPerBooking || 1, min_per_booking: t.minPerBooking || 1, + valid_on: t.validOn && t.validOn !== 'all' ? t.validOn : null, session_id: t.sessionId || null, + sales_start_at: t.salesStartAt || null, sales_end_at: t.salesEndAt || null, + eligibility: f.balance?.enabled || clean(t.eligibility) ? clean(t.eligibility) || null : null, sold: 0, held: 0 })) }; } @@ -617,14 +666,17 @@ 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 ev = (await c.query( `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) + organiser_org_id, checkout_mode) 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) RETURNING id, slug, category`, + $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34) RETURNING id, slug, category`, [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), @@ -634,14 +686,50 @@ 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])).rows[0]; + JSON.stringify((d.imageIds || []).map(imageUrl)), JSON.stringify(finalFeatures), coverMediaId, orgId, checkoutMode])).rows[0]; + + // Insert recurring / multi-date occurrences into event_sessions + const sessionMap = new Map(); + if (sched && sched.dates && sched.dates.length > 0) { + for (const [idx, item] of sched.dates.entries()) { + const sVenueName = sched.venueArrangement === 'different' && item.venueName ? item.venueName : clean(d.venue); + const sVenueAddress = sched.venueArrangement === 'different' && item.venueAddress ? item.venueAddress : (clean(d.venue) || null); + const sCity = sched.venueArrangement === 'different' && item.city ? item.city : canonicalCity; + const sMapsUrl = sched.venueArrangement === 'different' && item.mapsUrl ? item.mapsUrl : (d.mapsUrl || null); + const sLat = sched.venueArrangement === 'different' && item.lat != null ? item.lat : lat; + const sLng = sched.venueArrangement === 'different' && item.lng != null ? item.lng : lng; + const sTz = item.timezone || tz; + const sStart = zonedToUtc(item.startLocal, sTz); + const sEnd = item.endLocal ? zonedToUtc(item.endLocal, sTz) : null; + const sRow = (await c.query( + `INSERT INTO event_sessions ( + event_id, session_index, session_date, start_at, end_at, label, + venue_id, venue_name, venue_address, city, maps_url, lat, lng, timezone + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) + RETURNING id, session_date`, + [ev.id, idx + 1, item.date, sStart, sEnd, item.label || `Session ${idx + 1}`, + sched.venueArrangement === 'different' ? (item.venueId || null) : null, + sVenueName || null, sVenueAddress || null, sCity, sMapsUrl, sLat, sLng, sTz] + )).rows[0]; + sessionMap.set(item.date, sRow.id); + } + } for (const [i, t] of tickets.entries()) { + const admitCount = Number.isInteger(t.admitCount) && t.admitCount > 0 ? t.admitCount : (t.category === 'couple' ? 2 : t.category === 'group' ? 4 : 1); + const minPerBooking = Number.isInteger(t.minPerBooking) && t.minPerBooking > 0 ? t.minPerBooking : 1; + const category = clean(t.category) || 'general'; + const targetSessionId = t.sessionId || (t.validOn && sessionMap.get(t.validOn)) || null; await c.query( - `INSERT INTO ticket_types (event_id, name, kind, price_paise, quantity, max_per_booking, valid_on, eligibility, sort_order) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, - [ev.id, clean(t.name), t.kind, t.kind === 'free' ? 0 : t.pricePaise, t.quantity, t.maxPerBooking, - t.validOn && t.validOn !== 'all' ? t.validOn : null, f.balance?.enabled ? clean(t.eligibility) || null : null, i]); + `INSERT INTO ticket_types ( + event_id, name, kind, price_paise, quantity, max_per_booking, min_per_booking, + valid_on, eligibility, sort_order, category, admit_count, sales_start_at, sales_end_at, session_id + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`, + [ev.id, clean(t.name), t.kind, t.kind === 'free' ? 0 : t.pricePaise, t.quantity, t.maxPerBooking || 1, + minPerBooking, t.validOn && t.validOn !== 'all' ? t.validOn : null, + f.balance?.enabled || clean(t.eligibility) ? clean(t.eligibility) || null : null, + i, category, admitCount, t.salesStartAt ? new Date(t.salesStartAt) : null, + t.salesEndAt ? new Date(t.salesEndAt) : null, targetSessionId]); } if (imageIds.length) await c.query(`UPDATE event_images SET is_public = true WHERE id = ANY($1)`, [imageIds]); await c.query(`UPDATE event_drafts SET status = 'published', event_id = $2, published_at = now(), version = version + 1 WHERE id = $1`, [draftId, ev.id]); @@ -1126,6 +1214,9 @@ export async function cancelOrganiserBooking(user, bookingId, { reason = 'Cancel [bookingId, user.id, reason] ); + // Reverse infrastructure fee entry and generate credit note + await reverseBookingFeeEntry(bookingId, { reason, actor: `organiser:${user.id}` }, c); + // If booking was paid, transition payment to refund_pending (100% full refund guarantee) const pb = (await c.query( `SELECT p.id, p.order_id, p.amount, p.status diff --git a/lib/services/ticketing.js b/lib/services/ticketing.js index 483bf4d..86da7bf 100644 --- a/lib/services/ticketing.js +++ b/lib/services/ticketing.js @@ -50,10 +50,12 @@ export function validateAnswers(questions, answers) { } async function assertSeats(c, event, tier, qty, excludeBookingId = null) { + const admitCount = Number.isInteger(tier.admit_count) && tier.admit_count > 0 ? tier.admit_count : (tier.category === 'couple' ? 2 : tier.category === 'group' ? 4 : 1); + const neededSeats = qty * admitCount; const eventLeft = event.capacity - await seatsTaken(c, event.id, excludeBookingId); const tierLeft = tier.quantity - await tierSeatsTaken(c, tier.id, excludeBookingId); - if (tierLeft < qty || eventLeft < qty) { - const left = Math.max(0, Math.min(tierLeft, eventLeft)); + if (tierLeft < qty || eventLeft < neededSeats) { + const left = Math.max(0, Math.min(tierLeft, Math.floor(eventLeft / admitCount))); throw new HttpError(409, 'sold_out', left > 0 ? `Only ${left} ${tier.name} ticket${left === 1 ? '' : 's'} left` : `${tier.name} is sold out`); } } @@ -85,7 +87,8 @@ export async function bookTier(user, eventId, body) { throw new HttpError(403, 'booking_unavailable', 'You have blocked this event organiser. Unblock to book.'); } } - const tier = (await c.query('SELECT * FROM ticket_types WHERE id = $1 AND event_id = $2 AND active', [body.ticketTypeId, eventId])).rows[0]; + const tierId = body.ticketTypeId || body.tierId; + const tier = (await c.query('SELECT * FROM ticket_types WHERE id = $1 AND event_id = $2 AND active', [tierId, eventId])).rows[0]; if (!tier) throw new HttpError(404, 'ticket_not_found', 'That ticket type is not available'); const qty = body.quantity; if (qty > tier.max_per_booking) throw new HttpError(400, 'validation', `Up to ${tier.max_per_booking} ${tier.name} ticket${tier.max_per_booking === 1 ? '' : 's'} per booking`, { fields: [{ field: 'quantity', message: 'Too many tickets' }] }); @@ -118,19 +121,22 @@ export async function bookTier(user, eventId, body) { ...(typeof answers === 'object' && answers !== null ? answers : {}), policy_snapshot: eventPolicy }; - const common = [eventId, user.id, tier.id, qty, JSON.stringify(finalAnswers), body.pickupPointId || null, tier.price_paise * qty]; + const admitCount = Number.isInteger(tier.admit_count) && tier.admit_count > 0 ? tier.admit_count : (tier.category === 'couple' ? 2 : tier.category === 'group' ? 4 : 1); + const sessionId = tier.session_id || null; + const sessionDate = tier.valid_on || null; + const common = [eventId, user.id, tier.id, qty, JSON.stringify(finalAnswers), body.pickupPointId || null, tier.price_paise * qty, sessionId, sessionDate, admitCount]; if (event.requires_approval) { // A request holds no seat; availability is re-checked when the host approves. const b = (await c.query( - `INSERT INTO bookings (event_id, user_id, ticket_type_id, quantity, answers, pickup_point_id, amount_paise, status) - VALUES ($1, $2, $3, $4, $5, $6, $7, 'pending_approval') RETURNING *`, common)).rows[0]; + `INSERT INTO bookings (event_id, user_id, ticket_type_id, quantity, answers, pickup_point_id, amount_paise, session_id, session_date, admit_count, status) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'pending_approval') RETURNING *`, common)).rows[0]; const nid = await notifyHost(c, event, b); await audit(`user:${user.id}`, 'booking.request', b.id, { eventId, tier: tier.id, qty }, c); return { booking: b, notificationIds: nid ? [nid] : [] }; } const b = (await c.query( - `INSERT INTO bookings (event_id, user_id, ticket_type_id, quantity, answers, pickup_point_id, amount_paise, status, payment_mode, confirmed_at) - VALUES ($1, $2, $3, $4, $5, $6, $7, 'confirmed', 'free', now()) RETURNING *`, common)).rows[0]; + `INSERT INTO bookings (event_id, user_id, ticket_type_id, quantity, answers, pickup_point_id, amount_paise, session_id, session_date, admit_count, status, payment_mode, confirmed_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'confirmed', 'free', now()) RETURNING *`, common)).rows[0]; await issueTicketsForBooking(b.id, c); const nid = await enqueue(c, { kind: 'booking_confirmed', userId: user.id, bookingId: b.id, dedupeKey: `bk:${b.id}:confirmed` }); await audit(`user:${user.id}`, 'booking.confirmed_free', b.id, { eventId, tier: tier.id, qty }, c); diff --git a/lib/services/tickets.js b/lib/services/tickets.js index 0cfe0cb..72d7dc3 100644 --- a/lib/services/tickets.js +++ b/lib/services/tickets.js @@ -109,7 +109,12 @@ export async function issueTicketsForBooking(bookingId, c = db) { async function doIssue(client) { const b = (await client.query( - `SELECT id, event_id, user_id, ticket_type_id, quantity, status FROM bookings WHERE id = $1 FOR UPDATE`, + `SELECT b.id, b.event_id, b.user_id, b.ticket_type_id, b.quantity, b.status, + b.session_id, b.session_date, b.admit_count, + tt.session_id AS tier_session_id, tt.valid_on AS tier_valid_on, tt.admit_count AS tier_admit_count + FROM bookings b + LEFT JOIN ticket_types tt ON tt.id = b.ticket_type_id + WHERE b.id = $1 FOR UPDATE OF b`, [bookingId] )).rows[0]; if (!b) throw new HttpError(404, 'not_found', 'Booking not found'); @@ -123,6 +128,10 @@ export async function issueTicketsForBooking(bookingId, c = db) { )).rows; if (existing.length > 0) return existing; + const sessionId = b.session_id || b.tier_session_id || null; + const sessionDate = b.session_date || b.tier_valid_on || null; + const admitCount = Number.isInteger(b.admit_count) && b.admit_count > 0 ? b.admit_count : (b.tier_admit_count || 1); + const tickets = []; const qty = Math.max(1, Number(b.quantity) || 1); for (let i = 1; i <= qty; i++) { @@ -131,10 +140,13 @@ export async function issueTicketsForBooking(bookingId, c = db) { const initialStatus = b.status === 'checked_in' ? 'checked_in' : 'valid'; const checkedInAt = initialStatus === 'checked_in' ? 'NOW()' : 'NULL'; const r = (await client.query( - `INSERT INTO tickets (booking_id, event_id, user_id, ticket_type_id, ticket_number, ticket_code, security_hash, status, checked_in_at) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, ${checkedInAt}) + `INSERT INTO tickets ( + booking_id, event_id, user_id, ticket_type_id, ticket_number, ticket_code, + security_hash, status, session_id, session_date, admit_count, checked_in_at + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, ${checkedInAt}) RETURNING *`, - [b.id, b.event_id, b.user_id, b.ticket_type_id, i, code, hash, initialStatus] + [b.id, b.event_id, b.user_id, b.ticket_type_id, i, code, hash, initialStatus, sessionId, sessionDate, admitCount] )).rows[0]; tickets.push(r); } @@ -186,6 +198,9 @@ export async function getBookingTickets(bookingId, viewerUser = null, c = db) { ticketCode: t.ticket_code, status: t.status, checkedInAt: t.checked_in_at, + sessionId: t.session_id || null, + sessionDate: t.session_date ? String(t.session_date).slice(0, 10) : null, + admitCount: t.admit_count || 1, tierName: t.tier_name || 'Standard Admission', qrPayload, qrSvg: generateTicketQrSvg(qrPayload) @@ -196,7 +211,7 @@ export async function getBookingTickets(bookingId, viewerUser = null, c = db) { /** * Server-authoritative ticket validation and check-in. */ -export async function checkInTicket(actor, eventId, { ticketCode = null, qrPayload = null, method = 'camera_qr', overrideReason = null } = {}, c = db) { +export async function checkInTicket(actor, eventId, { ticketCode = null, qrPayload = null, method = 'camera_qr', overrideReason = null, sessionId = null, sessionDate = null } = {}, c = db) { if (!actor || !actor.id) throw new HttpError(401, 'unauthorized', 'Authentication required'); // Verify permission @@ -258,7 +273,10 @@ export async function checkInTicket(actor, eventId, { ticketCode = null, qrPaylo return await db.tx(async (txClient) => { const t = (await txClient.query( `SELECT t.*, b.status AS booking_status, b.payment_mode, b.amount_paise, - u.alias AS attendee_alias, tt.name AS tier_name + u.alias AS attendee_alias, tt.name AS tier_name, tt.category AS tier_category, + COALESCE(t.admit_count, b.admit_count, tt.admit_count, 1) AS effective_admit_count, + COALESCE(t.session_id, b.session_id, tt.session_id) AS effective_session_id, + COALESCE(t.session_date, b.session_date, tt.valid_on) AS effective_session_date FROM tickets t JOIN bookings b ON b.id = t.booking_id JOIN users u ON u.id = t.user_id @@ -281,6 +299,24 @@ export async function checkInTicket(actor, eventId, { ticketCode = null, qrPaylo }); } + if (sessionId && t.effective_session_id && t.effective_session_id !== sessionId) { + if (method !== 'manual_override') { + throw new HttpError(400, 'session_mismatch', 'This ticket is valid for a different session', { + ticketSessionId: t.effective_session_id, + scannerSessionId: sessionId + }); + } + } + + if (sessionDate && t.effective_session_date && t.effective_session_date !== sessionDate) { + if (method !== 'manual_override') { + throw new HttpError(400, 'session_date_mismatch', `This ticket is valid for session on ${t.effective_session_date}`, { + ticketSessionDate: t.effective_session_date, + scannerSessionDate: sessionDate + }); + } + } + if (t.status === 'checked_in') { const prevStaff = t.checked_in_by ? (await txClient.query(`SELECT alias FROM users WHERE id = $1`, [t.checked_in_by])).rows[0]?.alias : 'Staff'; throw new HttpError(409, 'already_checked_in', 'This ticket has already been checked in', { @@ -292,6 +328,7 @@ export async function checkInTicket(actor, eventId, { ticketCode = null, qrPaylo }, checkedInAt: t.checked_in_at, checkedInByAlias: prevStaff, + admitCount: t.effective_admit_count, attendee: { alias: t.attendee_alias, tier: t.tier_name, ref: t.booking_id.slice(0, 8) } }); } @@ -371,12 +408,13 @@ export async function checkInTicket(actor, eventId, { ticketCode = null, qrPaylo eventId, ticketId: t.id, bookingId: t.booking_id, + sessionId: t.effective_session_id || null, scannedBy: actor.id, result: scanResult, method, overrideReason: overrideReason || null, payloadHash, - metadata: { code, attendeeAlias: t.attendee_alias, tier: t.tier_name } + metadata: { code, attendeeAlias: t.attendee_alias, tier: t.tier_name, admitCount: t.effective_admit_count, sessionDate: t.effective_session_date } }, txClient); const auditAction = method === 'manual_override' ? 'ticket.manual_override' : 'ticket.check_in'; @@ -384,7 +422,9 @@ export async function checkInTicket(actor, eventId, { ticketCode = null, qrPaylo eventId, ticketCode: t.ticket_code, method, - overrideReason: overrideReason || null + overrideReason: overrideReason || null, + admitCount: t.effective_admit_count, + sessionId: t.effective_session_id || null }, txClient); return { @@ -396,11 +436,16 @@ export async function checkInTicket(actor, eventId, { ticketCode = null, qrPaylo ticketNumber: t.ticket_number, status: 'checked_in', checkedInAt: now.toISOString(), - method + method, + admitCount: t.effective_admit_count, + sessionId: t.effective_session_id, + sessionDate: t.effective_session_date }, attendee: { alias: t.attendee_alias || 'Guest', ticketType: t.tier_name || 'Standard', + category: t.tier_category || 'general', + admitCount: t.effective_admit_count, ref: t.booking_id.slice(0, 8).toUpperCase() } }; @@ -598,10 +643,10 @@ function hashPayload(str) { return crypto.createHash('sha256').update(String(str || '')).digest('hex'); } -async function recordScanLog({ eventId, ticketId, bookingId, scannedBy, result, method, overrideReason = null, payloadHash, metadata = {} }, c) { +async function recordScanLog({ eventId, ticketId, bookingId, sessionId = null, scannedBy, result, method, overrideReason = null, payloadHash, metadata = {} }, c) { await c.query( - `INSERT INTO ticket_scans (event_id, ticket_id, booking_id, scanned_by, scan_result, scan_method, override_reason, scanned_payload_hash, metadata) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, - [eventId, ticketId, bookingId, scannedBy, result, method, overrideReason, payloadHash, JSON.stringify(metadata)] + `INSERT INTO ticket_scans (event_id, ticket_id, booking_id, session_id, scanned_by, scan_result, scan_method, override_reason, scanned_payload_hash, metadata) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, + [eventId, ticketId, bookingId, sessionId, scannedBy, result, method, overrideReason, payloadHash, JSON.stringify(metadata)] ); } diff --git a/lib/services/upi-payments.js b/lib/services/upi-payments.js index 3a40360..4a0fba0 100644 --- a/lib/services/upi-payments.js +++ b/lib/services/upi-payments.js @@ -5,7 +5,8 @@ import crypto from 'node:crypto'; import { db } from '../db.js'; import { HttpError } from '../http.js'; import { audit } from '../audit.js'; -import { upiCheckoutEnabled } from '../config.js'; +import { upiCheckoutEnabled, isProductionRuntime } from '../config.js'; +import { isLiveGatewayConfigured } from '../payments/availability.js'; import { phonePeInstance, mockInstance, PhonePeAdapter, PaymentAdapterError } from '../upi/adapter.js'; import { enqueue } from './notifications.js'; import { removeFromChat } from './invites.js'; @@ -13,6 +14,13 @@ import { seatsTaken, tierSeatsTaken } from './bookings.js'; import { logger } from '../logger.js'; import { issueTicketsForBooking } from './tickets.js'; import { resolveCancellationPolicy } from './cancellation-policy.js'; +import { + calculateInfrastructureFee, + getActiveFeeRule, + recordBookingFeeEntry, + reverseBookingFeeEntry, + DEFAULT_FEE_PERCENTAGE +} from './finance.js'; export const UPI_LEGAL_TRANSITIONS = { created: ['pending', 'failed', 'expired', 'cancelled'], @@ -156,7 +164,7 @@ export function getAdapter(provider = null) { */ export async function activePaymentHolds(c, eventId, excludeOrderId = null) { const { rows } = await c.query( - `SELECT COALESCE(sum((p.raw_ref->>'qty')::int), 0)::int AS n + `SELECT COALESCE(sum((p.raw_ref->>'qty')::int * COALESCE((p.raw_ref->>'admitCount')::int, 1)), 0)::int AS n FROM payments p WHERE (p.raw_ref->>'eventId')::uuid = $1 AND p.status IN ('created', 'pending', 'processing') @@ -203,6 +211,9 @@ export async function createUpiPaymentIntent({ clientIp = '127.0.0.1' }) { assertUpiCheckoutEnabled(); + if (isProductionRuntime() && !isLiveGatewayConfigured()) { + throw new HttpError(403, 'gateway_pending_configuration', 'Paid checkout is pending payment gateway configuration in Production.'); + } if (process.env.VERCEL_ENV === 'preview' && process.env.ALLOW_PREVIEW_PAID_CHECKOUT !== 'true') { throw new HttpError(403, 'preview_paid_checkout_disabled', 'Paid checkout is disabled in Preview deployments.'); } @@ -212,7 +223,7 @@ export async function createUpiPaymentIntent({ return db.tx(async (c) => { // 1. Fetch and lock event const event = (await c.query( - `SELECT id, slug, title, status, start_at, capacity, checkout_mode FROM events + `SELECT id, slug, title, status, start_at, capacity, checkout_mode, organiser_user_id, organiser_upi_id, infrastructure_fee_deadline FROM events WHERE slug = $1 FOR UPDATE`, [slug] )).rows[0]; @@ -226,17 +237,32 @@ export async function createUpiPaymentIntent({ // 2. Fetch ticket tier const tier = (await c.query( - `SELECT id, name, kind, price_paise, quantity, max_per_booking, active FROM ticket_types - WHERE id = $1 AND event_id = $2 AND active`, + `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 + FROM ticket_types + WHERE id = $1 AND event_id = $2 AND active`, [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} 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. Assert capacity including confirmed bookings AND active payment holds const takenEventBookings = await seatsTaken(c, event.id); @@ -247,7 +273,7 @@ export async function createUpiPaymentIntent({ const totalEventTaken = takenEventBookings + takenEventHolds; const totalTierTaken = takenTierBookings + takenTierHolds; - if ((event.capacity - totalEventTaken < qty) || (tier.quantity - totalTierTaken < qty)) { + if ((event.capacity - totalEventTaken < eventSeatsNeeded) || (tier.quantity - totalTierTaken < qty)) { throw new HttpError(409, 'sold_out', `${tier.name} is sold out or held by active checkout sessions`); } @@ -266,10 +292,26 @@ export async function createUpiPaymentIntent({ } } - // 4. Generate Order ID & call Payment Adapter + // 4. Generate Order ID, calculate transparent 5% platform fee for organiser events & call Payment Adapter const orderId = newUpiOrderId(); const guestToken = crypto.randomBytes(24).toString('base64url'); - const amountPaise = tier.price_paise * qty; + const baseAmountPaise = tier.price_paise * qty; + let feePct = 0; + let feeRuleId = null; + let calc = { + basePaise: baseAmountPaise, + feePaise: 0, + totalPaise: baseAmountPaise, + feePercentage: 0 + }; + + if (event.organiser_user_id) { + const activeRule = await getActiveFeeRule(c); + feePct = Number(activeRule?.fee_percentage ?? DEFAULT_FEE_PERCENTAGE); + feeRuleId = activeRule?.id || null; + calc = calculateInfrastructureFee(baseAmountPaise, feePct); + } + const amountPaise = calc.totalPaise; const adapter = getAdapter(); const configuredMerchantId = adapter?.merchantId; @@ -307,13 +349,28 @@ export async function createUpiPaymentIntent({ configuredMerchantId.trim(), resolvedUserId, amountPaise, - Boolean(adapter.isSandbox), + Boolean(adapter.isSandbox || !isLiveGatewayConfigured()), deviceType === 'mobile' ? 'upi_intent' : 'upi_qr', deviceType, intent.upiIntentUrl, intent.qrData, intent.expiresAt, - JSON.stringify({ eventId: event.id, ticketTypeId: tier.id, qty, deviceType, guestToken }) + JSON.stringify({ + eventId: event.id, + ticketTypeId: tier.id, + qty, + admitCount, + sessionId: tier.session_id || null, + sessionDate: tier.valid_on || null, + deviceType, + guestToken, + baseAmountPaise: calc.basePaise, + feePaise: calc.feePaise, + totalAmountPaise: calc.totalPaise, + feePercentage: feePct, + feeRuleId: feeRuleId, + organiserUpiId: event.organiser_upi_id || null + }) ] )).rows[0]; @@ -325,7 +382,7 @@ export async function createUpiPaymentIntent({ payment.id, orderId, resolvedUserId ? `user:${resolvedUserId}` : `guest:${clientIp}`, - JSON.stringify({ eventId: event.id, tierId: tier.id, qty, amountPaise, guestToken }) + JSON.stringify({ eventId: event.id, tierId: tier.id, qty, amountPaise, baseAmountPaise: calc.basePaise, feePaise: calc.feePaise, guestToken }) ] ); @@ -334,18 +391,25 @@ export async function createUpiPaymentIntent({ status: 'pending', amountPaise, amountRupees: (amountPaise / 100).toFixed(2), + baseAmountPaise: calc.basePaise, + baseAmountRupees: (calc.basePaise / 100).toFixed(2), + feePaise: calc.feePaise, + feeRupees: (calc.feePaise / 100).toFixed(2), + feePercentage: feePct, currency: 'INR', eventTitle: event.title, tierName: tier.name, quantity: qty, guestToken, + isTest: Boolean(payment.is_test), upiIntentUrl: intent.upiIntentUrl, upiUri: intent.upiIntentUrl, appIntents: intent.appIntents, qrData: intent.qrData, qrSvg: intent.qrSvg, expiresInSeconds: intent.expiresInSeconds, - expiresAt: intent.expiresAt + expiresAt: intent.expiresAt, + organiserUpiId: event.organiser_upi_id || null }; }); } @@ -434,11 +498,18 @@ export async function getUpiPaymentStatus(orderId, { user = null, guestToken = n } } + const rawRef = payment.raw_ref || {}; return { orderId: payment.order_id, status: payment.status, amountPaise: Number(payment.amount), amountRupees: (Number(payment.amount) / 100).toFixed(2), + baseAmountPaise: rawRef.baseAmountPaise || Number(payment.amount), + baseAmountRupees: ((rawRef.baseAmountPaise || Number(payment.amount)) / 100).toFixed(2), + feePaise: rawRef.feePaise || 0, + feeRupees: ((rawRef.feePaise || 0) / 100).toFixed(2), + feePercentage: rawRef.feePercentage || DEFAULT_FEE_PERCENTAGE, + organiserUpiId: rawRef.organiserUpiId || null, currency: payment.currency, eventTitle: payment.event_title, eventSlug: payment.event_slug, @@ -581,6 +652,7 @@ export async function applySuccessfulUpiPayment({ const event = (await c.query(`SELECT * FROM events WHERE id = $1 FOR UPDATE`, [eventId])).rows[0]; if (!event) throw new HttpError(404, 'event_not_found', 'Event not found'); + let tier = ticketTypeId ? (await c.query(`SELECT * FROM ticket_types WHERE id = $1`, [ticketTypeId])).rows[0] : null; // REV-02: Check existing active bookings inside locked confirmation transaction if (payment.user_id) { @@ -679,7 +751,7 @@ export async function applySuccessfulUpiPayment({ } if (ticketTypeId) { - const tier = (await c.query(`SELECT * FROM ticket_types WHERE id = $1 FOR UPDATE`, [ticketTypeId])).rows[0]; + tier = (await c.query(`SELECT * FROM ticket_types WHERE id = $1 FOR UPDATE`, [ticketTypeId])).rows[0]; if (tier && tier.capacity) { const tierTaken = await tierSeatsTaken(c, tier.id); if (tier.capacity - tierTaken < qty) { @@ -764,15 +836,36 @@ export async function applySuccessfulUpiPayment({ }; try { await c.query('SAVEPOINT sp_confirm_booking'); + const admitCount = Number.isInteger(refData.admitCount) && refData.admitCount > 0 ? refData.admitCount : 1; + const sessionId = refData.sessionId || null; + const sessionDate = refData.sessionDate || null; + const basePricePaise = refData.baseAmountPaise || Math.round(payment.amount / 1.05); + const feePaise = refData.feePaise || (payment.amount - basePricePaise); + const feePercentage = refData.feePercentage || DEFAULT_FEE_PERCENTAGE; + const feeRuleId = refData.feeRuleId || null; + const feeSnapshot = { + baseAmountPaise: basePricePaise, + feePaise, + totalCollectedPaise: payment.amount, + feePercentage, + calculatedAt: new Date().toISOString() + }; booking = (await c.query( `INSERT INTO bookings ( event_id, user_id, ticket_type_id, quantity, status, amount_paise, - payment_mode, source, confirmed_at, payment_id, answers - ) VALUES ($1, $2, $3, $4, 'confirmed', $5, 'provider', 'site', now(), $6, $7) + base_price_paise, infrastructure_fee_paise, fee_percentage, fee_rule_id, fee_calculation_snapshot, + payment_mode, source, confirmed_at, payment_id, answers, + session_id, session_date, admit_count + ) VALUES ($1, $2, $3, $4, 'confirmed', $5, $6, $7, $8, $9, $10, 'provider', 'site', now(), $11, $12, $13, $14, $15) RETURNING *`, - [event.id, payment.user_id, ticketTypeId, qty, payment.amount, payment.id, JSON.stringify(answersWithSnapshot)] + [ + event.id, payment.user_id, ticketTypeId, qty, payment.amount, + basePricePaise, feePaise, feePercentage, feeRuleId, JSON.stringify(feeSnapshot), + payment.id, JSON.stringify(answersWithSnapshot), sessionId, sessionDate, admitCount + ] )).rows[0]; await issueTicketsForBooking(booking.id, c); + await recordBookingFeeEntry(booking, event, tier, c); await c.query('RELEASE SAVEPOINT sp_confirm_booking'); } catch (err) { if (err.code === '23505') { @@ -901,6 +994,7 @@ export async function claimUpiBooking({ orderId, guestToken, user }) { const event = (await c.query(`SELECT * FROM events WHERE id = $1 FOR UPDATE`, [eventId])).rows[0]; if (!event) throw new HttpError(404, 'event_not_found', 'Event not found'); + let tier = ticketTypeId ? (await c.query(`SELECT * FROM ticket_types WHERE id = $1`, [ticketTypeId])).rows[0] : null; // REV-02: Prevent duplicate active booking on guest claim const existingActiveBooking = (await c.query( @@ -923,15 +1017,36 @@ export async function claimUpiBooking({ orderId, guestToken, user }) { }; try { await c.query('SAVEPOINT sp_claim_booking'); + const admitCount = Number.isInteger(refData.admitCount) && refData.admitCount > 0 ? refData.admitCount : 1; + const sessionId = refData.sessionId || null; + const sessionDate = refData.sessionDate || null; + const basePricePaise = refData.baseAmountPaise || Math.round(payment.amount / 1.05); + const feePaise = refData.feePaise || (payment.amount - basePricePaise); + const feePercentage = refData.feePercentage || DEFAULT_FEE_PERCENTAGE; + const feeRuleId = refData.feeRuleId || null; + const feeSnapshot = { + baseAmountPaise: basePricePaise, + feePaise, + totalCollectedPaise: payment.amount, + feePercentage, + calculatedAt: new Date().toISOString() + }; booking = (await c.query( `INSERT INTO bookings ( event_id, user_id, ticket_type_id, quantity, status, amount_paise, - payment_mode, source, confirmed_at, payment_id, answers - ) VALUES ($1, $2, $3, $4, 'confirmed', $5, 'provider', 'site', now(), $6, $7) + base_price_paise, infrastructure_fee_paise, fee_percentage, fee_rule_id, fee_calculation_snapshot, + payment_mode, source, confirmed_at, payment_id, answers, + session_id, session_date, admit_count + ) VALUES ($1, $2, $3, $4, 'confirmed', $5, $6, $7, $8, $9, $10, 'provider', 'site', now(), $11, $12, $13, $14, $15) RETURNING *`, - [event.id, uid, ticketTypeId, qty, payment.amount, payment.id, JSON.stringify(answersWithSnapshot)] + [ + event.id, uid, ticketTypeId, qty, payment.amount, + basePricePaise, feePaise, feePercentage, feeRuleId, JSON.stringify(feeSnapshot), + payment.id, JSON.stringify(answersWithSnapshot), sessionId, sessionDate, admitCount + ] )).rows[0]; await issueTicketsForBooking(booking.id, c); + await recordBookingFeeEntry(booking, event, tier, c); await c.query('RELEASE SAVEPOINT sp_claim_booking'); } catch (err) { if (err.code === '23505') { @@ -1041,6 +1156,7 @@ export async function processUpiWebhook({ headers, rawBody, clientIp, adapter = [payment.id, orderId, payment.status, `webhook:${verified.provider}`, JSON.stringify(verified.raw || {})] ); if (payment.booking_id) { + await reverseBookingFeeEntry(payment.booking_id, { reason: 'Refund webhook confirmed', actor: `webhook:${verified.provider}` }, c); await c.query(`UPDATE bookings SET status = 'refunded', refunded_at = now() WHERE id = $1`, [payment.booking_id]); await c.query(`UPDATE invite_links SET revoked_at = COALESCE(revoked_at, now()) WHERE booking_id = $1 AND used_at IS NULL`, [payment.booking_id]); const joined = (await c.query( @@ -1225,6 +1341,7 @@ export async function refundUpiOrder(orderId, { ); if (p.booking_id) { + await reverseBookingFeeEntry(p.booking_id, { reason, adminUser: sessionAdmin, actor: verifiedActor }, c); await c.query(`UPDATE bookings SET status = 'refunded', refunded_at = now() WHERE id = $1`, [p.booking_id]); await c.query(`UPDATE invite_links SET revoked_at = COALESCE(revoked_at, now()) WHERE booking_id = $1 AND used_at IS NULL`, [p.booking_id]); const joined = (await c.query( @@ -1331,6 +1448,7 @@ export async function refundUpiOrder(orderId, { ); if (isCompleted && p.booking_id) { + await reverseBookingFeeEntry(p.booking_id, { reason, actor }, c); await c.query(`UPDATE bookings SET status = 'refunded', refunded_at = now() WHERE id = $1`, [p.booking_id]); await c.query(`UPDATE invite_links SET revoked_at = COALESCE(revoked_at, now()) WHERE booking_id = $1 AND used_at IS NULL`, [p.booking_id]); const joined = (await c.query( diff --git a/lib/views/checkout-upi.js b/lib/views/checkout-upi.js index 0790757..bb30b50 100644 --- a/lib/views/checkout-upi.js +++ b/lib/views/checkout-upi.js @@ -12,9 +12,20 @@ export function renderUpiCheckout({ csrfToken = '' }) { const amountRupees = (order.amountPaise / 100).toFixed(2); + const baseRupees = order.baseAmountPaise !== undefined + ? (order.baseAmountPaise / 100).toFixed(2) + : (tier.price_paise ? ((tier.price_paise * (order.quantity || 1)) / 100).toFixed(2) : amountRupees); + const feeRupees = order.feePaise !== undefined + ? (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 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 totalAdmit = (order.quantity || 1) * admitCount; const body = html`
@@ -22,25 +33,50 @@ export function renderUpiCheckout({
+ ${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.

+
` : ''} +
- Payment session expires in: + Seat reservation holds for: 15:00
@@ -54,7 +90,7 @@ export function renderUpiCheckout({
- or open directly in + or choose your preferred app
@@ -107,22 +143,22 @@ export function renderUpiCheckout({
-

Awaiting payment authorization...

+

Awaiting payment authorization from bank...

@@ -137,7 +173,7 @@ export function renderUpiCheckout({