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
123 changes: 123 additions & 0 deletions e2e/test-publish-upi.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// e2e/test-publish-upi.spec.js
import { test, expect } from '@playwright/test';
import { signInAs, expectAccessible, expectNoHorizontalOverflow } from './helpers.js';

test('verify facilities redesign and direct upi publishing', async ({ page }) => {
await signInAs(page, 'organiser');
await page.goto('/organiser/new?fresh=1');

// Start draft
await page.getByRole('button', { name: /Party or nightlife/ }).click();
await expect(page.locator('#f-title')).toBeVisible();

// Step 1: Basics
const title = `The Saturday Night Social ${Date.now()}`;
await page.locator('#f-title').fill(title);
await page.locator('#f-city').fill('Bengaluru');
await page.locator('#f-area').fill('Indiranagar');
await page.locator('#f-venue').fill('Secret Warehouse Indiranagar');

const tmrw = new Date(Date.now() + 864e5).toISOString().slice(0, 10);
await page.locator('#f-startLocal').fill(`${tmrw}T20:00`);
await page.locator('#f-endLocal').fill(`${tmrw}T23:00`);

await page.locator('#f-description').fill('Amazing direct UPI party with great music, visual effects and fun people. 21+ only.');
const rightsCheckbox = page.locator('#f-imageRightsConfirmed');
if (await rightsCheckbox.isVisible()) {
await rightsCheckbox.check();
}

// Step 2: Tickets
await page.getByRole('button', { name: /Next: Tickets/ }).click();
await expect(page.locator('input[value="direct_upi"]')).toBeVisible();

await page.locator('input[value="direct_upi"]').check();
await expect(page.locator('#f-organiserUpiId')).toBeVisible();

await page.locator('#f-organiserUpiId').fill('organiser@okaxis');
await page.locator('#f-organiserPayeeName').fill('Party Host');

const kindSelect = page.locator('select[data-path="tickets.0.kind"]');
await expect(kindSelect).toBeVisible();
await kindSelect.selectOption('paid');

const priceInput = page.locator('input[data-path="tickets.0.pricePaise"]');
await expect(priceInput).toBeVisible();
await priceInput.fill('499');

// Step 3: Features
await page.getByRole('button', { name: /Next: Features/ }).click();
await expect(page.getByRole('heading', { name: /Facilities & amenities/i })).toBeVisible();

// Verify all 5 categories exist
await expect(page.getByRole('heading', { name: 'Parking', exact: true })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Food & Beverages', exact: true })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Accessibility', exact: true })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Medical & Safety', exact: true })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Other Facilities & Rules', exact: true })).toBeVisible();

// Test individual facility card toggle
const valetParking = page.locator('[data-act="toggle-facility"][data-key="valet_parking"]');
await expect(valetParking).toBeVisible();
await valetParking.click();
await expect(valetParking).toHaveClass(/is-selected/);
await expect(valetParking).toHaveAttribute('aria-checked', 'true');

// Test "Select all" in Parking category
const selectAllParking = page.locator('[data-act="select-all-cat"][data-cat="parking"]');
await selectAllParking.click();
const parkingSelected = page.locator('.facility-category-section:has-text("Parking") [aria-checked="true"]');
expect(await parkingSelected.count()).toBe(5);

// Test "Clear" in Parking category
const clearParking = page.locator('[data-act="clear-cat"][data-cat="parking"]');
await clearParking.click();
expect(await parkingSelected.count()).toBe(0);

// Toggle specific amenities across categories
await page.locator('[data-act="toggle-facility"][data-key="free_parking"]').click();
await page.locator('[data-act="toggle-facility"][data-key="alcohol_available"]').click();
await page.locator('[data-act="toggle-facility"][data-key="wheelchair_accessible"]').click();
await page.locator('[data-act="toggle-facility"][data-key="first_aid"]').click();

// Add custom amenity
await page.locator('#custom-fac-name').fill('Rooftop Swimming Pool');
await page.locator('#custom-fac-desc').fill('Complimentary towel service provided');
await page.locator('button[data-act="add-custom-facility"]').click();
await expect(page.locator('.custom-facility-item')).toContainText('Rooftop Swimming Pool');

// Take screenshot of redesigned Facilities UI
await page.screenshot({ path: 'test-results/facilities-redesign.png', fullPage: false });
await expectNoHorizontalOverflow(page);
await expectAccessible(page);

// Step 4: Preview
await page.getByRole('button', { name: /^Next/ }).click();
await expect(page.getByRole('button', { name: /Publish Event/i })).toBeVisible();

// Click Publish Event to open dialog
await page.getByRole('button', { name: /Publish Event/i }).click();

const dialog = page.locator('[data-publish-dialog]');
await expect(dialog).toBeVisible();
await expect(dialog.getByRole('heading', { name: /Publish event/i })).toBeVisible();
await expect(dialog).toContainText('organiser@okaxis');
await expect(dialog).toContainText('Party Host');

// Take screenshot of confirmation dialog
await page.screenshot({ path: 'test-results/publish-dialog.png' });

// Click Publish Event Now
const confirmBtn = dialog.locator('[data-act="publish-confirm"]');
await expect(confirmBtn).toBeVisible();
await confirmBtn.click();

// Wait for published state
await expect(page.locator('.wz-done')).toBeVisible({ timeout: 10000 });
await expect(page.locator('.wz-done h1')).toContainText('Your event is live');

// Take screenshot of published confirmation
await page.screenshot({ path: 'test-results/event-published.png' });
await expectNoHorizontalOverflow(page);
await expectAccessible(page);
});
16 changes: 11 additions & 5 deletions lib/services/event-offers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import { db } from '../db.js';
import { HttpError } from '../http.js';

export async function saveEventOffers(c, eventId, offers = []) {
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export async function saveEventOffers(c, eventId, offers = [], tierMapping = {}) {
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]);
Expand All @@ -25,10 +27,14 @@ export async function saveEventOffers(c, eventId, offers = []) {
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 tierIds = Array.isArray(o.applicableTierIds)
? o.applicableTierIds.map((tid) => tierMapping[tid] || tid).filter((tid) => typeof tid === 'string' && UUID_REGEX.test(tid))
: [];
const phaseIds = Array.isArray(o.applicablePhaseIds)
? o.applicablePhaseIds.filter((pid) => typeof pid === 'string' && UUID_REGEX.test(pid))
: [];
const startsAt = o.startsAt && !isNaN(new Date(o.startsAt).getTime()) ? new Date(o.startsAt) : null;
const expiresAt = o.expiresAt && !isNaN(new Date(o.expiresAt).getTime()) ? 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;
Expand Down
5 changes: 4 additions & 1 deletion lib/services/event-venue.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import { db } from '../db.js';
import { HttpError } from '../http.js';

const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export const SECTION_PRESETS = {
stage: { name: 'Stage', color: '#1f2937', category: 'stage', shape: 'rect' },
general: { name: 'General Admission / Standing', color: '#3b82f6', category: 'general', shape: 'rect' },
Expand Down Expand Up @@ -51,7 +53,8 @@ export async function saveEventVenueLayout(c, eventId, layoutConfig = {}, sectio
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 rawTier = tierMapping[sectionKey] || s.ticketTypeId || null;
const ticketTypeId = typeof rawTier === 'string' && UUID_REGEX.test(rawTier) ? rawTier : null;

const secRow = (await c.query(
`INSERT INTO event_venue_sections (
Expand Down
65 changes: 44 additions & 21 deletions lib/services/organiser.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// A draft is JSON in event_drafts. It is never visible publicly: public queries read `events`,
// and an events row is only created by publishDraft() after an explicit, confirmed request.
import crypto from 'node:crypto';
import { logger } from '../logger.js';
import { db } from '../db.js';
import { HttpError } from '../http.js';
import { z, parse } from '../validate.js';
Expand Down Expand Up @@ -149,16 +150,18 @@ export const DraftData = z.object({
schedule: EventScheduleDraft.optional(),
tickets: z.array(TicketDraft).max(MAX_TIERS).optional(),
facilities: z.array(z.object({
category: z.string().max(40),
category: z.string().max(40).optional(),
facilityKey: z.string().max(80).optional(),
key: z.string().max(80).optional(),
name: z.string().max(100),
description: text(500),
icon: text(50),
description: z.string().max(500).nullable().optional(),
icon: z.string().max(50).nullable().optional(),
isCustom: flag
}).passthrough()).max(60).optional(),
offers: z.array(z.object({
id: z.string().max(60).optional(),
name: z.string().max(80),
description: text(500),
description: z.string().max(500).nullable().optional(),
code: text(30),
discountType: z.enum(['percentage', 'fixed_amount']),
discountValue: z.coerce.number().int(),
Expand All @@ -177,7 +180,8 @@ export const DraftData = z.object({
canvasWidth: looseInt,
canvasHeight: looseInt,
sections: z.array(z.object({
sectionKey: z.string().max(60),
id: z.string().max(60).optional(),
sectionKey: z.string().max(60).optional(),
name: z.string().max(80),
category: z.string().max(40).optional(),
color: text(20),
Expand All @@ -196,6 +200,7 @@ export const DraftData = z.object({
salesTimeline: z.object({
enabled: flag,
phases: z.array(z.object({
id: z.string().max(60).optional(),
name: z.string().max(80),
startsAt: text(40),
endsAt: text(40),
Expand Down Expand Up @@ -514,20 +519,20 @@ export function publishIssues(d, { checkout = ticketCheckoutStatus(), now = new
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.`);
err('features', `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 (!clean(o.name)) err('features', `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.`);
err('features', `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%.`);
err('features', `offers.${idx}.discountValue`, `${clean(o.name) || 'Offer'}: Percentage discount cannot exceed 100%.`);
}
});
}
Expand All @@ -536,19 +541,19 @@ export function publishIssues(d, { checkout = ticketCheckoutStatus(), now = new
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.');
err('features', '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.`);
if (!clean(s.name)) err('features', `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 (!clean(p.name)) err('features', `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.`);
err('features', `salesTimeline.phases.${idx}.endsAt`, `Phase "${clean(p.name)}": End time must be after start time.`);
}
});
}
Expand Down Expand Up @@ -868,7 +873,8 @@ export async function publishDraft(user, draftId, { version, confirm }) {
if (confirm !== true) throw new HttpError(400, 'confirm_required', 'Publishing needs explicit confirmation.');
await requireOrganiser(user);
const checkout = ticketCheckoutStatus();
const result = await db.tx(async (c) => {
try {
const result = await db.tx(async (c) => {
const draft = (await c.query('SELECT * FROM event_drafts WHERE id = $1 AND organiser_user_id = $2 FOR UPDATE', [draftId, user.id])).rows[0];
if (!draft) throw new HttpError(404, 'not_found', 'Draft not found');
if (draft.status !== 'active') throw new HttpError(409, 'draft_closed', draft.status === 'published' ? 'This draft has already been published.' : 'This draft was discarded.');
Expand Down Expand Up @@ -1011,34 +1017,37 @@ export async function publishDraft(user, draftId, { version, confirm }) {
}
}

const tierIdMap = {};
for (const [i, t] of tickets.entries()) {
const admitCount = Number.isInteger(t.admitCount) && t.admitCount > 0 ? t.admitCount : (t.category === 'couple' ? 2 : t.category === 'group' ? 4 : 1);
const minPerBooking = Number.isInteger(t.minPerBooking) && t.minPerBooking > 0 ? t.minPerBooking : 1;
const category = clean(t.category) || 'general';
const targetSessionId = t.sessionId || (t.validOn && sessionMap.get(t.validOn)) || null;
await c.query(
const salesStartAt = t.salesStartAt && !isNaN(new Date(t.salesStartAt).getTime()) ? new Date(t.salesStartAt) : null;
const salesEndAt = t.salesEndAt && !isNaN(new Date(t.salesEndAt).getTime()) ? new Date(t.salesEndAt) : null;
const tRow = (await c.query(
`INSERT INTO ticket_types (
event_id, name, kind, price_paise, quantity, max_per_booking, min_per_booking,
valid_on, eligibility, sort_order, category, admit_count, sales_start_at, sales_end_at, session_id
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING id`,
[ev.id, clean(t.name), t.kind, t.kind === 'free' ? 0 : t.pricePaise, t.quantity, t.maxPerBooking || 1,
minPerBooking, t.validOn && t.validOn !== 'all' ? t.validOn : null,
f.balance?.enabled || clean(t.eligibility) ? clean(t.eligibility) || null : null,
i, category, admitCount, t.salesStartAt ? new Date(t.salesStartAt) : null,
t.salesEndAt ? new Date(t.salesEndAt) : null, targetSessionId]);
i, category, admitCount, salesStartAt, salesEndAt, targetSessionId])).rows[0];
if (t.id && tRow?.id) tierIdMap[t.id] = tRow.id;
}

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);
await saveEventOffers(c, ev.id, d.offers, tierIdMap);
}
if (d.salesTimeline?.enabled && Array.isArray(d.salesTimeline.phases) && d.salesTimeline.phases.length > 0) {
await saveEventSalesPhases(c, ev.id, d.salesTimeline.phases);
await saveEventSalesPhases(c, ev.id, d.salesTimeline.phases, tierIdMap);
}
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);
await saveEventVenueLayout(c, ev.id, d.venueLayout, d.venueLayout.sections, tierIdMap);
}

if (imageIds.length) await c.query(`UPDATE event_images SET is_public = true WHERE id = ANY($1)`, [imageIds]);
Expand All @@ -1055,6 +1064,20 @@ export async function publishDraft(user, draftId, { version, confirm }) {
invalidatePublicEventCache();
const path = `${isTripCategory(result.category) ? '/trips' : '/events'}/${result.slug}`;
return { eventId: result.id, slug: result.slug, path, url: `${siteUrl()}${path}`, manageUrl: `/organiser/events/${result.id}` };
} catch (err) {
if (err instanceof HttpError) throw err;
logger.error('publishDraft transaction failed', err, { draftId, userId: user.id });
if (err.code === '23505') {
throw new HttpError(422, 'duplicate_entry', 'An event with this title or configuration already exists. Please adjust and try again.');
}
if (err.code === '23503') {
throw new HttpError(422, 'reference_error', 'A linked resource could not be verified. Please review images and venue details.');
}
if (err.code === '23514') {
throw new HttpError(422, 'constraint_violation', 'One or more event parameters violates system constraints. Please check ticket limits and dates.');
}
throw new HttpError(422, 'publish_failed', err.message || 'Event publishing could not be completed. Please review your details and try again.');
}
}

// ---------- organiser's events ----------
Expand Down
Loading
Loading