Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/handlers/organiser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 }
};
}
Expand Down
14 changes: 11 additions & 3 deletions lib/handlers/upi-checkout.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -78,14 +78,22 @@ 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) {
order = await createDirectUpiBooking({
slug,
user,
ticketTypeId: tier.id,
quantity: qty
quantity: qty,
sectionId,
phaseId,
promoCode,
accessCode
});
} else {
order = await createUpiPaymentIntent({
Expand Down
2 changes: 1 addition & 1 deletion lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 || {}) }
Expand Down
126 changes: 114 additions & 12 deletions lib/services/direct-upi.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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.');
Expand Down Expand Up @@ -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',
Expand All @@ -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',
Expand All @@ -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);

Expand All @@ -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,
Expand All @@ -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 (
Expand All @@ -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()}`;
Expand Down Expand Up @@ -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."
};
}
Expand Down Expand Up @@ -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 (
Expand Down
112 changes: 112 additions & 0 deletions lib/services/event-facilities.js
Original file line number Diff line number Diff line change
@@ -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);
}
Loading
Loading