From ff5773c202659144676360f84e111ece39df0d82 Mon Sep 17 00:00:00 2001 From: Satelink Network Date: Tue, 24 Nov 2026 19:36:31 +0530 Subject: [PATCH] feat: advanced event configuration and professional ticketing system - Migration 033: schema for event facilities, venue layouts & sections, sales phases, offers & discounts, and booking price snapshots - Module 1: Predefined and custom event facilities & amenities with category grouping and public event page display - Module 2: Offers & discount engine supporting percentage and flat discounts, promo codes, minimum quantities, caps, and organiser analytics - Module 3: Visual interactive venue layout & section-based ticketing with stage/VIP/fanpit/gold presets, per-section pricing/capacity, and row-locking reservation guards - Module 4: Sales timeline & scheduled pricing phases with server-clock authoritative state evaluation, phase price overrides, quotas, and access code unlocks - Integrated unified pricing engine into direct UPI checkout flow, maintaining zero live gateway dependencies and preserving full backward compatibility for free events - Organiser wizard extensions with dedicated configuration cards and responsive mobile tap-target guards - Full test coverage with 11 new integration tests in advanced-event-ticketing.test.js and migration 033 verification --- lib/handlers/organiser.js | 5 + lib/handlers/upi-checkout.js | 14 +- lib/router.js | 2 +- lib/services/direct-upi.js | 126 ++- lib/services/event-facilities.js | 112 +++ lib/services/event-offers.js | 274 +++++++ lib/services/event-venue.js | 157 ++++ lib/services/events.js | 32 +- lib/services/organiser.js | 139 +++- lib/services/pricing-engine.js | 187 +++++ lib/services/sales-phases.js | 141 ++++ lib/views/checkout-upi.js | 15 +- lib/views/event.js | 132 ++++ lib/views/layout.js | 2 +- lib/views/pages.js | 4 +- .../033_advanced_event_configuration.sql | 172 ++++ public/css/organiser.css | 1 + public/js/organiser.js | 387 ++++++++- test/advanced-event-ticketing.test.js | 741 ++++++++++++++++++ test/migrations.test.js | 59 +- 20 files changed, 2669 insertions(+), 33 deletions(-) create mode 100644 lib/services/event-facilities.js create mode 100644 lib/services/event-offers.js create mode 100644 lib/services/event-venue.js create mode 100644 lib/services/pricing-engine.js create mode 100644 lib/services/sales-phases.js create mode 100644 migrations/033_advanced_event_configuration.sql create mode 100644 test/advanced-event-ticketing.test.js diff --git a/lib/handlers/organiser.js b/lib/handlers/organiser.js index 605fe1b..f5ce968 100644 --- a/lib/handlers/organiser.js +++ b/lib/handlers/organiser.js @@ -5,6 +5,8 @@ import { HttpError, readJson, readBinaryBody, sendJson, sendHtml, redirect } from '../http.js'; import { getSessionUser, requireUser, requireCsrf, csrfTokenFor } from '../session.js'; import { parse, z, uuid } from '../validate.js'; +import { PREDEFINED_FACILITIES, FACILITY_CATEGORIES } from '../services/event-facilities.js'; +import { SECTION_PRESETS } from '../services/event-venue.js'; import { rateLimit } from '../ratelimit.js'; import { afterResponse } from '../after.js'; import { deliverMany } from '../services/notifications.js'; @@ -84,6 +86,9 @@ function wizardConfig(user, draftId, venueId = null) { categories: Object.entries(CATEGORY_LABELS), timezones: TIMEZONES, checkout: ticketCheckoutStatus(), + predefinedFacilities: PREDEFINED_FACILITIES, + facilityCategories: FACILITY_CATEGORIES, + sectionPresets: SECTION_PRESETS, limits: { images: O.MAX_IMAGES, imageBytes: O.MAX_IMAGE_BYTES, tiers: O.MAX_TIERS, questions: O.MAX_QUESTIONS, pickups: O.MAX_PICKUPS, days: O.MAX_EVENT_DAYS } }; } diff --git a/lib/handlers/upi-checkout.js b/lib/handlers/upi-checkout.js index 1c81499..1630c54 100644 --- a/lib/handlers/upi-checkout.js +++ b/lib/handlers/upi-checkout.js @@ -56,12 +56,12 @@ export async function upiCheckoutPage({ req, res, params, query, ip }) { } // Determine tier - let tierId = query.get('tier') || query.get('ticket_type_id'); + let tierId = query.get('tier') || query.get('ticketTypeId') || query.get('ticket_type_id'); let tier; if (tierId) { tier = await db.one( `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`, + WHERE (id::text = $1 OR name = $1) AND event_id = $2 AND active`, [tierId, event.id] ); } else { @@ -78,6 +78,10 @@ export async function upiCheckoutPage({ req, res, params, query, ip }) { } const qty = parseInt(query.get('qty') || query.get('quantity'), 10) || 1; + const promoCode = query.get('code') || query.get('promo') || query.get('promoCode') || query.get('promo_code') || null; + const sectionId = query.get('section') || query.get('sectionId') || query.get('section_id') || null; + const phaseId = query.get('phase') || query.get('phaseId') || query.get('phase_id') || null; + const accessCode = query.get('access') || query.get('accessCode') || query.get('access_code') || null; let order; if (isDirectUpi) { @@ -85,7 +89,11 @@ export async function upiCheckoutPage({ req, res, params, query, ip }) { slug, user, ticketTypeId: tier.id, - quantity: qty + quantity: qty, + sectionId, + phaseId, + promoCode, + accessCode }); } else { order = await createUpiPaymentIntent({ diff --git a/lib/router.js b/lib/router.js index 43afef5..d62a74d 100644 --- a/lib/router.js +++ b/lib/router.js @@ -373,7 +373,7 @@ export async function handle(req, res) { if (err.extra?.retryAfter) res.setHeader('Retry-After', String(err.extra.retryAfter)); if (wantsHtml(pathname)) { const { renderNotFound, renderError } = await import('./views/pages.js'); - sendHtml(res, status, status === 404 ? renderNotFound() : renderError()); + sendHtml(res, status, status === 404 ? renderNotFound() : renderError(err.message || 'Something went wrong')); } else { const safe = err instanceof HttpError ? { ok: false, error: err.code, message: err.message, ...(err.extra || {}) } diff --git a/lib/services/direct-upi.js b/lib/services/direct-upi.js index 93d809d..07a69cd 100644 --- a/lib/services/direct-upi.js +++ b/lib/services/direct-upi.js @@ -13,6 +13,9 @@ import { seatsTaken, tierSeatsTaken } from './bookings.js'; import { issueTicketsForBooking } from './tickets.js'; import { enqueue } from './notifications.js'; import { can } from './permissions.js'; +import { calculateBookingPrice, createBookingPriceSnapshot } from './pricing-engine.js'; +import { recordOfferRedemption } from './event-offers.js'; +import { assertAndRecordPhaseSale } from './sales-phases.js'; export const DIRECT_UPI_STATUSES = [ 'awaiting_payment', @@ -52,7 +55,12 @@ export async function createDirectUpiBooking({ ticketTypeId, quantity = 1, answers = {}, - pickupPointId = null + pickupPointId = null, + sectionId = null, + phaseId = null, + promoCode = null, + offerId = null, + accessCode = null }) { if (!user) throw new HttpError(401, 'unauthorized', 'Please sign in to book tickets.'); if (!user.age_confirmed_21) throw new HttpError(403, 'age_required', 'Please confirm you are 21 or older.'); @@ -133,6 +141,19 @@ export async function createDirectUpiBooking({ if (b.status === 'pending_payment') { const isExpired = !b.hold_expires_at || new Date(b.hold_expires_at) <= new Date(); if (isExpired) { + if (b.phase_id) { + await c.query( + `UPDATE event_sales_phases SET tickets_sold = GREATEST(0, tickets_sold - $2), updated_at = now() WHERE id = $1`, + [b.phase_id, b.quantity] + ); + } + if (b.offer_id) { + await c.query( + `UPDATE event_offers SET redemption_count = GREATEST(0, redemption_count - 1), updated_at = now() WHERE id = $1`, + [b.offer_id] + ); + await c.query(`DELETE FROM offer_redemptions WHERE booking_id = $1`, [b.id]); + } await c.query( `UPDATE bookings SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'hold_expired', @@ -142,9 +163,22 @@ export async function createDirectUpiBooking({ ); } else { // Live unexpired hold exists for this user: return it if matching tier, or cancel to replace - if (b.ticket_type_id === tier.id && b.quantity === qty) { + if (b.ticket_type_id === tier.id && b.quantity === qty && !promoCode && !offerId && !sectionId) { return formatDirectUpiOrder(b, event, tier); } + if (b.phase_id) { + await c.query( + `UPDATE event_sales_phases SET tickets_sold = GREATEST(0, tickets_sold - $2), updated_at = now() WHERE id = $1`, + [b.phase_id, b.quantity] + ); + } + if (b.offer_id) { + await c.query( + `UPDATE event_offers SET redemption_count = GREATEST(0, redemption_count - 1), updated_at = now() WHERE id = $1`, + [b.offer_id] + ); + await c.query(`DELETE FROM offer_redemptions WHERE booking_id = $1`, [b.id]); + } await c.query( `UPDATE bookings SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'hold_replaced', @@ -165,8 +199,25 @@ export async function createDirectUpiBooking({ throw new HttpError(409, 'sold_out', left > 0 ? `Only ${left} ${tier.name} ticket${left === 1 ? '' : 's'} left.` : `${tier.name} is sold out.`); } - // 5. Server-side total amount calculation (never trust client) - const totalAmountPaise = tier.price_paise * qty; + // 5. Server-side unified pricing calculation (never trust client) + const pricing = await calculateBookingPrice({ + c, + event, + tier, + sectionId, + phaseId, + quantity: qty, + promoCode, + offerId, + userId: user.id, + accessCode + }); + + if (pricing.activePhase) { + await assertAndRecordPhaseSale(c, pricing.activePhase.id, qty); + } + + const totalAmountPaise = pricing.finalPaise; const bookingRef = generateBookingRef(); const holdExpiresAt = new Date(Date.now() + DIRECT_UPI_HOLD_MINUTES * 60 * 1000); @@ -175,8 +226,9 @@ export async function createDirectUpiBooking({ `INSERT INTO bookings ( event_id, user_id, ticket_type_id, quantity, admit_count, amount_paise, status, payment_mode, direct_upi_status, booking_ref, hold_expires_at, - answers, pickup_point_id, created_at, updated_at - ) VALUES ($1, $2, $3, $4, $5, $6, 'pending_payment', 'direct_upi', 'awaiting_payment', $7, $8, $9, $10, now(), now()) + answers, pickup_point_id, section_id, phase_id, offer_id, discount_paise, + created_at, updated_at + ) VALUES ($1, $2, $3, $4, $5, $6, 'pending_payment', 'direct_upi', 'awaiting_payment', $7, $8, $9, $10, $11, $12, $13, $14, now(), now()) RETURNING *`, [ event.id, @@ -188,10 +240,32 @@ export async function createDirectUpiBooking({ bookingRef, holdExpiresAt, JSON.stringify(answers || {}), - pickupPointId || null + pickupPointId || null, + pricing.section ? pricing.section.id : null, + pricing.activePhase ? pricing.activePhase.id : null, + pricing.appliedOffer ? pricing.appliedOffer.id : null, + pricing.discountPaise ] )).rows[0]; + // Record offer redemption if applicable + if (pricing.appliedOffer) { + await recordOfferRedemption(c, { + offerId: pricing.appliedOffer.id, + eventId: event.id, + bookingId: booking.id, + userId: user.id, + discountPaise: pricing.discountPaise + }); + } + + // Save immutable booking price snapshot + await createBookingPriceSnapshot(c, { + bookingId: booking.id, + eventId: event.id, + pricing + }); + // 7. Audit log initial booking creation await c.query( `INSERT INTO direct_upi_payment_audits ( @@ -203,18 +277,25 @@ export async function createDirectUpiBooking({ event.id, user.id, totalAmountPaise, - JSON.stringify({ bookingRef, organiserUpiId: event.organiser_upi_id, qty, tierId: tier.id }) + JSON.stringify({ + bookingRef, + organiserUpiId: event.organiser_upi_id, + qty, + tierId: tier.id, + discountPaise: pricing.discountPaise, + breakdown: pricing.breakdown + }) ] ); - return formatDirectUpiOrder(booking, event, tier); + return formatDirectUpiOrder(booking, event, tier, pricing.breakdown); }); } /** * Format order response with safe UPI intent link and dynamic QR. */ -export function formatDirectUpiOrder(booking, event, tier) { +export function formatDirectUpiOrder(booking, event, tier, breakdown = null) { const amountPaise = Number(booking.amount_paise); const amountRupees = (amountPaise / 100).toFixed(2); const bookingRef = booking.booking_ref || `NLZ-${booking.id.slice(0, 8).toUpperCase()}`; @@ -250,10 +331,16 @@ export function formatDirectUpiOrder(booking, event, tier) { organiserPayeeName: event.organiser_payee_name, paymentInstructions: event.payment_instructions || null, upiIntentUrl, - appIntents, qrSvg, - utrReference: booking.utr_reference || null, + appIntents, + holdExpiresAt: booking.hold_expires_at, expiresAt: booking.hold_expires_at ? new Date(booking.hold_expires_at).toISOString() : null, + pricing: breakdown || (booking.discount_paise ? { + subtotalPaise: amountPaise + Number(booking.discount_paise), + discountPaise: Number(booking.discount_paise), + finalPayablePaise: amountPaise + } : null), + utrReference: booking.utr_reference || null, disclaimer: "Your payment goes directly to the event organiser's UPI account. NIGHTLIFEZ does not collect or hold this ticket payment. Your ticket will be confirmed after the organiser verifies receipt." }; } @@ -474,6 +561,21 @@ export async function rejectDirectUpiPayment(user, eventId, bookingId, { reason [cleanReason, newStatus, bookingId] ); + // Release phase ticket quota and offer redemption if applicable + if (booking.phase_id) { + await c.query( + `UPDATE event_sales_phases SET tickets_sold = GREATEST(0, tickets_sold - $2), updated_at = now() WHERE id = $1`, + [booking.phase_id, booking.quantity] + ); + } + if (booking.offer_id) { + await c.query( + `UPDATE event_offers SET redemption_count = GREATEST(0, redemption_count - 1), updated_at = now() WHERE id = $1`, + [booking.offer_id] + ); + await c.query(`DELETE FROM offer_redemptions WHERE booking_id = $1`, [booking.id]); + } + // Audit trail await c.query( `INSERT INTO direct_upi_payment_audits ( diff --git a/lib/services/event-facilities.js b/lib/services/event-facilities.js new file mode 100644 index 0000000..9cf2f2f --- /dev/null +++ b/lib/services/event-facilities.js @@ -0,0 +1,112 @@ +// lib/services/event-facilities.js - Event Facilities & Amenities Module. +// Configurable predefined & custom amenities for organiser events. + +import { db } from '../db.js'; + +export const FACILITY_CATEGORIES = { + parking: { label: 'Parking', icon: 'car' }, + food_beverage: { label: 'Food & Beverages', icon: 'utensils' }, + accessibility: { label: 'Accessibility', icon: 'wheelchair' }, + medical_safety: { label: 'Medical & Safety', icon: 'shield-plus' }, + other: { label: 'Other Facilities & Rules', icon: 'info' }, + custom: { label: 'Custom Facilities', icon: 'star' } +}; + +export const PREDEFINED_FACILITIES = [ + // PARKING + { category: 'parking', key: 'paid_parking', name: 'Paid parking available', icon: 'parking' }, + { category: 'parking', key: 'free_parking', name: 'Free parking available', icon: 'parking' }, + { category: 'parking', key: 'two_wheeler_parking', name: 'Two-wheeler parking', icon: 'bike' }, + { category: 'parking', key: 'four_wheeler_parking', name: 'Four-wheeler parking', icon: 'car' }, + { category: 'parking', key: 'valet_parking', name: 'Valet parking', icon: 'key' }, + + // FOOD & BEVERAGES + { category: 'food_beverage', key: 'food_available', name: 'Food available', icon: 'utensils' }, + { category: 'food_beverage', key: 'veg_options', name: 'Vegetarian options', icon: 'leaf' }, + { category: 'food_beverage', key: 'non_veg_options', name: 'Non-vegetarian options', icon: 'drumstick' }, + { category: 'food_beverage', key: 'alcohol_available', name: 'Alcohol available (21+ only, legally permitted)', icon: 'glass' }, + { category: 'food_beverage', key: 'non_alcoholic', name: 'Non-alcoholic beverages', icon: 'cup' }, + { category: 'food_beverage', key: 'outside_food_restrictions', name: 'Outside food restrictions', icon: 'ban' }, + + // ACCESSIBILITY + { category: 'accessibility', key: 'wheelchair_accessible', name: 'Wheelchair accessible', icon: 'wheelchair' }, + { category: 'accessibility', key: 'accessible_entrance', name: 'Accessible entrance', icon: 'door-open' }, + { category: 'accessibility', key: 'accessible_washrooms', name: 'Accessible washrooms', icon: 'bath' }, + { category: 'accessibility', key: 'companion_assistance', name: 'Companion assistance', icon: 'hands-helping' }, + { category: 'accessibility', key: 'accessible_parking', name: 'Accessible parking', icon: 'parking-accessible' }, + + // MEDICAL & SAFETY + { category: 'medical_safety', key: 'first_aid', name: 'First-aid support', icon: 'first-aid' }, + { category: 'medical_safety', key: 'medical_staff', name: 'Medical staff on site', icon: 'user-md' }, + { category: 'medical_safety', key: 'ambulance', name: 'Ambulance availability', icon: 'ambulance' }, + { category: 'medical_safety', key: 'security_personnel', name: 'Security personnel', icon: 'shield' }, + { category: 'medical_safety', key: 'emergency_assistance', name: 'Emergency assistance', icon: 'bell' }, + + // OTHER + { category: 'other', key: 'common_washrooms', name: 'Common washrooms', icon: 'restroom' }, + { category: 'other', key: 'smoking_zones', name: 'Designated smoking zones', icon: 'smoking' }, + { category: 'other', key: 'cloakroom', name: 'Cloakroom & baggage storage', icon: 'box' }, + { category: 'other', key: 'photography_rules', name: 'Photography allowed / rules apply', icon: 'camera' }, + { category: 'other', key: 're_entry_policy', name: 'Re-entry policy', icon: 'door' }, + { category: 'other', key: 'age_restrictions', name: 'Age restrictions (21+ only)', icon: 'id-card' }, + { category: 'other', key: 'dress_code', name: 'Dress code applicable', icon: 'tshirt' }, + { category: 'other', key: 'pet_policy', name: 'Pet friendly / Pet restrictions', icon: 'paw' } +]; + +export async function saveEventFacilities(c, eventId, facilities = []) { + await c.query(`DELETE FROM event_facilities WHERE event_id = $1`, [eventId]); + if (!Array.isArray(facilities) || facilities.length === 0) { + await c.query(`UPDATE events SET has_facilities = false WHERE id = $1`, [eventId]); + return []; + } + + const valid = []; + for (let i = 0; i < facilities.length; i++) { + const f = facilities[i]; + const name = String(f.name || '').trim(); + if (!name) continue; + const cat = FACILITY_CATEGORIES[f.category] ? f.category : 'custom'; + const key = String(f.facilityKey || f.key || `custom_${i}`).trim(); + const desc = f.description ? String(f.description).trim().slice(0, 500) : null; + const icon = f.icon ? String(f.icon).trim().slice(0, 50) : null; + const isCustom = Boolean(f.isCustom || cat === 'custom'); + + const res = await c.query( + `INSERT INTO event_facilities (event_id, category, facility_key, name, description, icon, is_custom, sort_order) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *`, + [eventId, cat, key, name, desc, icon, isCustom, i] + ); + valid.push(res.rows[0]); + } + + await c.query(`UPDATE events SET has_facilities = $2 WHERE id = $1`, [eventId, valid.length > 0]); + return valid; +} + +export async function getEventFacilities(first, second = db) { + const c = (first && typeof first.query === 'function') ? first : second; + const eventId = (first && typeof first.query === 'function') ? second : first; + + const { rows } = await c.query( + `SELECT * FROM event_facilities WHERE event_id = $1 ORDER BY sort_order ASC, created_at ASC`, + [eventId] + ); + return rows; +} + +export function groupFacilitiesByCategory(facilities = []) { + const groups = {}; + for (const f of facilities) { + const cat = f.category || 'other'; + if (!groups[cat]) { + groups[cat] = { + category: cat, + label: FACILITY_CATEGORIES[cat]?.label || 'Other Facilities', + icon: FACILITY_CATEGORIES[cat]?.icon || 'info', + items: [] + }; + } + groups[cat].items.push(f); + } + return Object.values(groups); +} diff --git a/lib/services/event-offers.js b/lib/services/event-offers.js new file mode 100644 index 0000000..e3ce755 --- /dev/null +++ b/lib/services/event-offers.js @@ -0,0 +1,274 @@ +// lib/services/event-offers.js - Offers & Discount Engine Module. +// Server-side discount calculation, promo code verification, redemption tracking & limits. + +import { db } from '../db.js'; +import { HttpError } from '../http.js'; + +export async function saveEventOffers(c, eventId, offers = []) { + await c.query(`DELETE FROM event_offers WHERE event_id = $1`, [eventId]); + if (!Array.isArray(offers) || offers.length === 0) { + await c.query(`UPDATE events SET has_offers = false WHERE id = $1`, [eventId]); + return []; + } + + const valid = []; + for (let i = 0; i < offers.length; i++) { + const o = offers[i]; + const name = String(o.name || '').trim(); + if (!name) continue; + const desc = o.description ? String(o.description).trim().slice(0, 500) : null; + const code = o.code ? String(o.code).trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 30) : null; + const type = o.discountType === 'fixed_amount' ? 'fixed_amount' : 'percentage'; + const value = parseInt(o.discountValue, 10); + if (!value || value <= 0) continue; + + const maxDiscountPaise = o.maxDiscountPaise ? parseInt(o.maxDiscountPaise, 10) : null; + const minOrderPaise = o.minOrderPaise ? Math.max(0, parseInt(o.minOrderPaise, 10)) : 0; + const minQuantity = o.minQuantity ? Math.max(1, parseInt(o.minQuantity, 10)) : 1; + const tierIds = Array.isArray(o.applicableTierIds) ? o.applicableTierIds.filter(Boolean) : []; + const phaseIds = Array.isArray(o.applicablePhaseIds) ? o.applicablePhaseIds.filter(Boolean) : []; + const startsAt = o.startsAt ? new Date(o.startsAt) : null; + const expiresAt = o.expiresAt ? new Date(o.expiresAt) : null; + const totalLimit = o.totalLimit ? parseInt(o.totalLimit, 10) : null; + const perUserLimit = o.perUserLimit ? parseInt(o.perUserLimit, 10) : 1; + const active = o.active !== false; + + const res = await c.query( + `INSERT INTO event_offers ( + event_id, name, description, code, discount_type, discount_value, max_discount_paise, + min_order_paise, min_quantity, applicable_tier_ids, applicable_phase_ids, + starts_at, expires_at, total_limit, per_user_limit, active + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) + RETURNING *`, + [ + eventId, name, desc, code || null, type, value, maxDiscountPaise, + minOrderPaise, minQuantity, tierIds, phaseIds, + startsAt, expiresAt, totalLimit, perUserLimit, active + ] + ); + valid.push(res.rows[0]); + } + + await c.query(`UPDATE events SET has_offers = $2 WHERE id = $1`, [eventId, valid.length > 0]); + return valid; +} + +export async function getEventOffers(eventId, c = db) { + const { rows } = await c.query( + `SELECT * FROM event_offers WHERE event_id = $1 ORDER BY created_at ASC`, + [eventId] + ); + return rows; +} + +/** + * Validates and calculates discount on the server side using integer paise. + */ +export async function evaluateOffer({ + c = db, + eventId, + offerId = null, + promoCode = null, + ticketSubtotalPaise = 0, + quantity = 1, + tierId = null, + phaseId = null, + userId = null, + now = new Date() +}) { + if (!offerId && !promoCode) { + return { valid: false, reason: 'no_offer_specified' }; + } + + let offer; + if (offerId) { + offer = (await c.query( + `SELECT * FROM event_offers WHERE id = $1 AND event_id = $2 FOR UPDATE`, + [offerId, eventId] + )).rows[0]; + } else if (promoCode) { + const cleanCode = String(promoCode).trim().toUpperCase(); + offer = (await c.query( + `SELECT * FROM event_offers WHERE event_id = $1 AND code = $2 FOR UPDATE`, + [eventId, cleanCode] + )).rows[0]; + } + + if (!offer) { + return { valid: false, reason: 'Offer or promo code not found.' }; + } + + if (!offer.active) { + return { valid: false, reason: 'This promotional offer is no longer active.' }; + } + + if (offer.starts_at && new Date(offer.starts_at) > now) { + return { valid: false, reason: 'This promotional offer has not started yet.' }; + } + + if (offer.expires_at && new Date(offer.expires_at) < now) { + return { valid: false, reason: 'This promotional offer has expired.' }; + } + + if (offer.min_quantity && quantity < offer.min_quantity) { + return { + valid: false, + reason: `Requires a minimum of ${offer.min_quantity} tickets (current: ${quantity}).` + }; + } + + if (offer.min_order_paise && ticketSubtotalPaise < offer.min_order_paise) { + const minRs = Math.ceil(offer.min_order_paise / 100); + return { + valid: false, + reason: `Requires a minimum order value of ₹${minRs}.` + }; + } + + if (Array.isArray(offer.applicable_tier_ids) && offer.applicable_tier_ids.length > 0) { + if (!tierId || !offer.applicable_tier_ids.includes(tierId)) { + return { valid: false, reason: 'This offer is not applicable to the selected ticket type.' }; + } + } + + if (Array.isArray(offer.applicable_phase_ids) && offer.applicable_phase_ids.length > 0) { + if (!phaseId || !offer.applicable_phase_ids.includes(phaseId)) { + return { valid: false, reason: 'This offer is not applicable to the current sales phase.' }; + } + } + + if (offer.total_limit != null && offer.redemption_count >= offer.total_limit) { + return { valid: false, reason: 'This offer has reached its maximum total redemptions.' }; + } + + if (userId && offer.per_user_limit) { + const userRedemptions = (await c.query( + `SELECT COUNT(*)::int as count FROM offer_redemptions WHERE offer_id = $1 AND user_id = $2`, + [offer.id, userId] + )).rows[0]?.count || 0; + + if (userRedemptions >= offer.per_user_limit) { + return { valid: false, reason: 'You have already redeemed this offer the maximum allowed number of times.' }; + } + } + + // Calculate discount in paise + let discountPaise = 0; + if (offer.discount_type === 'percentage') { + discountPaise = Math.floor((ticketSubtotalPaise * offer.discount_value) / 100); + if (offer.max_discount_paise && discountPaise > offer.max_discount_paise) { + discountPaise = offer.max_discount_paise; + } + } else if (offer.discount_type === 'fixed_amount') { + discountPaise = offer.discount_value; + } + + // Never allow discount to exceed eligible ticket subtotal + discountPaise = Math.max(0, Math.min(discountPaise, ticketSubtotalPaise)); + + return { + valid: true, + offer, + discountPaise, + finalAmountPaise: ticketSubtotalPaise - discountPaise, + finalPayablePaise: ticketSubtotalPaise - discountPaise + }; +} + +/** + * Pure calculation helper for offer discounts using integer paise. + */ +export function calculateDiscountPaise(offer, { ticketSubtotalPaise = 0, quantity = 1 } = {}) { + const minQty = offer.min_quantity ?? offer.minQuantity ?? 1; + if (minQty && quantity < minQty) { + return { valid: false, reason: `Minimum of ${minQty} tickets required.` }; + } + const minOrder = offer.min_order_paise ?? offer.minOrderPaise; + if (minOrder && ticketSubtotalPaise < minOrder) { + return { valid: false, reason: `Minimum order value of ₹${Math.ceil(minOrder / 100)} required.` }; + } + let discountPaise = 0; + const dType = offer.discount_type || offer.discountType; + const dVal = offer.discount_value ?? offer.discountValue ?? 0; + const maxCap = offer.max_discount_paise ?? offer.maxDiscountPaise; + if (dType === 'percentage') { + discountPaise = Math.floor((ticketSubtotalPaise * dVal) / 100); + if (maxCap && discountPaise > maxCap) { + discountPaise = maxCap; + } + } else if (dType === 'fixed_amount') { + discountPaise = dVal; + } + discountPaise = Math.max(0, Math.min(discountPaise, ticketSubtotalPaise)); + return { + valid: true, + discountPaise, + finalAmountPaise: ticketSubtotalPaise - discountPaise, + finalPayablePaise: ticketSubtotalPaise - discountPaise + }; +} + +/** + * Record redemption transactionally upon booking creation or confirmation. + */ +export async function recordOfferRedemption(c, { offerId, eventId, bookingId, userId, discountPaise }) { + if (!offerId || !bookingId) return null; + + // Insert redemption record + const row = (await c.query( + `INSERT INTO offer_redemptions (offer_id, event_id, booking_id, user_id, discount_paise) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (offer_id, booking_id) DO NOTHING + RETURNING *`, + [offerId, eventId, bookingId, userId, discountPaise] + )).rows[0]; + + if (row) { + // Atomically increment redemption count on offer + await c.query( + `UPDATE event_offers SET redemption_count = redemption_count + 1, updated_at = now() WHERE id = $1`, + [offerId] + ); + } + return row; +} + +/** + * Organiser reporting on offers usage. + */ +export async function getOrganiserOffersReport(first, second = db) { + const c = (first && typeof first.query === 'function') ? first : second; + const eventId = (first && typeof first.query === 'function') ? second : first; + + const { rows } = await c.query( + `SELECT o.id, o.name, o.code, o.discount_type, o.discount_value, o.total_limit, o.redemption_count, + COALESCE(SUM(r.discount_paise), 0)::bigint as total_discount_given_paise, + COALESCE(SUM(b.amount_paise), 0)::bigint as total_net_revenue_paise, + COUNT(r.id)::int as actual_redemption_count + FROM event_offers o + LEFT JOIN offer_redemptions r ON r.offer_id = o.id + LEFT JOIN bookings b ON b.id = r.booking_id + WHERE o.event_id = $1 + GROUP BY o.id + ORDER BY o.created_at ASC`, + [eventId] + ); + return rows.map((r) => ({ + id: r.id, + name: r.name, + code: r.code, + discountType: r.discount_type, + discountValue: r.discount_value, + totalLimit: r.total_limit, + redemptionCount: r.redemption_count, + actualRedemptionCount: r.actual_redemption_count, + remainingCapacity: r.total_limit ? Math.max(0, r.total_limit - r.redemption_count) : null, + totalDiscountPaise: Number(r.total_discount_given_paise), + total_discount_paise: Number(r.total_discount_given_paise), + netRevenuePaise: Number(r.total_net_revenue_paise), + net_revenue_paise: Number(r.total_net_revenue_paise), + total_redemptions: r.redemption_count, + totalRedemptions: r.redemption_count, + totalDiscountGivenPaise: parseInt(r.total_discount_given_paise, 10) || 0 + })); +} diff --git a/lib/services/event-venue.js b/lib/services/event-venue.js new file mode 100644 index 0000000..45cdc62 --- /dev/null +++ b/lib/services/event-venue.js @@ -0,0 +1,157 @@ +// lib/services/event-venue.js - Interactive Venue Layout & Section-Based Ticketing Module. +// Visual venue diagram, section-based capacity, coordinates & section pricing. + +import { db } from '../db.js'; +import { HttpError } from '../http.js'; + +export const SECTION_PRESETS = { + stage: { name: 'Stage', color: '#1f2937', category: 'stage', shape: 'rect' }, + general: { name: 'General Admission / Standing', color: '#3b82f6', category: 'general', shape: 'rect' }, + silver: { name: 'Silver Section', color: '#94a3b8', category: 'silver', shape: 'rect' }, + gold: { name: 'Gold Section', color: '#eab308', category: 'gold', shape: 'rect' }, + platinum: { name: 'Platinum Section', color: '#06b6d4', category: 'platinum', shape: 'rect' }, + fanpit: { name: 'Fanpit', color: '#ec4899', category: 'fanpit', shape: 'rect' }, + vip: { name: 'VIP Lounge', color: '#a855f7', category: 'vip', shape: 'rect' }, + backstage: { name: 'Backstage Pass', color: '#f97316', category: 'backstage', shape: 'rect' }, + custom: { name: 'Custom Section', color: '#10b981', category: 'custom', shape: 'rect' } +}; + +export async function saveEventVenueLayout(c, eventId, layoutConfig = {}, sections = [], tierMapping = {}) { + await c.query(`DELETE FROM event_venue_layouts WHERE event_id = $1`, [eventId]); + + const layoutType = layoutConfig.layoutType || (sections.length > 0 ? 'section_based' : 'none'); + if (layoutType === 'none' || !sections || sections.length === 0) { + await c.query(`UPDATE events SET has_venue_layout = false WHERE id = $1`, [eventId]); + return null; + } + + const canvasWidth = parseInt(layoutConfig.canvasWidth, 10) || 800; + const canvasHeight = parseInt(layoutConfig.canvasHeight, 10) || 500; + + const layoutRow = (await c.query( + `INSERT INTO event_venue_layouts (event_id, layout_type, canvas_width, canvas_height, config) + VALUES ($1, $2, $3, $4, $5) RETURNING *`, + [eventId, layoutType, canvasWidth, canvasHeight, JSON.stringify(layoutConfig.config || {})] + )).rows[0]; + + const savedSections = []; + for (let i = 0; i < sections.length; i++) { + const s = sections[i]; + const sectionKey = String(s.sectionKey || s.key || `sec_${i}`).trim(); + const name = String(s.name || `Section ${i + 1}`).trim(); + const category = s.category || 'custom'; + const color = s.color || SECTION_PRESETS[category]?.color || '#6366f1'; + const shape = s.shape || 'rect'; + const x = parseInt(s.x, 10) || 0; + const y = parseInt(s.y, 10) || 0; + const width = parseInt(s.width, 10) || 120; + const height = parseInt(s.height, 10) || 80; + const capacity = Math.max(0, parseInt(s.capacity, 10) || 100); + const pricePaise = Math.max(0, parseInt(s.pricePaise, 10) || 0); + const minPerBooking = Math.max(1, parseInt(s.minPerBooking, 10) || 1); + const maxPerBooking = Math.max(minPerBooking, parseInt(s.maxPerBooking, 10) || 10); + const status = s.status === 'unavailable' ? 'unavailable' : (s.status === 'sold_out' ? 'sold_out' : 'available'); + const ticketTypeId = tierMapping[sectionKey] || s.ticketTypeId || null; + + const secRow = (await c.query( + `INSERT INTO event_venue_sections ( + layout_id, event_id, ticket_type_id, section_key, name, category, color, shape, + x, y, width, height, capacity, price_paise, min_per_booking, max_per_booking, + status, sort_order, metadata + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19) + RETURNING *`, + [ + layoutRow.id, eventId, ticketTypeId, sectionKey, name, category, color, shape, + x, y, width, height, capacity, pricePaise, minPerBooking, maxPerBooking, + status, i, JSON.stringify(s.metadata || {}) + ] + )).rows[0]; + savedSections.push(secRow); + } + + await c.query(`UPDATE events SET has_venue_layout = true WHERE id = $1`, [eventId]); + return { ...layoutRow, sections: savedSections }; +} + +export async function getEventVenueLayout(first, second = db) { + const c = (first && typeof first.query === 'function') ? first : second; + const eventId = (first && typeof first.query === 'function') ? second : first; + + const layout = (await c.query( + `SELECT * FROM event_venue_layouts WHERE event_id = $1`, + [eventId] + )).rows[0]; + + if (!layout) return null; + + // Fetch sections with calculated sold seats + const { rows: sections } = await c.query( + `SELECT s.*, + COALESCE(( + SELECT SUM(b.quantity)::int + FROM bookings b + WHERE b.section_id = s.id + AND b.status IN ('pending_payment', 'confirmed', 'checked_in') + AND (b.status != 'pending_payment' OR b.hold_expires_at > now()) + ), 0) as seats_taken + FROM event_venue_sections s + WHERE s.layout_id = $1 + ORDER BY s.sort_order ASC, s.created_at ASC`, + [layout.id] + ); + + const formattedSections = sections.map((sec) => { + const taken = sec.seats_taken || 0; + const remaining = Math.max(0, sec.capacity - taken); + const isSoldOut = sec.capacity > 0 && remaining <= 0; + const effectiveStatus = sec.status === 'unavailable' ? 'unavailable' : (isSoldOut ? 'sold_out' : 'available'); + return { + ...sec, + seatsTaken: taken, + remainingSeats: remaining, + effectiveStatus + }; + }); + + return { + ...layout, + layoutType: layout.layout_type, + sections: formattedSections + }; +} + +/** + * Validates section availability and reserves inventory with row locks. + */ +export async function assertSectionInventory(c, sectionId, quantity) { + if (!sectionId) return null; + const sec = (await c.query( + `SELECT * FROM event_venue_sections WHERE (id::text = $1 OR section_key = $1) FOR UPDATE`, + [String(sectionId)] + )).rows[0]; + + if (!sec) throw new HttpError(404, 'section_not_found', 'Venue section not found.'); + if (sec.status === 'unavailable' || sec.status === 'sold_out') { + throw new HttpError(409, 'section_sold_out', `${sec.name} is ${sec.status === 'sold_out' ? 'sold out' : 'currently unavailable'}.`); + } + + const taken = (await c.query( + `SELECT COALESCE(SUM(quantity), 0)::int as count + FROM bookings + WHERE section_id = $1 + AND status IN ('pending_payment', 'confirmed', 'checked_in') + AND (status != 'pending_payment' OR hold_expires_at > now())`, + [sectionId] + )).rows[0]?.count || 0; + + if (sec.capacity - taken < quantity) { + const left = Math.max(0, sec.capacity - taken); + throw new HttpError( + 409, + 'section_sold_out', + left > 0 ? `Only ${left} seat(s) remaining in ${sec.name}.` : `${sec.name} is sold out.` + ); + } + + return sec; +} diff --git a/lib/services/events.js b/lib/services/events.js index 6d95946..4dff3fd 100644 --- a/lib/services/events.js +++ b/lib/services/events.js @@ -250,6 +250,14 @@ export function toPublicEvent(row, { checkout = checkoutForEvent(row) } = {}) { organiserUpiId: row.organiser_upi_id || null, organiserPayeeName: row.organiser_payee_name || null, paymentInstructions: row.payment_instructions || null, + facilities: list(row.facilities), + offers: list(row.offers), + salesPhases: list(row.sales_phases), + venueLayout: row.venue_layout && row.venue_layout.id ? row.venue_layout : null, + hasFacilities: Boolean(row.has_facilities || (row.facilities && row.facilities.length > 0)), + hasOffers: Boolean(row.has_offers || (row.offers && row.offers.length > 0)), + hasSalesPhases: Boolean(row.has_sales_phases || (row.sales_phases && row.sales_phases.length > 0)), + hasVenueLayout: Boolean(row.has_venue_layout || (row.venue_layout && row.venue_layout.id && row.venue_layout.sections && row.venue_layout.sections.length > 0)), inclusions: arr(row.inclusions), exclusions: arr(row.exclusions), refundPolicy: row.refund_policy || '', @@ -289,7 +297,29 @@ const PUBLIC_SELECT = ` SELECT e.*, (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 + ${TIERS_SQL} AS tiers, + (SELECT COALESCE(json_agg(json_build_object( + 'id', f.id, 'category', f.category, 'facilityKey', f.facility_key, 'name', f.name, + 'description', f.description, 'icon', f.icon, 'isCustom', f.is_custom, 'sortOrder', f.sort_order + ) ORDER BY f.sort_order), '[]'::json) FROM event_facilities f WHERE f.event_id = e.id) AS facilities, + (SELECT COALESCE(json_agg(json_build_object( + 'id', o.id, 'name', o.name, 'description', o.description, 'code', o.code, + 'discountType', o.discount_type, 'discountValue', o.discount_value, 'maxDiscountPaise', o.max_discount_paise, + 'minOrderPaise', o.min_order_paise, 'minQuantity', o.min_quantity, 'startsAt', o.starts_at, 'expiresAt', o.expires_at + ) ORDER BY o.created_at), '[]'::json) FROM event_offers o WHERE o.event_id = e.id AND o.active) AS offers, + (SELECT COALESCE(json_agg(json_build_object( + 'id', p.id, 'name', p.name, 'startsAt', p.starts_at, 'endsAt', p.ends_at, 'timezone', p.timezone, + 'pricePaise', p.price_paise, 'quota', p.quota, 'ticketsSold', p.tickets_sold, 'maxPerBooking', p.max_per_booking + ) ORDER BY p.sort_order, p.starts_at), '[]'::json) FROM event_sales_phases p WHERE p.event_id = e.id AND p.is_active) AS sales_phases, + (SELECT json_build_object( + 'id', vl.id, 'layoutType', vl.layout_type, 'canvasWidth', vl.canvas_width, 'canvasHeight', vl.canvas_height, + 'sections', COALESCE((SELECT json_agg(json_build_object( + 'id', vs.id, 'sectionKey', vs.section_key, 'name', vs.name, 'category', vs.category, + 'color', vs.color, 'shape', vs.shape, 'x', vs.x, 'y', vs.y, 'width', vs.width, 'height', vs.height, + 'capacity', vs.capacity, 'pricePaise', vs.price_paise, 'status', vs.status, + 'seatsTaken', COALESCE((SELECT SUM(b.quantity)::int FROM bookings b WHERE b.section_id = vs.id AND b.status IN ('pending_payment', 'confirmed', 'checked_in') AND (b.status != 'pending_payment' OR b.hold_expires_at > now())), 0) + ) ORDER BY vs.sort_order) FROM event_venue_sections vs WHERE vs.layout_id = vl.id), '[]'::json) + ) FROM event_venue_layouts vl WHERE vl.event_id = e.id) AS venue_layout FROM events e`; const PUBLIC_EVENT_CACHE = new Map(); diff --git a/lib/services/organiser.js b/lib/services/organiser.js index dd206d0..7eb0b41 100644 --- a/lib/services/organiser.js +++ b/lib/services/organiser.js @@ -19,6 +19,10 @@ import { CancellationPolicyDraft, POLICY_TEMPLATES, resolveCancellationPolicy } import { EventScheduleDraft, normalizeSchedule, deriveEventBounds } from './event-schedule.js'; import { reverseBookingFeeEntry } from './finance.js'; import { validateUpiId, validatePayeeName, UPI_REGEX } from './payment-settings.js'; +import { saveEventFacilities, PREDEFINED_FACILITIES, FACILITY_CATEGORIES } from './event-facilities.js'; +import { saveEventOffers } from './event-offers.js'; +import { saveEventVenueLayout, SECTION_PRESETS } from './event-venue.js'; +import { saveEventSalesPhases } from './sales-phases.js'; export const MAX_IMAGES = 5; export const MAX_TIERS = 10; @@ -137,13 +141,73 @@ export const DraftData = z.object({ imageIds: z.array(z.string().uuid().or(z.literal(''))).max(MAX_IMAGES).optional().transform((arr) => arr ? arr.filter(Boolean) : undefined), imageRightsConfirmed: flag, paymentMethod: z.enum(['free', 'direct_upi']).optional(), - organiserUpiId: z.string().max(256).optional(), - organiserPayeeName: z.string().max(100).optional(), - paymentInstructions: z.string().max(1000).optional(), + organiserUpiId: z.string().max(256).nullable().optional(), + organiserPayeeName: z.string().max(100).nullable().optional(), + paymentInstructions: z.string().max(1000).nullable().optional(), refundPolicy: text(1000).optional(), cancellationPolicy: CancellationPolicyDraft.optional(), schedule: EventScheduleDraft.optional(), tickets: z.array(TicketDraft).max(MAX_TIERS).optional(), + facilities: z.array(z.object({ + category: z.string().max(40), + facilityKey: z.string().max(80).optional(), + name: z.string().max(100), + description: text(500), + icon: text(50), + isCustom: flag + }).passthrough()).max(60).optional(), + offers: z.array(z.object({ + name: z.string().max(80), + description: text(500), + code: text(30), + discountType: z.enum(['percentage', 'fixed_amount']), + discountValue: z.coerce.number().int(), + maxDiscountPaise: looseInt, + minOrderPaise: looseInt, + minQuantity: looseInt, + applicableTierIds: z.array(z.string()).optional(), + startsAt: text(40), + expiresAt: text(40), + totalLimit: looseInt, + perUserLimit: looseInt, + active: flag + }).passthrough()).max(20).optional(), + venueLayout: z.object({ + layoutType: z.enum(['none', 'section_based', 'reserved_seating']).optional(), + canvasWidth: looseInt, + canvasHeight: looseInt, + sections: z.array(z.object({ + sectionKey: z.string().max(60), + name: z.string().max(80), + category: z.string().max(40).optional(), + color: text(20), + shape: text(20), + x: looseInt, + y: looseInt, + width: looseInt, + height: looseInt, + capacity: looseInt, + pricePaise: looseInt, + minPerBooking: looseInt, + maxPerBooking: looseInt, + status: z.string().optional() + }).passthrough()).max(30).optional() + }).passthrough().optional(), + salesTimeline: z.object({ + enabled: flag, + phases: z.array(z.object({ + name: z.string().max(80), + startsAt: text(40), + endsAt: text(40), + timezone: text(40), + pricePaise: looseInt, + quota: looseInt, + maxPerBooking: looseInt, + applicableTierIds: z.array(z.string()).optional(), + accessCode: text(30), + isActive: flag + }).passthrough()).max(10).optional() + }).passthrough().optional(), features: FeaturesDraft.optional() }).passthrough(); @@ -173,6 +237,10 @@ export function initialDraftData(templateKey) { }, refundPolicy: POLICY_TEMPLATES.standard.summary, tickets: (t.tickets || []).map((k) => ({ id: rid(), ...TICKET_PRESETS[k] })), + facilities: [], + offers: [], + venueLayout: { layoutType: 'none', sections: [] }, + salesTimeline: { enabled: false, phases: [] }, features: { questions: { enabled: Boolean(f.questions), items: (f.questions || []).map((k) => ({ id: rid(), ...strip(QUESTION_PRESETS[k]) })) }, approval: { enabled: Boolean(f.approval) }, @@ -441,6 +509,49 @@ export function publishIssues(d, { checkout = ticketCheckoutStatus(), now = new if (f.balance?.enabled && !tickets.some((t) => clean(t.eligibility))) { err('features', 'features.balance.enabled', 'Crowd balance is on: say who each restricted ticket is for (Tickets step), or switch it off.'); } + + // Facilities + if (Array.isArray(d.facilities) && d.facilities.length > 0) { + d.facilities.forEach((fac, idx) => { + if (!clean(fac.name)) { + err('facilities', `facilities.${idx}.name`, `Facility ${idx + 1}: Name is required.`); + } + }); + } + + // Offers + if (Array.isArray(d.offers) && d.offers.length > 0) { + d.offers.forEach((o, idx) => { + if (!clean(o.name)) err('offers', `offers.${idx}.name`, `Offer ${idx + 1}: Offer name is required.`); + if (!o.discountValue || o.discountValue <= 0) { + err('offers', `offers.${idx}.discountValue`, `${clean(o.name) || 'Offer'}: Discount value must be greater than 0.`); + } + if (o.discountType === 'percentage' && o.discountValue > 100) { + err('offers', `offers.${idx}.discountValue`, `${clean(o.name) || 'Offer'}: Percentage discount cannot exceed 100%.`); + } + }); + } + + // Venue layout + if (d.venueLayout && d.venueLayout.layoutType === 'section_based') { + const secs = d.venueLayout.sections || []; + if (!secs.length) { + err('venue', 'venueLayout.sections', 'Section-based venue layout selected: add at least one section or switch to General Admission.'); + } + secs.forEach((s, idx) => { + if (!clean(s.name)) err('venue', `venueLayout.sections.${idx}.name`, `Section ${idx + 1}: Section name is required.`); + }); + } + + // Sales timeline + if (d.salesTimeline?.enabled && Array.isArray(d.salesTimeline.phases)) { + d.salesTimeline.phases.forEach((p, idx) => { + if (!clean(p.name)) err('timeline', `salesTimeline.phases.${idx}.name`, `Phase ${idx + 1}: Phase name is required.`); + if (p.startsAt && p.endsAt && new Date(p.endsAt) <= new Date(p.startsAt)) { + err('timeline', `salesTimeline.phases.${idx}.endsAt`, `Phase "${clean(p.name)}": End time must be after start time.`); + } + }); + } return out; } @@ -695,6 +806,14 @@ export function draftToRow(d, { hostFallback = '' } = {}) { booking_questions: f.questions?.enabled ? sanitizeQuestions(f.questions.items) : [], pickup_points: f.pickup?.enabled ? sanitizePickups(f.pickup.points) : [], contact_phone: f.contact?.enabled ? normalizePhone(f.contact.phone) : null, + facilities: d.facilities || [], + offers: d.offers || [], + venue_layout: d.venueLayout || null, + sales_phases: d.salesTimeline?.phases || [], + has_facilities: Boolean(d.facilities && d.facilities.length), + has_offers: Boolean(d.offers && d.offers.length), + has_venue_layout: Boolean(d.venueLayout && d.venueLayout.layoutType === 'section_based'), + has_sales_phases: Boolean(d.salesTimeline?.enabled && d.salesTimeline?.phases?.length), 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, category: t.category || 'general', admit_count: t.admitCount || (t.category === 'couple' ? 2 : t.category === 'group' ? 4 : 1), @@ -908,6 +1027,20 @@ export async function publishDraft(user, draftId, { version, confirm }) { i, category, admitCount, t.salesStartAt ? new Date(t.salesStartAt) : null, t.salesEndAt ? new Date(t.salesEndAt) : null, targetSessionId]); } + + if (Array.isArray(d.facilities) && d.facilities.length > 0) { + await saveEventFacilities(c, ev.id, d.facilities); + } + if (Array.isArray(d.offers) && d.offers.length > 0) { + await saveEventOffers(c, ev.id, d.offers); + } + if (d.salesTimeline?.enabled && Array.isArray(d.salesTimeline.phases) && d.salesTimeline.phases.length > 0) { + await saveEventSalesPhases(c, ev.id, d.salesTimeline.phases); + } + if (d.venueLayout && d.venueLayout.layoutType === 'section_based' && Array.isArray(d.venueLayout.sections) && d.venueLayout.sections.length > 0) { + await saveEventVenueLayout(c, ev.id, d.venueLayout, d.venueLayout.sections); + } + 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]); await c.query( diff --git a/lib/services/pricing-engine.js b/lib/services/pricing-engine.js new file mode 100644 index 0000000..12d413b --- /dev/null +++ b/lib/services/pricing-engine.js @@ -0,0 +1,187 @@ +// lib/services/pricing-engine.js - Unified Pricing Engine. +// Enforces order of operations: Base Tier/Section Price → Sales Phase Override → Offer Discount → Final Payable. +// Never trusts client-side totals. Stores immutable price snapshot. + +import { db } from '../db.js'; +import { HttpError } from '../http.js'; +import { evaluateOffer, recordOfferRedemption } from './event-offers.js'; +import { categorizePhases, assertAndRecordPhaseSale } from './sales-phases.js'; +import { assertSectionInventory } from './event-venue.js'; + +/** + * Calculates authoritative pricing breakdown and returns snapshot data. + */ +export async function calculateBookingPrice({ + c = db, + event, + tier, + sectionId = null, + phaseId = null, + quantity = 1, + promoCode = null, + offerId = null, + userId = null, + accessCode = null, + now = new Date() +}) { + const qty = Math.max(1, parseInt(quantity, 10) || 1); + + // 1. Determine Base Price: Section vs Tier + let basePricePaise = tier.price_paise; + let section = null; + if (sectionId) { + section = await assertSectionInventory(c, sectionId, qty); + if (section && section.price_paise != null) { + basePricePaise = section.price_paise; + } + } + + // 2. Sales Timeline & Scheduled Pricing Phase Resolution + const { rows: phases } = await c.query( + `SELECT * FROM event_sales_phases WHERE event_id = $1 AND is_active ORDER BY sort_order ASC, starts_at ASC`, + [event.id] + ); + + let activePhase = null; + if (phaseId) { + const specificPhase = phases.find((p) => p.id === phaseId || p.name === phaseId); + if (!specificPhase) { + throw new HttpError(404, 'phase_not_found', 'Selected sales phase not found.'); + } + if (specificPhase.access_code && accessCode !== specificPhase.access_code) { + throw new HttpError(400, 'invalid_access_code', 'Valid access code required to unlock this sales phase.'); + } + const currentTime = now.getTime(); + if (new Date(specificPhase.starts_at).getTime() > currentTime) { + throw new HttpError(409, 'phase_not_started', `Sales phase "${specificPhase.name}" has not started yet.`); + } + if (new Date(specificPhase.ends_at).getTime() <= currentTime) { + throw new HttpError(409, 'phase_ended', `Sales phase "${specificPhase.name}" has ended.`); + } + if (specificPhase.quota != null && (specificPhase.tickets_sold + qty > specificPhase.quota)) { + throw new HttpError(409, 'phase_quota_exhausted', `Sales phase "${specificPhase.name}" has reached its ticket quota.`); + } + activePhase = specificPhase; + } else { + const phaseAnalysis = categorizePhases(phases, { now, tierId: tier.id, accessCode }); + activePhase = phaseAnalysis.current; + } + + let effectiveUnitPricePaise = basePricePaise; + if (activePhase && activePhase.price_paise != null) { + effectiveUnitPricePaise = activePhase.price_paise; + } + + const ticketSubtotalPaise = effectiveUnitPricePaise * qty; + + // 3. Offers & Discount Engine Evaluation + let discountPaise = 0; + let appliedOffer = null; + let offerReason = null; + + if (promoCode || offerId) { + const offerRes = await evaluateOffer({ + c, + eventId: event.id, + offerId, + promoCode, + ticketSubtotalPaise, + quantity: qty, + tierId: tier.id, + phaseId: activePhase ? activePhase.id : null, + userId, + now + }); + + if (offerRes.valid) { + discountPaise = offerRes.discountPaise; + appliedOffer = offerRes.offer; + } else { + offerReason = offerRes.reason; + } + } + + const finalPaise = Math.max(0, ticketSubtotalPaise - discountPaise); + + return { + basePricePaise, + effectiveUnitPricePaise, + quantity: qty, + ticketSubtotalPaise, + activePhase, + section, + appliedOffer, + offerReason, + discountPaise, + finalPaise, + breakdown: { + tierName: tier.name, + sectionName: section ? section.name : null, + phaseName: activePhase ? activePhase.name : null, + unitPricePaise: effectiveUnitPricePaise, + quantity: qty, + subtotalPaise: ticketSubtotalPaise, + offerName: appliedOffer ? appliedOffer.name : null, + offerCode: appliedOffer ? appliedOffer.code : null, + discountPaise, + finalPayablePaise: finalPaise, + currency: 'INR' + } + }; +} + +/** + * Saves immutable price snapshot in database for an initiated booking. + */ +export async function createBookingPriceSnapshot(c, { + bookingId, + eventId, + pricing +}) { + const { + basePricePaise, + quantity, + ticketSubtotalPaise, + activePhase, + section, + appliedOffer, + discountPaise, + finalPaise, + breakdown + } = pricing; + + const res = await c.query( + `INSERT INTO booking_price_snapshots ( + booking_id, event_id, base_price_paise, quantity, subtotal_paise, + phase_id, phase_name, section_id, section_name, + offer_id, offer_name, offer_code, discount_paise, final_paise, + currency, breakdown + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, 'INR', $15) + ON CONFLICT (booking_id) DO UPDATE + SET base_price_paise = EXCLUDED.base_price_paise, + subtotal_paise = EXCLUDED.subtotal_paise, + discount_paise = EXCLUDED.discount_paise, + final_paise = EXCLUDED.final_paise, + breakdown = EXCLUDED.breakdown + RETURNING *`, + [ + bookingId, + eventId, + basePricePaise, + quantity, + ticketSubtotalPaise, + activePhase ? activePhase.id : null, + activePhase ? activePhase.name : null, + section ? section.id : null, + section ? section.name : null, + appliedOffer ? appliedOffer.id : null, + appliedOffer ? appliedOffer.name : null, + appliedOffer ? appliedOffer.code : null, + discountPaise, + finalPaise, + JSON.stringify(breakdown) + ] + ); + + return res.rows[0]; +} diff --git a/lib/services/sales-phases.js b/lib/services/sales-phases.js new file mode 100644 index 0000000..fa35a91 --- /dev/null +++ b/lib/services/sales-phases.js @@ -0,0 +1,141 @@ +// lib/services/sales-phases.js - Sales Timeline & Scheduled Pricing Phases Module. +// Multi-phase scheduled pricing, automatic phase transitions, quotas & server-time enforcement. + +import { db } from '../db.js'; +import { HttpError } from '../http.js'; + +export async function saveEventSalesPhases(c, eventId, phases = []) { + await c.query(`DELETE FROM event_sales_phases WHERE event_id = $1`, [eventId]); + if (!Array.isArray(phases) || phases.length === 0) { + await c.query(`UPDATE events SET has_sales_phases = false WHERE id = $1`, [eventId]); + return []; + } + + const valid = []; + for (let i = 0; i < phases.length; i++) { + const p = phases[i]; + const name = String(p.name || '').trim(); + if (!name) continue; + if (!p.startsAt || !p.endsAt) continue; + + const startsAt = new Date(p.startsAt); + const endsAt = new Date(p.endsAt); + if (isNaN(startsAt.getTime()) || isNaN(endsAt.getTime()) || endsAt <= startsAt) { + continue; + } + + const tz = String(p.timezone || 'Asia/Kolkata').trim(); + const pricePaise = p.pricePaise != null ? Math.max(0, parseInt(p.pricePaise, 10)) : null; + const quota = p.quota != null ? Math.max(1, parseInt(p.quota, 10)) : null; + const maxPerBooking = p.maxPerBooking != null ? Math.max(1, parseInt(p.maxPerBooking, 10)) : 10; + const tierIds = Array.isArray(p.applicableTierIds) ? p.applicableTierIds.filter(Boolean) : []; + const accessCode = p.accessCode ? String(p.accessCode).trim().toUpperCase() : null; + const isActive = p.isActive !== false; + + const res = await c.query( + `INSERT INTO event_sales_phases ( + event_id, name, starts_at, ends_at, timezone, price_paise, quota, + max_per_booking, applicable_tier_ids, access_code, is_active, sort_order + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) + RETURNING *`, + [ + eventId, name, startsAt, endsAt, tz, pricePaise, quota, + maxPerBooking, tierIds, accessCode, isActive, i + ] + ); + valid.push(res.rows[0]); + } + + await c.query(`UPDATE events SET has_sales_phases = $2 WHERE id = $1`, [eventId, valid.length > 0]); + return valid; +} + +export async function getEventSalesPhases(eventId, c = db) { + const { rows } = await c.query( + `SELECT * FROM event_sales_phases WHERE event_id = $1 ORDER BY sort_order ASC, starts_at ASC`, + [eventId] + ); + return rows; +} + +/** + * Resolves active, upcoming and expired phases according to authoritative server clock. + */ +export function categorizePhases(phases = [], { now = new Date(), tierId = null, accessCode = null } = {}) { + const currentTime = now.getTime(); + let currentActive = null; + const upcoming = []; + const past = []; + + for (const p of phases) { + if (p.is_active === false || p.isActive === false) continue; + if (Array.isArray(p.applicable_tier_ids) && p.applicable_tier_ids.length > 0 && tierId) { + if (!p.applicable_tier_ids.includes(tierId)) continue; + } + + const start = new Date(p.starts_at || p.startsAt).getTime(); + const end = new Date(p.ends_at || p.endsAt).getTime(); + const sold = p.tickets_sold ?? p.soldCount ?? 0; + const isExhausted = p.quota != null && sold >= p.quota; + + if (currentTime >= start && currentTime < end && !isExhausted) { + if (p.access_code && accessCode !== p.access_code) { + // Requires code to unlock + continue; + } + if (!currentActive) { + currentActive = p; + } + } else if (currentTime < start) { + upcoming.push(p); + } else { + past.push(p); + } + } + + return { + current: currentActive, + activePhase: currentActive, + upcoming, + upcomingPhases: upcoming, + past, + pastPhases: past + }; +} + +/** + * Atomically records phase ticket allocation and asserts quota under row locks. + */ +export async function assertAndRecordPhaseSale(c, phaseId, quantity = 1) { + if (!phaseId) return null; + const phase = (await c.query( + `SELECT * FROM event_sales_phases WHERE (id::text = $1 OR name = $1) FOR UPDATE`, + [String(phaseId)] + )).rows[0]; + + if (!phase) throw new HttpError(404, 'phase_not_found', 'Sales phase not found.'); + const now = Date.now(); + if (new Date(phase.starts_at).getTime() > now) { + throw new HttpError(409, 'phase_not_started', `Sales phase "${phase.name}" has not started yet.`); + } + if (new Date(phase.ends_at).getTime() <= now) { + throw new HttpError(409, 'phase_ended', `Sales phase "${phase.name}" has ended.`); + } + if (phase.quota != null && phase.tickets_sold + quantity > phase.quota) { + const remaining = Math.max(0, phase.quota - phase.tickets_sold); + throw new HttpError( + 409, + 'phase_quota_exhausted', + remaining > 0 + ? `Only ${remaining} ticket(s) remaining in ${phase.name}.` + : `Sales phase "${phase.name}" has sold out.` + ); + } + + await c.query( + `UPDATE event_sales_phases SET tickets_sold = tickets_sold + $2, updated_at = now() WHERE id = $1`, + [phase.id, quantity] + ); + + return phase; +} diff --git a/lib/views/checkout-upi.js b/lib/views/checkout-upi.js index 918d0a1..62efa71 100644 --- a/lib/views/checkout-upi.js +++ b/lib/views/checkout-upi.js @@ -18,6 +18,12 @@ export function renderUpiCheckout({ ? (order.feePaise / 100).toFixed(2) : Math.max(0, Number(amountRupees) - Number(baseRupees)).toFixed(2); const feePct = order.feePercentage || 5; + const pricing = order.pricing; + const subtotalRupees = pricing?.subtotalPaise ? (pricing.subtotalPaise / 100).toFixed(2) : (isDirectUpi ? amountRupees : baseRupees); + const discountRupees = pricing?.discountPaise ? (pricing.discountPaise / 100).toFixed(2) : null; + const offerName = pricing?.offerName || (pricing?.offerCode ? `Code ${pricing.offerCode}` : null); + const phaseName = pricing?.phaseName; + const sectionName = pricing?.sectionName; const organiserDestination = order.organiserUpiId || event.organiser_upi_id || 'Organiser UPI'; const organiserName = order.organiserPayeeName || event.organiser_payee_name || event.organizer || 'Event Organiser'; const upiUri = order.upiIntentUrl; @@ -47,9 +53,14 @@ export function renderUpiCheckout({
- ${isDirectUpi ? 'Ticket price' : 'Organiser ticket price'} (${tier.name} × ${order.quantity}) - ₹${isDirectUpi ? amountRupees : baseRupees} + ${sectionName ? `${sectionName} (Section)` : (phaseName ? `${tier.name} (${phaseName})` : (isDirectUpi ? 'Ticket price' : 'Organiser ticket price'))} (${tier.name} × ${order.quantity}) + ₹${subtotalRupees}
+ ${discountRupees && Number(discountRupees) > 0 ? html` +
+ Discount${offerName ? ` (${offerName})` : ''} + -₹${discountRupees} +
` : ''} ${!isDirectUpi && Number(feeRupees) > 0 ? html`
NIGHTLIFEZ infrastructure fee (${feePct}%) diff --git a/lib/views/event.js b/lib/views/event.js index 685bf76..4e2aa96 100644 --- a/lib/views/event.js +++ b/lib/views/event.js @@ -58,6 +58,134 @@ const dayLabel = (d) => fmtDate(`${d}T12:00:00Z`, 'UTC'); /** A local 'YYYY-MM-DDTHH:mm' (already in the event's timezone) → "Sat, 14 Dec, 6:30 am". */ const localLabel = (t) => `${fmtDate(`${t}:00Z`, 'UTC')}, ${fmtTime(`${t}:00Z`, 'UTC')}`; +function renderFacilitiesSectionHtml(facilities = []) { + if (!Array.isArray(facilities) || facilities.length === 0) return ''; + const groups = {}; + for (const f of facilities) { + const cat = f.category || 'other'; + if (!groups[cat]) groups[cat] = []; + groups[cat].push(f); + } + const CATEGORY_NAMES = { + parking: '🚗 Parking', + food_beverage: '🍽️ Food & Beverages', + accessibility: '♿ Accessibility', + medical_safety: '🛡️ Medical & Safety', + other: '✨ Other Facilities & Policies', + custom: '⭐ Additional Amenities' + }; + + return html`
+

Facilities & Amenities

+
+ ${Object.entries(groups).map(([cat, items]) => html` +
+

${CATEGORY_NAMES[cat] || 'Facilities'}

+
    + ${items.map((item) => html`
  • + +
    + ${item.name} + ${item.description ? html`

    ${item.description}

    ` : ''} +
    +
  • `)} +
+
+ `)} +
+
`; +} + +function renderOffersSectionHtml(offers = []) { + if (!Array.isArray(offers) || offers.length === 0) return ''; + return html`
+

Offers & Discounts

+
+ ${offers.map((o) => { + const valLabel = o.discountType === 'percentage' + ? `${o.discountValue}% OFF${o.maxDiscountPaise ? ` (up to ₹${Math.round(o.maxDiscountPaise / 100)})` : ''}` + : `₹${Math.round(o.discountValue / 100)} OFF`; + return html` +
+ ${valLabel} +

${o.name}

+ ${o.description ? html`

${o.description}

` : ''} + ${o.code ? html`

Use code: ${o.code}

` : ''} +
`; + })} +
+
`; +} + +function renderSalesTimelineSectionHtml(phases = []) { + if (!Array.isArray(phases) || phases.length === 0) return ''; + const now = Date.now(); + return html`
+

Ticket Sales Timeline

+
+ + + + + + + + + + + ${phases.map((p) => { + const start = new Date(p.startsAt).getTime(); + const end = new Date(p.endsAt).getTime(); + const isActive = now >= start && now < end && (p.quota == null || p.ticketsSold < p.quota); + const isSoldOut = p.quota != null && p.ticketsSold >= p.quota; + const isPast = now >= end; + const statusLabel = isSoldOut ? 'Sold Out' : (isPast ? 'Ended' : (isActive ? 'Active Now' : 'Upcoming')); + const statusClass = isActive ? 'badge badge-brand' : (isSoldOut ? 'badge badge-sold-out' : 'badge badge-ghost'); + return html` + + + + + + `; + })} + +
PhasePriceDatesStatus
${p.name}${p.pricePaise != null ? `₹${Math.round(p.pricePaise / 100)}` : 'Standard'}${fmtDate(p.startsAt)} – ${fmtDate(p.endsAt)}${statusLabel}
+
+
`; +} + +function renderVenueMapSectionHtml(venueLayout) { + if (!venueLayout || !Array.isArray(venueLayout.sections) || venueLayout.sections.length === 0) return ''; + const sections = venueLayout.sections; + return html`
+

Venue Layout & Sections

+

View section locations, capacities, and pricing.

+
+
+
STAGE
+
+
+ ${sections.map((sec) => { + const isOff = sec.status === 'unavailable' || sec.effectiveStatus === 'sold_out'; + const priceStr = sec.pricePaise != null ? `₹${Math.round(sec.pricePaise / 100)}` : ''; + return html` +
+
+ ${sec.name} + ${priceStr ? html`${priceStr}` : ''} +
+

+ ${sec.capacity ? `Capacity: ${sec.capacity}` : ''} + ${isOff ? (sec.effectiveStatus === 'sold_out' ? ' · Sold Out' : ' · Unavailable') : ' · Available'} +

+
`; + })} +
+
+
`; +} + function questionField(q, disabled) { const name = `answers.${q.id}`; const req = q.required ? raw(' required') : ''; @@ -211,6 +339,10 @@ export function renderEvent(e, { preview = false, previewBanner = '' } = {}) {
Hosted by
${e.organizer}
${e.description && e.description !== e.summary ? html`

About

${e.description.split(/\n{2,}/).map((p) => html`

${p}

`)}
` : ''} + ${e.offers?.length ? renderOffersSectionHtml(e.offers) : ''} + ${e.venueLayout?.sections?.length ? renderVenueMapSectionHtml(e.venueLayout) : ''} + ${e.salesPhases?.length ? renderSalesTimelineSectionHtml(e.salesPhases) : ''} + ${e.facilities?.length ? renderFacilitiesSectionHtml(e.facilities) : ''} ${e.schedule?.dates?.length > 1 ? html`

Dates & Schedule

' + '

This number is shown only to guests with a confirmed booking — never on the public page.

'; return card('Ask guests questions', toggle('features.questions.enabled', 'Ask questions when guests book', 'Collect what you need to run the event, like dietary needs.') + qBody) + + facilitiesCardHtml() + card('Approve each guest', toggle('features.approval.enabled', 'Approve every booking yourself', '') + '
  • What guests see: a “Request to join” button. Their request waits for you; nothing is charged.
  • ' + '
  • What you do: approve or decline each request from your event page. You’ll get a Telegram message for each one.
  • ' + @@ -2393,13 +2592,50 @@ '
') : ''; + var facHtml = ''; + if (d.facilities && d.facilities.length) { + facHtml = '

Facilities & Amenities

' + + d.facilities.map(function (fc) { + return '' + esc(fc.icon ? fc.icon + ' ' : '') + esc(fc.name) + ''; + }).join('') + '
'; + } + + var venueSecHtml = ''; + if (d.venueLayout && d.venueLayout.layoutType === 'section_based' && d.venueLayout.sections && d.venueLayout.sections.length) { + venueSecHtml = '

Venue Sections & Layout

' + + d.venueLayout.sections.map(function (sc) { + return '
' + esc(sc.name) + ' · ' + (sc.pricePaise ? money(sc.pricePaise) : 'Free') + ' (' + esc(sc.capacity) + ' spots)
'; + }).join('') + '
'; + } + + var offersHtml = ''; + if (d.offers && d.offers.length) { + offersHtml = '

Special Offers

' + + d.offers.map(function (of) { + var disc = of.discountType === 'percentage' ? of.discountValue + '% OFF' : '₹' + (of.discountValue / 100) + ' OFF'; + return '
' + esc(of.name) + ' (' + esc(disc) + (of.code ? ' · Code: ' + esc(of.code) : '') + ')
'; + }).join('') + '
'; + } + + var timelineHtml = ''; + if (d.salesTimeline && d.salesTimeline.enabled && d.salesTimeline.phases && d.salesTimeline.phases.length) { + timelineHtml = '

Sales Timeline

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

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

' + '

' + esc(d.title || 'Untitled event') + '

' + esc(whenSummary()) + '

' + esc(where || 'Location to be added') + '

' + (d.description ? '

' + esc(d.description.slice(0, 700)) + (d.description.length > 700 ? '…' : '') + '

' : '') + schedHtml + + venueSecHtml + + timelineHtml + + offersHtml + '

Tickets

' + (tix ? '
    ' + tix + '
' : '

No tickets yet.

') + + facHtml + '

Entry

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

Questions at booking

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

Pickup points

    ' + pts.map(function (p) { return '
  • ' + esc(p.name || 'Unnamed') + (p.time ? ' · ' + esc(fmtLocal(p.time)) : '') + '
  • '; }).join('') + '
' : '') + @@ -2833,6 +3069,155 @@ }); case 'publish-cancel': return $('[data-publish-dialog]', el).close(); case 'publish-confirm': return publishNow(b); + case 'set-venue-layout-type': + var vType = b.getAttribute('data-val') || 'none'; + if (!S.data.venueLayout) S.data.venueLayout = { layoutType: vType, sections: [] }; + S.data.venueLayout.layoutType = vType; + if (vType === 'section_based' && (!S.data.venueLayout.sections || !S.data.venueLayout.sections.length)) { + S.data.venueLayout.sections = [ + { id: uid(), name: 'General Admission', category: 'general', pricePaise: 0, capacity: 200, status: 'available', color: '#6366f1' } + ]; + } + touch(); return render(); + case 'add-venue-section': + if (!S.data.venueLayout) S.data.venueLayout = { layoutType: 'section_based', sections: [] }; + var secPresetKey = b.getAttribute('data-sec') || 'custom'; + var secPresets = { + stage: { name: 'Stage Front', category: 'stage', pricePaise: 99900, capacity: 50, color: '#f43f5e' }, + vip: { name: 'VIP Lounge', category: 'vip', pricePaise: 149900, capacity: 30, color: '#a855f7' }, + fanpit: { name: 'Fanpit', category: 'fanpit', pricePaise: 79900, capacity: 100, color: '#06b6d4' }, + gold: { name: 'Gold Tier', category: 'gold', pricePaise: 59900, capacity: 150, color: '#eab308' }, + silver: { name: 'Silver Tier', category: 'silver', pricePaise: 39900, capacity: 200, color: '#94a3b8' }, + general: { name: 'Standing Area', category: 'general', pricePaise: 19900, capacity: 300, color: '#10b981' }, + custom: { name: 'Custom Section', category: 'custom', pricePaise: 49900, capacity: 100, color: '#3b82f6' } + }; + var sp = secPresets[secPresetKey] || secPresets.custom; + var newSec = { + id: uid(), + name: sp.name, + category: sp.category, + pricePaise: S.data.paymentMethod === 'direct_upi' ? sp.pricePaise : 0, + capacity: sp.capacity, + status: 'available', + color: sp.color + }; + S.data.venueLayout.sections = (S.data.venueLayout.sections || []).concat(newSec); + touch(); return render(); + case 'del-venue-section': + if (S.data.venueLayout && S.data.venueLayout.sections) { + S.data.venueLayout.sections.splice(i, 1); + touch(); return render(); + } + return; + case 'add-sales-phase': + if (!S.data.salesTimeline) S.data.salesTimeline = { enabled: true, phases: [] }; + var phKey = b.getAttribute('data-phase') || 'general'; + var phPresets = { + early_access: { name: 'Early Access', phaseType: 'early_access', pricePaise: 29900, quota: 50 }, + pre_sale: { name: 'Pre-Sale Phase', phaseType: 'pre_sale', pricePaise: 39900, quota: 100 }, + general: { name: 'General Public Sale', phaseType: 'general', pricePaise: 49900, quota: null }, + final_release: { name: 'Final Release', phaseType: 'final_release', pricePaise: 69900, quota: 50 } + }; + var php = phPresets[phKey] || phPresets.general; + var newPhase = { + id: uid(), + name: php.name, + phaseType: php.phaseType, + pricePaise: S.data.paymentMethod === 'direct_upi' ? php.pricePaise : null, + startsAt: S.data.startLocal || '', + endsAt: S.data.endLocal || '', + quota: php.quota, + accessCode: '' + }; + S.data.salesTimeline.phases = (S.data.salesTimeline.phases || []).concat(newPhase); + touch(); return render(); + case 'del-sales-phase': + if (S.data.salesTimeline && S.data.salesTimeline.phases) { + S.data.salesTimeline.phases.splice(i, 1); + touch(); return render(); + } + return; + case 'add-offer': + if (!S.data.offers) S.data.offers = []; + var offKey = b.getAttribute('data-offer') || 'custom'; + var offPresets = { + percent10: { name: '10% Off Early Special', code: 'SAVE10', discountType: 'percentage', discountValue: 10, maxDiscountPaise: 20000, minOrderPaise: null, minQuantity: 1 }, + fixed200: { name: '₹200 Flat Discount', code: 'PARTY200', discountType: 'fixed_amount', discountValue: 20000, maxDiscountPaise: null, minOrderPaise: 50000, minQuantity: 1 }, + group15: { name: 'Squad Deal (2+ tickets)', code: 'SQUAD15', discountType: 'percentage', discountValue: 15, maxDiscountPaise: 50000, minOrderPaise: null, minQuantity: 2 }, + custom: { name: 'Special Promotion', code: '', discountType: 'percentage', discountValue: 10, maxDiscountPaise: null, minOrderPaise: null, minQuantity: 1 } + }; + var op = offPresets[offKey] || offPresets.custom; + var newOffer = { + id: uid(), + name: op.name, + code: op.code, + discountType: op.discountType, + discountValue: op.discountValue, + maxDiscountPaise: op.maxDiscountPaise, + minOrderPaise: op.minOrderPaise, + minQuantity: op.minQuantity, + description: '' + }; + S.data.offers.push(newOffer); + touch(); return render(); + case 'del-offer': + if (S.data.offers) { + S.data.offers.splice(i, 1); + touch(); return render(); + } + return; + case 'toggle-facility': + if (!S.data.facilities) S.data.facilities = []; + var fKey = b.getAttribute('data-key'); + var fCat = b.getAttribute('data-cat') || 'other'; + var fName = b.getAttribute('data-name'); + var fIcon = b.getAttribute('data-icon') || ''; + var existingIdx = -1; + for (var fi = 0; fi < S.data.facilities.length; fi++) { + if ((S.data.facilities[fi].facilityKey || S.data.facilities[fi].key) === fKey) { + existingIdx = fi; + break; + } + } + if (existingIdx >= 0) { + S.data.facilities.splice(existingIdx, 1); + } else { + S.data.facilities.push({ + facilityKey: fKey, + category: fCat, + name: fName, + icon: fIcon, + isCustom: false + }); + } + touch(); return render(); + case 'add-custom-facility': + if (!S.data.facilities) S.data.facilities = []; + var customNameInput = $('#custom-fac-name', el); + var customCatSelect = $('#custom-fac-cat', el); + var customDescInput = $('#custom-fac-desc', el); + var cName = customNameInput ? customNameInput.value.trim() : ''; + var cCat = customCatSelect ? customCatSelect.value : 'other'; + var cDesc = customDescInput ? customDescInput.value.trim() : ''; + if (!cName) { + alert('Please enter a facility name.'); + return; + } + S.data.facilities.push({ + facilityKey: 'custom_' + uid(), + category: cCat, + name: cName, + description: cDesc, + isCustom: true + }); + touch(); return render(); + case 'del-custom-facility': + if (!S.data.facilities) return; + var delName = b.getAttribute('data-name'); + S.data.facilities = S.data.facilities.filter(function (f) { + return f.name !== delName; + }); + touch(); return render(); case 'copy': return copyText(b.getAttribute('data-url'), b); case 'share': return share(S.data.title, b.getAttribute('data-url'), b); } diff --git a/test/advanced-event-ticketing.test.js b/test/advanced-event-ticketing.test.js new file mode 100644 index 0000000..c5a8e5d --- /dev/null +++ b/test/advanced-event-ticketing.test.js @@ -0,0 +1,741 @@ +// test/advanced-event-ticketing.test.js +// Automated test suite for Advanced Event Configuration & Professional Ticketing System: +// Module 1: Event Facilities & Amenities +// Module 2: Offers & Discount Engine +// Module 3: Interactive Venue Layout & Section-Based Ticketing +// Module 4: Sales Timeline & Scheduled Pricing Phases +// Integration: Full E2E with Direct UPI Checkout and Backward Compatibility for Free Events. + +import { test, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { + resetDb, startServer, stopServer, db, signedInClient, clearCalls +} from './helpers.js'; + +import { + PREDEFINED_FACILITIES, + FACILITY_CATEGORIES, + getEventFacilities +} from '../lib/services/event-facilities.js'; + +import { + calculateDiscountPaise, + getOrganiserOffersReport +} from '../lib/services/event-offers.js'; + +import { + getEventVenueLayout +} from '../lib/services/event-venue.js'; + +import { + categorizePhases +} from '../lib/services/sales-phases.js'; + +let org1; +let org2; +let attendee1; +let attendee2; + +function istLocal(days, hh = '19:00') { + const d = new Date(Date.now() + days * 864e5 + 5.5 * 3600e3).toISOString().slice(0, 10); + return `${d}T${hh}`; +} + +async function createOrganiser() { + const c = await signedInClient(); + await db.query('UPDATE users SET organiser_enabled = true WHERE id = $1', [c.userId]); + return c; +} + +before(async () => { + process.env.ENABLE_LIVE_PAYMENTS = 'false'; + process.env.UPI_CHECKOUT_ENABLED = 'false'; + + await resetDb(); + await startServer(); + + org1 = await createOrganiser(); + org2 = await createOrganiser(); + attendee1 = await signedInClient(); + attendee2 = await signedInClient(); +}); + +after(async () => { + await stopServer(); +}); + +beforeEach(clearCalls); + +function baseEventDraft(overrides = {}) { + return { + template: 'party', + category: 'nightlife', + title: 'Superclub Experience Bangalore', + timezone: 'Asia/Kolkata', + startLocal: istLocal(5, '20:00'), + endLocal: istLocal(6, '02:00'), + multiDay: false, + venue: 'Sky Lounge Highstreet', + city: 'Bengaluru', + area: 'MG Road', + privateVenue: false, + description: 'Premier nightlife experience with international DJs.', + paymentMethod: 'direct_upi', + organiserUpiId: 'superclub@okhdfcbank', + organiserPayeeName: 'Superclub Ventures Pvt Ltd', + paymentInstructions: 'Transfer ticket amount and provide bank UTR.', + refundPolicy: 'Full refund if cancelled 48h before event.', + cancellationPolicy: { + template: 'standard', + primaryDeadlineHours: 48, + primaryRefundPercent: 100, + secondaryDeadlineHours: 24, + secondaryRefundPercent: 50, + noRefundHours: 24, + allowTransfers: false + }, + tickets: [ + { + id: 'tier_ga', + name: 'General Admission', + kind: 'paid', + pricePaise: 99900, + quantity: 100, + maxPerBooking: 4, + validOn: 'all' + } + ], + features: {}, + ...overrides + }; +} + +// ============================================================================= +// MODULE 1: EVENT FACILITIES & AMENITIES +// ============================================================================= + +test('Module 1: Predefined facilities and categories are properly defined', () => { + assert.ok(Array.isArray(PREDEFINED_FACILITIES)); + assert.ok(PREDEFINED_FACILITIES.length >= 10); + assert.ok(Object.keys(FACILITY_CATEGORIES).length >= 5); + + const keys = PREDEFINED_FACILITIES.map(f => f.key); + assert.ok(keys.includes('valet_parking')); + assert.ok(keys.includes('wheelchair_accessible')); + assert.ok(keys.includes('first_aid')); + assert.ok(keys.includes('food_available')); +}); + +test('Module 1: Save facilities with draft, publish, and query public event', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const draftId = r.json.draft.id; + const version = r.json.draft.version; + + const facilities = [ + { + facilityKey: 'free_parking', + category: 'parking', + name: 'Free Parking Available', + icon: '🚗', + description: 'Dedicated parking for 200 cars' + }, + { + facilityKey: 'wheelchair_accessible', + category: 'accessibility', + name: 'Wheelchair Accessible', + icon: '♿' + }, + { + facilityKey: 'custom_pool_lounge', + category: 'other', + name: 'Rooftop Pool Access', + icon: '🏊', + description: 'Towels provided at entrance', + isCustom: true + } + ]; + + const putRes = await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data: baseEventDraft({ facilities }), + step: 'preview', + version + }); + assert.equal(putRes.status, 200, putRes.text); + assert.equal(putRes.json.draft.data.facilities.length, 3); + + // Publish event + const pubRes = await org1.post(`/api/organiser/drafts/${draftId}/publish`, { + version: putRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + const eventId = pubRes.json.eventId; + assert.ok(eventId); + + // Verify facilities in database + const savedFacs = await getEventFacilities(db, eventId); + assert.equal(savedFacs.length, 3); + const custom = savedFacs.find(f => f.is_custom); + assert.ok(custom); + assert.equal(custom.name, 'Rooftop Pool Access'); + assert.equal(custom.category, 'other'); + + // Verify public event data includes facilities + const eventRow = await db.one('SELECT * FROM events WHERE id = $1', [eventId]); + assert.equal(eventRow.has_facilities, true); + + // Verify HTML renders the facilities section + const pageRes = await attendee1.get(`/events/${pubRes.json.slug}`); + assert.equal(pageRes.status, 200); + assert.match(pageRes.text, /Facilities & Amenities/); + assert.match(pageRes.text, /Free Parking Available/); + assert.match(pageRes.text, /Wheelchair Accessible/); + assert.match(pageRes.text, /Rooftop Pool Access/); +}); + +test('Module 1: Free event works with facilities completely omitted', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'social' }); + const draftId = r.json.draft.id; + const version = r.json.draft.version; + + const freeDraft = baseEventDraft({ + title: 'Sunday Morning Coffee & Book Club', + paymentMethod: 'free', + organiserUpiId: null, + organiserPayeeName: null, + tickets: [ + { + id: 'tier_free_rsvp', + name: 'Free RSVP', + kind: 'free', + pricePaise: 0, + quantity: 30, + maxPerBooking: 2, + validOn: 'all' + } + ], + facilities: [] + }); + + const putRes = await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data: freeDraft, + step: 'preview', + version + }); + assert.equal(putRes.status, 200, putRes.text); + + const pubRes = await org1.post(`/api/organiser/drafts/${draftId}/publish`, { + version: putRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + + const savedFacs = await getEventFacilities(db, pubRes.json.eventId); + assert.equal(savedFacs.length, 0); + + const eventRow = await db.one('SELECT has_facilities FROM events WHERE id = $1', [pubRes.json.eventId]); + assert.equal(eventRow.has_facilities, false); +}); + +// ============================================================================= +// MODULE 2: OFFERS & DISCOUNT ENGINE +// ============================================================================= + +test('Module 2: Percentage discount calculation with cap in integer paise', () => { + const offer = { + name: '20% Mega Festival Discount', + code: 'FEST20', + discountType: 'percentage', + discountValue: 20, + maxDiscountPaise: 50000, // Capped at ₹500 + minOrderPaise: 100000, // Min ₹1,000 order + minQuantity: 1 + }; + + // Case 1: Order of ₹2,000 (200000 paise). 20% is ₹400 (40000 paise) < cap ₹500 + const eval1 = calculateDiscountPaise(offer, { ticketSubtotalPaise: 200000, quantity: 2 }); + assert.equal(eval1.valid, true); + assert.equal(eval1.discountPaise, 40000); + assert.equal(eval1.finalPayablePaise, 160000); + + // Case 2: Order of ₹5,000 (500000 paise). 20% is ₹1,000 > cap ₹500. Discount capped at ₹500 + const eval2 = calculateDiscountPaise(offer, { ticketSubtotalPaise: 500000, quantity: 5 }); + assert.equal(eval2.valid, true); + assert.equal(eval2.discountPaise, 50000); + assert.equal(eval2.finalPayablePaise, 450000); + + // Case 3: Order below min order (₹800 < ₹1,000) + const eval3 = calculateDiscountPaise(offer, { ticketSubtotalPaise: 80000, quantity: 1 }); + assert.equal(eval3.valid, false); + assert.match(eval3.reason, /Minimum order/); +}); + +test('Module 2: Fixed rupee discount and minQuantity rule', () => { + const offer = { + name: 'Squad Saver ₹300 Off', + code: 'SQUAD300', + discountType: 'fixed_amount', + discountValue: 30000, // ₹300 in paise + minQuantity: 3 + }; + + // Only 2 tickets: fails minQuantity + const eval1 = calculateDiscountPaise(offer, { ticketSubtotalPaise: 100000, quantity: 2 }); + assert.equal(eval1.valid, false); + assert.match(eval1.reason, /Minimum of 3/); + + // 3 tickets: succeeds + const eval2 = calculateDiscountPaise(offer, { ticketSubtotalPaise: 150000, quantity: 3 }); + assert.equal(eval2.valid, true); + assert.equal(eval2.discountPaise, 30000); + assert.equal(eval2.finalPayablePaise, 120000); + + // Discount cannot make price negative + const eval3 = calculateDiscountPaise(offer, { ticketSubtotalPaise: 20000, quantity: 3 }); + assert.equal(eval3.valid, true); + assert.equal(eval3.discountPaise, 20000); // capped at subtotal + assert.equal(eval3.finalPayablePaise, 0); +}); + +test('Module 2: Direct UPI checkout with promo code reflects exact discounted amount', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const draftId = r.json.draft.id; + const version = r.json.draft.version; + + const offers = [ + { + name: 'Nightlife Launch 10% Off', + code: 'NIGHT10', + discountType: 'percentage', + discountValue: 10, + maxDiscountPaise: 20000, + minQuantity: 1 + } + ]; + + const putRes = await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data: baseEventDraft({ + title: 'Neon Nights With Promo Code', + tickets: [ + { + id: 'tier_vip', + name: 'VIP Pass', + kind: 'paid', + pricePaise: 100000, // ₹1,000 + quantity: 50, + maxPerBooking: 4, + validOn: 'all' + } + ], + offers + }), + step: 'preview', + version + }); + assert.equal(putRes.status, 200, putRes.text); + + const pubRes = await org1.post(`/api/organiser/drafts/${draftId}/publish`, { + version: putRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + const event = pubRes.json; + + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.eventId]); + + // Attendee initiates checkout for 2 tickets with promo code night10 + // Subtotal = 2 * ₹1,000 = ₹2,000. 10% discount = ₹200. Final payable = ₹1,800. + const checkoutRes = await attendee1.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=2&promoCode=night10` + ); + assert.equal(checkoutRes.status, 200, checkoutRes.text); + + // Verify rendered checkout page includes payee, discounted total and discount row + assert.match(checkoutRes.text, /Superclub Ventures Pvt Ltd/); + assert.match(checkoutRes.text, /superclub@okhdfcbank/); + assert.match(checkoutRes.text, /₹1800\.00/); + assert.match(checkoutRes.text, /am=1800\.00/); + assert.match(checkoutRes.text, /Nightlife Launch 10% Off/); + + // Retrieve booking from DB + const booking = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.eventId, attendee1.userId] + ); + assert.ok(booking); + assert.equal(booking.amount_paise, 180000); // ₹1,800 + assert.equal(booking.discount_paise, 20000); // ₹200 + assert.equal(booking.quantity, 2); + + // Submit UTR + const utrRes = await attendee1.post('/api/checkout/upi/report-payment', { + bookingId: booking.id, + utr: '123456789012' + }); + assert.equal(utrRes.status, 200); + + // Organiser confirms payment + const confirmRes = await org1.post(`/api/organiser/events/${event.eventId}/payments/${booking.id}/confirm`, { + warningConfirmed: true, + note: 'Verified ₹1,800 in bank app' + }); + assert.equal(confirmRes.status, 200); + + // Verify reporting + const report = await getOrganiserOffersReport(db, event.eventId); + assert.equal(report.length, 1); + assert.equal(report[0].code, 'NIGHT10'); + assert.equal(Number(report[0].total_redemptions), 1); + assert.equal(Number(report[0].total_discount_paise), 20000); + assert.equal(Number(report[0].net_revenue_paise), 180000); +}); + +// ============================================================================= +// MODULE 3: INTERACTIVE VENUE LAYOUT & SECTION-BASED TICKETING +// ============================================================================= + +test('Module 3: Section-based venue layout with independent prices and capacities', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const draftId = r.json.draft.id; + const version = r.json.draft.version; + + const venueLayout = { + layoutType: 'section_based', + sections: [ + { + sectionKey: 'sec_vip_lounge', + name: 'VIP Sky Lounge', + category: 'vip', + pricePaise: 199900, // ₹1,999 + capacity: 10, + status: 'available', + color: '#a855f7' + }, + { + sectionKey: 'sec_fanpit', + name: 'Front Fanpit', + category: 'fanpit', + pricePaise: 99900, // ₹999 + capacity: 20, + status: 'available', + color: '#06b6d4' + }, + { + sectionKey: 'sec_sold_out', + name: 'Sold Out Balcony', + category: 'gold', + pricePaise: 149900, + capacity: 5, + status: 'sold_out', + color: '#eab308' + } + ] + }; + + const putRes = await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data: baseEventDraft({ + title: 'Stadium Concert with Section Layout', + venueLayout + }), + step: 'preview', + version + }); + assert.equal(putRes.status, 200, putRes.text); + + const pubRes = await org1.post(`/api/organiser/drafts/${draftId}/publish`, { + version: putRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + const event = pubRes.json; + + // Verify public layout retrieval + const layout = await getEventVenueLayout(event.eventId, db); + assert.equal(layout.layoutType, 'section_based'); + assert.equal(layout.sections.length, 3); + + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.eventId]); + const vipSec = layout.sections.find(s => s.section_key === 'sec_vip_lounge'); + assert.ok(vipSec); + + // Booking with VIP section uses the VIP section price (₹1,999) + const checkoutRes = await attendee1.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=2§ionId=${vipSec.id}` + ); + assert.equal(checkoutRes.status, 200, checkoutRes.text); + assert.match(checkoutRes.text, /₹3998\.00/); + assert.match(checkoutRes.text, /am=3998\.00/); + + // Booking with sold-out section fails with error + const soldOutSec = layout.sections.find(s => s.section_key === 'sec_sold_out'); + const soldOutRes = await attendee2.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1§ionId=${soldOutSec.id}` + ); + assert.equal(soldOutRes.status, 409); + assert.match(soldOutRes.text, /sold out/i); +}); + +test('Module 3: Section capacity oversell protection with transactional row-locking', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const draftId = r.json.draft.id; + const version = r.json.draft.version; + + const venueLayout = { + layoutType: 'section_based', + sections: [ + { + sectionKey: 'sec_micro_table', + name: 'Private Table 1', + category: 'vip', + pricePaise: 500000, + capacity: 2, // only 2 spots! + status: 'available' + } + ] + }; + + const putRes = await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data: baseEventDraft({ + title: 'Exclusive High Roller Event', + venueLayout + }), + step: 'preview', + version + }); + assert.equal(putRes.status, 200, putRes.text); + + const pubRes = await org1.post(`/api/organiser/drafts/${draftId}/publish`, { + version: putRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + const event = pubRes.json; + + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.eventId]); + const sec = await db.one('SELECT * FROM event_venue_sections WHERE event_id = $1', [event.eventId]); + + // Attendee 1 books 2 seats (fills section capacity) + const book1 = await attendee1.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=2§ionId=${sec.id}` + ); + assert.equal(book1.status, 200); + + // Attendee 2 attempts to book 1 seat in the same section -> rejected! + const book2 = await attendee2.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1§ionId=${sec.id}` + ); + assert.equal(book2.status, 409); + assert.match(book2.text, /sold out/i); +}); + +// ============================================================================= +// MODULE 4: SALES TIMELINE & SCHEDULED PRICING PHASES +// ============================================================================= + +test('Module 4: Authoritative server clock evaluates active, upcoming, and ended phases', () => { + const now = new Date('2026-11-24T12:00:00Z'); + + const phases = [ + { + id: 'p_past', + name: 'Early Bird', + phase_type: 'early_access', + starts_at: '2026-11-20T00:00:00Z', + ends_at: '2026-11-23T23:59:59Z', + price_paise: 49900 + }, + { + id: 'p_curr', + name: 'Phase 2 Pre-Sale', + phase_type: 'pre_sale', + starts_at: '2026-11-24T00:00:00Z', + ends_at: '2026-11-26T23:59:59Z', + price_paise: 69900, + quota: 100, + tickets_sold: 10 + }, + { + id: 'p_future', + name: 'General Final Release', + phase_type: 'final_release', + starts_at: '2026-11-27T00:00:00Z', + ends_at: '2026-11-30T23:59:59Z', + price_paise: 99900 + } + ]; + + const cat = categorizePhases(phases, { now }); + assert.equal(cat.current?.id, 'p_curr'); + assert.equal(cat.upcoming.length, 1); + assert.equal(cat.upcoming[0].id, 'p_future'); + assert.equal(cat.past.length, 1); + assert.equal(cat.past[0].id, 'p_past'); +}); + +test('Module 4: Phase quota exhaustion and access code unlocking', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const draftId = r.json.draft.id; + const version = r.json.draft.version; + + const nowIso = new Date().toISOString(); + const futureIso = new Date(Date.now() + 864e5 * 2).toISOString(); + + const salesTimeline = { + enabled: true, + phases: [ + { + name: 'Flash Sale (First 2 Only)', + phaseType: 'pre_sale', + startsAt: nowIso, + endsAt: futureIso, + pricePaise: 29900, // ₹299 + quota: 2 // only 2 tickets in this phase + }, + { + name: 'Secret VIP Release', + phaseType: 'early_access', + startsAt: nowIso, + endsAt: futureIso, + pricePaise: 19900, + quota: 10, + accessCode: 'SECRETVIP' + } + ] + }; + + const putRes = await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data: baseEventDraft({ + title: 'Festival with Progressive Phases', + salesTimeline + }), + step: 'preview', + version + }); + assert.equal(putRes.status, 200, putRes.text); + + const pubRes = await org1.post(`/api/organiser/drafts/${draftId}/publish`, { + version: putRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + const event = pubRes.json; + + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.eventId]); + const phases = (await db.query('SELECT * FROM event_sales_phases WHERE event_id = $1', [event.eventId])).rows; + const secretPhase = phases.find(p => p.access_code === 'SECRETVIP'); + const flashPhase = phases.find(p => p.quota === 2); + + // 1. Secret VIP phase requires valid access code + const noCodeRes = await attendee1.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1&phaseId=${secretPhase.id}` + ); + assert.equal(noCodeRes.status, 400); + assert.match(noCodeRes.text, /access code/i); + + const withCodeRes = await attendee1.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1&phaseId=${secretPhase.id}&accessCode=SECRETVIP` + ); + assert.equal(withCodeRes.status, 200); + assert.match(withCodeRes.text, /₹199\.00/); + + // 2. Flash sale quota test: book 2 tickets + const flash1 = await attendee1.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=2&phaseId=${flashPhase.id}` + ); + assert.equal(flash1.status, 200); + assert.match(flash1.text, /₹598\.00/); // 2 × ₹299 + + // Attempting to book 1 more ticket under flashPhase fails because quota (2) is exhausted + const flash2 = await attendee2.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}&quantity=1&phaseId=${flashPhase.id}` + ); + assert.equal(flash2.status, 409); + assert.match(flash2.text, /quota|sold out/i); +}); + +// ============================================================================= +// INTEGRATION: COMBINED WORKFLOW & BACKWARD COMPATIBILITY +// ============================================================================= + +test('Integration: Combined workflow (Section + Phase Override + Offer Discount) with Direct UPI', async () => { + const r = await org1.post('/api/organiser/drafts', { template: 'party' }); + const draftId = r.json.draft.id; + const version = r.json.draft.version; + + const nowIso = new Date().toISOString(); + const futureIso = new Date(Date.now() + 864e5 * 2).toISOString(); + + // Base tier: ₹1,000 (100000 paise) + // Section: VIP Lounge base price ₹2,000 (200000 paise) + // Phase: Early Bird price override ₹1,500 (150000 paise) + // Offer: Promo code SAVE20 (20% off) -> 20% of ₹1,500 = ₹300 discount -> Final ₹1,200 (120000 paise) + const fullDraft = baseEventDraft({ + title: 'Ultimate Mega Festival 2026', + facilities: [ + { facilityKey: 'valet_parking', category: 'parking', name: 'Valet Parking Available', icon: '🚗' }, + { facilityKey: 'first_aid', category: 'medical_safety', name: 'First Aid & Medical Desk', icon: '🩺' } + ], + venueLayout: { + layoutType: 'section_based', + sections: [ + { sectionKey: 'sec_vip', name: 'VIP Lounge', category: 'vip', pricePaise: 200000, capacity: 50, status: 'available' } + ] + }, + salesTimeline: { + enabled: true, + phases: [ + { name: 'Early Bird Phase', phaseType: 'early_access', startsAt: nowIso, endsAt: futureIso, pricePaise: 150000 } + ] + }, + offers: [ + { name: '20% Mega Promo', code: 'SAVE20', discountType: 'percentage', discountValue: 20, minQuantity: 1 } + ] + }); + + const putRes = await org1.req('PUT', `/api/organiser/drafts/${draftId}`, { + data: fullDraft, + step: 'preview', + version + }); + assert.equal(putRes.status, 200, putRes.text); + + const pubRes = await org1.post(`/api/organiser/drafts/${draftId}/publish`, { + version: putRes.json.draft.version, + confirm: true + }); + assert.equal(pubRes.status, 200, pubRes.text); + const event = pubRes.json; + + const tier = await db.one('SELECT * FROM ticket_types WHERE event_id = $1', [event.eventId]); + const sec = await db.one('SELECT * FROM event_venue_sections WHERE event_id = $1', [event.eventId]); + const phase = await db.one('SELECT * FROM event_sales_phases WHERE event_id = $1', [event.eventId]); + + // Attendee books 1 ticket in VIP section under Early Bird phase with SAVE20 promo code + const checkoutRes = await attendee1.get( + `/checkout/${event.slug}/upi?ticketTypeId=${tier.id}§ionId=${sec.id}&phaseId=${phase.id}&promoCode=save20&quantity=1` + ); + + assert.equal(checkoutRes.status, 200, checkoutRes.text); + assert.match(checkoutRes.text, /₹1200\.00/); + assert.match(checkoutRes.text, /am=1200\.00/); + assert.match(checkoutRes.text, /20% Mega Promo/); + + // Retrieve booking and verify snapshot + const booking = await db.one( + `SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 ORDER BY created_at DESC LIMIT 1`, + [event.eventId, attendee1.userId] + ); + assert.equal(booking.amount_paise, 120000); // ₹1,200 + assert.equal(booking.discount_paise, 30000); // ₹300 + assert.equal(booking.section_id, sec.id); + assert.equal(booking.phase_id, phase.id); + + // Verify booking price snapshot + const snapshot = await db.one('SELECT * FROM booking_price_snapshots WHERE booking_id = $1', [booking.id]); + assert.ok(snapshot); + assert.equal(snapshot.base_price_paise, 200000); // VIP section base price + assert.equal(snapshot.subtotal_paise, 150000); // Early Bird phase override + assert.equal(snapshot.discount_paise, 30000); + assert.equal(snapshot.final_paise, 120000); + assert.equal(snapshot.offer_code, 'SAVE20'); +}); diff --git a/test/migrations.test.js b/test/migrations.test.js index 7e9a212..f1f7523 100644 --- a/test/migrations.test.js +++ b/test/migrations.test.js @@ -20,13 +20,13 @@ test('migration files inventory: sequential numbering, correct naming, and sorte .filter((f) => /^\d+_.*\.sql$/.test(f)) .sort(); - // Exactly 30 migrations currently exist: 003 through 032 - assert.equal(files.length, 30, `expected 30 migration files, got ${files.length}: ${files.join(', ')}`); + // Exactly 31 migrations currently exist: 003 through 033 + assert.equal(files.length, 31, `expected 31 migration files, got ${files.length}: ${files.join(', ')}`); // Verify sequential ordering const expectedPrefixes = [ '003_', '004_', '005_', '006_', '007_', '008_', - '009_', '010_', '011_', '012_', '013_', '014_', '015_', '016_', '017_', '018_', '019_', '020_', '021_', '022_', '023_', '024_', '025_', '026_', '027_', '028_', '029_', '030_', '031_', '032_' + '009_', '010_', '011_', '012_', '013_', '014_', '015_', '016_', '017_', '018_', '019_', '020_', '021_', '022_', '023_', '024_', '025_', '026_', '027_', '028_', '029_', '030_', '031_', '032_', '033_' ]; for (let i = 0; i < expectedPrefixes.length; i++) { assert.ok( @@ -45,9 +45,9 @@ test('migration idempotency: re-running migrate() on an up-to-date database appl assert.deepEqual(thirdRun, [], 'expected zero migrations applied on third run'); }); -test('schema_migrations table records all 30 migrations in correct order', async () => { +test('schema_migrations table records all 31 migrations in correct order', async () => { const { rows } = await db.query('SELECT name, applied_at FROM schema_migrations ORDER BY name ASC'); - assert.equal(rows.length, 30); + assert.equal(rows.length, 31); const appliedNames = rows.map((r) => r.name); const filesOnDisk = fs.readdirSync(MIGRATIONS_DIR) @@ -74,9 +74,9 @@ test('advisory lock serializes concurrent migrate() calls', async () => { assert.deepEqual(res2, []); assert.deepEqual(res3, []); - // Total count in schema_migrations must remain exactly 30 + // Total count in schema_migrations must remain exactly 31 const countRes = await db.one('SELECT count(*)::int AS n FROM schema_migrations'); - assert.equal(countRes.n, 30); + assert.equal(countRes.n, 31); }); test('migration policy respects environment boundaries', () => { @@ -587,3 +587,48 @@ test('migration 032: direct organiser upi payments schema objects exist', async assert.ok(auditCols.includes('actor_user_id'), 'direct_upi_payment_audits must have actor_user_id'); assert.ok(auditCols.includes('to_status'), 'direct_upi_payment_audits must have to_status'); }); + +test('migration 033: advanced event configuration schema objects exist', async () => { + const eventCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'events'` + )).rows.map((r) => r.column_name); + assert.ok(eventCols.includes('has_facilities'), 'events must have has_facilities'); + assert.ok(eventCols.includes('has_venue_layout'), 'events must have has_venue_layout'); + assert.ok(eventCols.includes('has_sales_phases'), 'events must have has_sales_phases'); + assert.ok(eventCols.includes('has_offers'), 'events must have has_offers'); + + const facilityCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'event_facilities'` + )).rows.map((r) => r.column_name); + assert.ok(facilityCols.includes('category'), 'event_facilities must have category'); + assert.ok(facilityCols.includes('facility_key'), 'event_facilities must have facility_key'); + assert.ok(facilityCols.includes('name'), 'event_facilities must have name'); + + const sectionCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'event_venue_sections'` + )).rows.map((r) => r.column_name); + assert.ok(sectionCols.includes('layout_id'), 'event_venue_sections must have layout_id'); + assert.ok(sectionCols.includes('price_paise'), 'event_venue_sections must have price_paise'); + assert.ok(sectionCols.includes('capacity'), 'event_venue_sections must have capacity'); + + const phaseCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'event_sales_phases'` + )).rows.map((r) => r.column_name); + assert.ok(phaseCols.includes('starts_at'), 'event_sales_phases must have starts_at'); + assert.ok(phaseCols.includes('ends_at'), 'event_sales_phases must have ends_at'); + assert.ok(phaseCols.includes('price_paise'), 'event_sales_phases must have price_paise'); + + const offerCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'event_offers'` + )).rows.map((r) => r.column_name); + assert.ok(offerCols.includes('discount_type'), 'event_offers must have discount_type'); + assert.ok(offerCols.includes('discount_value'), 'event_offers must have discount_value'); + assert.ok(offerCols.includes('code'), 'event_offers must have code'); + + const snapshotCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'booking_price_snapshots'` + )).rows.map((r) => r.column_name); + assert.ok(snapshotCols.includes('booking_id'), 'booking_price_snapshots must have booking_id'); + assert.ok(snapshotCols.includes('final_paise'), 'booking_price_snapshots must have final_paise'); + assert.ok(snapshotCols.includes('subtotal_paise'), 'booking_price_snapshots must have subtotal_paise'); +});