diff --git a/e2e/multi-role-acceptance.spec.js b/e2e/multi-role-acceptance.spec.js index 4342975..91f3e5a 100644 --- a/e2e/multi-role-acceptance.spec.js +++ b/e2e/multi-role-acceptance.spec.js @@ -158,29 +158,25 @@ test.describe('Milestone 9 Multi-Role E2E Acceptance Suite', () => { // =================================================================================== // 4. Venue / Business Owner Journey // =================================================================================== - test('Role 4: Venue Owner - listing submission, org isolation, and venue data protection', async ({ page }, testInfo) => { - // A. Visit /list-your-venue + test('Role 4: Venue Owner - self-service entry, org isolation, and venue data protection', async ({ page }, testInfo) => { + // A. Visit /list-your-venue self-service landing page await page.goto('/list-your-venue'); await expectNoHorizontalOverflow(page); await expectAccessible(page); await expect(page.getByRole('heading', { name: /List Your Venue/i })).toBeVisible(); - // B. Submit Venue Lead Form (AJAX submission) - await page.fill('input[name="name"]', 'Deepak Verma'); - await page.fill('input[name="venue_name"]', 'Skyline Terrace Lounge'); - await page.fill('input[name="email"]', 'deepak@skyline.in'); - await page.fill('input[name="city"]', 'Hyderabad'); - await page.fill('textarea[name="message"]', 'Premium rooftop lounge with 150 capacity, sound system, and cocktail bar.'); - await page.check('input[name="consent"]'); - - await page.locator('form[action="/api/leads/venue"] button[type="submit"]').click(); - await expect(page.locator('form[action="/api/leads/venue"] .form-msg')).toBeVisible({ timeout: 5000 }); - await expect(page.locator('form[action="/api/leads/venue"] .form-msg')).toContainText(/thank you|details/i); + // Verify self-service CTAs exist and old manual lead form is removed + await expect(page.locator('#ctaGetStarted')).toBeVisible(); + await expect(page.locator('#ctaSignIn')).toBeVisible(); + await expect(page.locator('form[action="/api/leads/venue"]')).toHaveCount(0); + await expect(page.locator('input[name="consent"]')).toHaveCount(0); - // Test Venue Received Confirmation Screen - await page.goto('/list-your-venue?sent=1'); - await expectNoHorizontalOverflow(page); - await expect(page.getByRole('heading', { name: /Thank you/i })).toBeVisible(); + // B. Direct Onboarding Entry for Authenticated User without Venue + await signInAs(page, 'guest'); + await page.goto('/venue'); + await expect(page.locator('#venueOnboardForm')).toBeVisible(); + await expect(page.locator('.venue-onboard-title')).toContainText('Launch Your Venue on NIGHTLIFEZ'); + await expect(page.locator('#btnLaunchVenue')).toBeVisible(); // C. Sign In as Venue Owner Jai and Verify Multi-Org Boundary Isolation await signInAs(page, 'venue'); diff --git a/e2e/venue-dashboard.spec.js b/e2e/venue-dashboard.spec.js index 6ac04f4..f8768c5 100644 --- a/e2e/venue-dashboard.spec.js +++ b/e2e/venue-dashboard.spec.js @@ -152,9 +152,9 @@ test.describe('NIGHTLIFEZ Venue Owner Dashboard Full-Stack E2E Suite', () => { await signInAs(page, 'guest'); await page.goto('/venue'); - // 3. Must render onboarding application form, NOT venue command centre - await expect(page.locator('#venueApplyForm')).toBeVisible(); - await expect(page.locator('.venue-onboarding-intro')).toContainText('Turn quiet nights into curated, high-margin experiences'); + // 3. Must render self-service onboarding wizard, NOT venue command centre + await expect(page.locator('#venueOnboardForm')).toBeVisible(); + await expect(page.locator('.venue-onboard-title')).toContainText('Launch Your Venue on NIGHTLIFEZ'); await expect(page.locator('.venue-header')).not.toBeVisible(); }); diff --git a/lib/handlers/pages.js b/lib/handlers/pages.js index 4ce3e4d..54a35f6 100644 --- a/lib/handlers/pages.js +++ b/lib/handlers/pages.js @@ -10,6 +10,7 @@ import { CATEGORY_LABELS, CITIES } from '../services/events.js'; import { isOrganiser } from '../services/organiser.js'; +import { isVenueOperator } from '../services/venue.js'; import { isEventSaved } from '../services/saved-events.js'; import { renderHome } from '../views/home.js'; import { renderEvent } from '../views/event.js'; @@ -94,7 +95,14 @@ export async function cityPage({ res, params }) { sendHtml(res, 200, P.renderCity(city, events), { cache: PUBLIC_CACHE }); } -const FORM_BY_PATH = { '/partner-with-us': 'partner', '/become-a-host': 'host', '/list-your-venue': 'venue' }; +const FORM_BY_PATH = { '/partner-with-us': 'partner', '/become-a-host': 'host' }; + +export async function listYourVenuePage({ req, res }) { + const user = req ? await getSessionUser(req).catch(() => null) : null; + const isOperator = user ? await isVenueOperator(user).catch(() => false) : false; + const html = P.renderListYourVenuePage({ user, isOperator }); + sendHtml(res, 200, html, user ? { cache: 'private, no-cache' } : { cache: PUBLIC_CACHE }); +} export async function formPage({ req, res, pathname, query }) { const type = FORM_BY_PATH[pathname.replace(/\/$/, '')]; diff --git a/lib/handlers/venue.js b/lib/handlers/venue.js index 46c83e1..e28ff67 100644 --- a/lib/handlers/venue.js +++ b/lib/handlers/venue.js @@ -59,6 +59,8 @@ export async function venueProfileApi(ctx) { const VenueProfilePatch = z.object({ name: z.string().trim().min(2).max(120).optional(), + category: z.string().trim().max(60).nullable().optional(), + neighbourhood: z.string().trim().max(120).nullable().optional(), capacity: z.number().int().positive().max(100_000).nullable().optional(), address_public: z.string().trim().max(300).nullable().optional(), address_private: z.string().trim().max(500).nullable().optional(), @@ -72,7 +74,7 @@ const VenueProfilePatch = z.object({ operating_hours: z.record(z.string()).optional(), contact_name: z.string().trim().max(120).nullable().optional(), contact_phone: z.string().trim().max(30).nullable().optional(), - contact_email: z.string().trim().email().nullable().optional(), + contact_email: z.string().trim().email().or(z.literal('')).nullable().optional(), rules: z.string().trim().max(2000).nullable().optional() }).strict().refine((b) => Object.keys(b).length > 0, { message: 'No fields to update' }); @@ -205,7 +207,46 @@ export async function submitVenueReportApi(ctx) { sendJson(ctx.res, 201, { ok: true, report }); } -// ---------- Application API ---------- +// ---------- Self-Service Onboarding & Direct Creation API ---------- + +const OnboardVenueBody = z.object({ + name: z.string().trim().min(2).max(160).optional(), + category: z.string().trim().max(60).nullable().optional(), + description: z.string().trim().max(3000).nullable().optional(), + city: z.string().trim().min(2).max(80).optional(), + city_id: z.string().uuid().optional(), + neighbourhood: z.string().trim().max(120).nullable().optional(), + address_public: z.string().trim().max(300).nullable().optional(), + address_private: z.string().trim().max(500).nullable().optional(), + capacity: z.coerce.number().int().min(1).max(50_000).optional(), + contact_name: z.string().trim().max(120).nullable().optional(), + contact_phone: z.string().trim().max(30).nullable().optional(), + contact_email: z.string().trim().email().max(160).or(z.literal('')).nullable().optional(), + facilities: z.array(z.string().trim().max(60)).optional(), + operating_hours: z.union([z.string().max(1000), z.record(z.string())]).optional(), + photos: z.array(z.union([z.string().url(), z.object({ url: z.string().url(), caption: z.string().optional() })])).optional(), + rules: z.string().trim().max(2000).nullable().optional(), + is_draft: z.boolean().optional(), + venue_id: z.string().uuid().optional(), + onboarding_step: z.number().int().min(1).max(5).optional() +}).strict(); + +export async function onboardVenueApi(ctx) { + const user = await writer(ctx); + const body = parse(OnboardVenueBody, await readJson(ctx.req)); + const result = await V.onboardVenue(user, body); + sendJson(ctx.res, 201, { + ok: true, + message: result.isDraft ? 'Venue progress saved' : 'Venue profile launched successfully', + venue: result.venue, + completionPercentage: result.completionPercentage, + missingFields: result.missingFields, + isDraft: result.isDraft, + redirect: '/venue' + }); +} + +// ---------- Legacy Application Compatibility API (Direct Onboarding) ---------- const ApplyVenueBody = z.object({ name: z.string().trim().min(2).max(120), @@ -222,6 +263,56 @@ const ApplyVenueBody = z.object({ export async function applyVenueApi(ctx) { const user = await writer(ctx); const body = parse(ApplyVenueBody, await readJson(ctx.req)); - const lead = await V.applyForVenue(user, body); - sendJson(ctx.res, 201, { ok: true, message: 'Application submitted for review', leadId: lead.id }); + const onboardData = { + name: body.venue_name || body.name, + contact_name: body.name, + contact_email: body.email, + contact_phone: body.phone, + city: body.city, + neighbourhood: body.area, + address_public: body.area ? `${body.area}, ${body.city}` : body.city, + capacity: body.capacity || 50, + description: body.message, + facilities: body.facilities || [] + }; + const result = await V.onboardVenue(user, onboardData); + sendJson(ctx.res, 201, { + ok: true, + message: 'Venue profile launched successfully', + venue: result.venue, + venueId: result.venue.id, + leadId: result.venue.id, + redirect: '/venue' + }); +} + +// ---------- Self-Service Ownership Claim & Recovery API ---------- + +const SubmitClaimBody = z.object({ + venue_id: z.string().uuid(), + claimant_role: z.string().trim().min(2).max(100), + business_proof_type: z.enum(['gstin', 'fssai_license', 'utility_bill', 'official_domain_email', 'corporate_deed', 'other']), + business_proof_ref: z.string().trim().min(2).max(120), + contact_name: z.string().trim().min(2).max(120), + contact_email: z.string().trim().email().max(160), + contact_phone: z.string().trim().max(30).optional(), + notes: z.string().trim().max(2000).optional() +}).strict(); + +export async function submitVenueClaimApi(ctx) { + const user = await writer(ctx); + const body = parse(SubmitClaimBody, await readJson(ctx.req)); + const result = await V.submitVenueClaim(user, body); + sendJson(ctx.res, 201, { + ok: true, + message: result.message, + claim: result.claim, + venue: result.venue + }); +} + +export async function listVenueClaimsApi(ctx) { + const user = await requireUser(ctx.req); + const claims = await V.getVenueClaims(user); + sendJson(ctx.res, 200, { ok: true, claims }); } diff --git a/lib/router.js b/lib/router.js index 8b6bb74..b910f00 100644 --- a/lib/router.js +++ b/lib/router.js @@ -23,7 +23,7 @@ const ROUTES = [ ['GET', '/meetups/:city', h('pages', 'cityPage')], ['GET', '/partner-with-us', h('pages', 'formPage')], ['GET', '/become-a-host', h('pages', 'formPage')], - ['GET', '/list-your-venue', h('pages', 'formPage')], + ['GET', '/list-your-venue', h('pages', 'listYourVenuePage')], ['GET', '/faq', h('pages', 'staticPage')], ['GET', '/trust-safety', h('pages', 'staticPage')], ['GET', '/community-guidelines', h('pages', 'staticPage')], @@ -178,7 +178,10 @@ const ROUTES = [ ['PATCH', '/api/venue/staff/:memberId', h('venue', 'updateVenueStaffApi')], ['GET', '/api/venue/reports', h('venue', 'venueReportsApi')], ['POST', '/api/venue/reports', h('venue', 'submitVenueReportApi')], + ['POST', '/api/venue/onboard', h('venue', 'onboardVenueApi')], ['POST', '/api/venue/apply', h('venue', 'applyVenueApi')], + ['POST', '/api/venue/claim', h('venue', 'submitVenueClaimApi')], + ['GET', '/api/venue/claims', h('venue', 'listVenueClaimsApi')], // Organiser (session + organiser access; drafts and events are owner-scoped) ['GET', '/api/organiser/context', h('organiser', 'context')], diff --git a/lib/services/venue.js b/lib/services/venue.js index e76e51b..9eae18e 100644 --- a/lib/services/venue.js +++ b/lib/services/venue.js @@ -21,6 +21,39 @@ export const VENUE_FACILITIES = [ { id: 'wifi_highspeed', label: 'High-Speed Wi-Fi', icon: '📶' } ]; +export const VENUE_CATEGORIES = [ + { id: 'rooftop_lounge', label: 'Rooftop Lounge & Skybar' }, + { id: 'cocktail_speakeasy', label: 'Cocktail Bar & Speakeasy' }, + { id: 'nightclub', label: 'Nightclub & Dance Venue' }, + { id: 'cafe_bistro', label: 'Café & Intimate Bistro' }, + { id: 'studio_loft', label: 'Art Studio & Creative Loft' }, + { id: 'resort_farmhouse', label: 'Resort, Villa & Farmhouse' }, + { id: 'brewery_pub', label: 'Microbrewery & Social Pub' }, + { id: 'event_space', label: 'Boutique Event Space' } +]; + +/** + * Calculates profile strength percentage and identifies missing fields for completion tracking. + */ +export function calculateProfileStrength(venue) { + let score = 0; + const missing = []; + if (venue.name?.trim()) score += 15; else missing.push('name'); + if (venue.category?.trim()) score += 15; else missing.push('category'); + if (venue.description?.trim()) score += 10; else missing.push('description'); + if (venue.address_public?.trim() || venue.addressPublic?.trim() || venue.city_id || venue.cityId) score += 20; else missing.push('location'); + if (venue.capacity && Number(venue.capacity) > 0) score += 10; else missing.push('capacity'); + const facs = Array.isArray(venue.facilities) ? venue.facilities : []; + if (facs.length > 0) score += 10; else missing.push('facilities'); + const photos = Array.isArray(venue.photos) ? venue.photos : []; + if (photos.length > 0) score += 10; else missing.push('photos'); + const hours = venue.operating_hours || venue.operatingHours; + const hasHours = hours && typeof hours === 'object' && Object.keys(hours).length > 0; + if (hasHours) score += 5; else missing.push('operating_hours'); + if (venue.contact_email?.trim() || venue.contactEmail?.trim() || venue.contact_phone?.trim() || venue.contactPhone?.trim()) score += 5; else missing.push('contact'); + return { percentage: Math.min(100, score), missing }; +} + /** * Returns whether user is an active venue operator (or super admin). */ @@ -36,8 +69,10 @@ export async function isVenueOperator(user, c = db) { const row = (await c.query( `SELECT 1 FROM org_memberships m JOIN organisations o ON o.id = m.org_id + JOIN venues v ON v.org_id = o.id WHERE m.user_id = $1 AND m.status = 'active' AND o.status = 'active' - AND o.kind = 'venue_operator' LIMIT 1`, + AND v.status = 'active' AND v.onboarding_completed = true + LIMIT 1`, [user.id] )).rows[0]; return Boolean(row); @@ -72,7 +107,7 @@ export async function getVenueContext(user, requestedVenueId = null, c = db) { FROM org_memberships m JOIN organisations o ON o.id = m.org_id WHERE m.user_id = $1 AND m.status = 'active' AND o.status = 'active' - AND o.kind = 'venue_operator' + AND (o.kind = 'venue_operator' OR EXISTS (SELECT 1 FROM venues v WHERE v.org_id = o.id AND v.status = 'active')) ORDER BY o.name`, [user.id] )).rows; @@ -80,35 +115,89 @@ export async function getVenueContext(user, requestedVenueId = null, c = db) { const orgIds = orgRows.map((o) => o.id); let venues = []; + let draftVenue = null; + if (isSuperAdmin) { const vRes = await c.query( - `SELECT v.id, v.org_id, v.name, v.capacity, v.status, v.address_public, v.address_private, - v.city_id, c.name AS city_name, v.locality_id, l.name AS locality_name, - v.photos, v.facilities, v.operating_hours, v.contact_name, v.contact_phone, v.contact_email, - v.created_at, o.name AS org_name, o.verified_at IS NOT NULL AS org_verified + `SELECT v.id, v.org_id, v.name, v.category, v.neighbourhood, v.capacity, v.status, + v.address_public, v.address_private, v.city_id, c.name AS city_name, + v.locality_id, l.name AS locality_name, v.photos, v.facilities, + v.operating_hours, v.contact_name, v.contact_phone, v.contact_email, + v.rules, v.onboarding_completed, v.created_at, o.name AS org_name, + o.verified_at IS NOT NULL AS org_verified FROM venues v JOIN organisations o ON o.id = v.org_id LEFT JOIN location_cities c ON c.id = v.city_id LEFT JOIN location_localities l ON l.id = v.locality_id - WHERE v.status = 'active' + WHERE v.status = 'active' AND v.onboarding_completed = true ORDER BY v.name` ); venues = vRes.rows; } else if (orgIds.length > 0) { const vRes = await c.query( - `SELECT v.id, v.org_id, v.name, v.capacity, v.status, v.address_public, v.address_private, - v.city_id, c.name AS city_name, v.locality_id, l.name AS locality_name, - v.photos, v.facilities, v.operating_hours, v.contact_name, v.contact_phone, v.contact_email, - v.created_at, o.name AS org_name, o.verified_at IS NOT NULL AS org_verified + `SELECT v.id, v.org_id, v.name, v.category, v.neighbourhood, v.capacity, v.status, + v.address_public, v.address_private, v.city_id, c.name AS city_name, + v.locality_id, l.name AS locality_name, v.photos, v.facilities, + v.operating_hours, v.contact_name, v.contact_phone, v.contact_email, + v.rules, v.onboarding_completed, v.created_at, o.name AS org_name, + o.verified_at IS NOT NULL AS org_verified FROM venues v JOIN organisations o ON o.id = v.org_id LEFT JOIN location_cities c ON c.id = v.city_id LEFT JOIN location_localities l ON l.id = v.locality_id - WHERE v.org_id = ANY($1::uuid[]) AND v.status = 'active' + WHERE v.org_id = ANY($1::uuid[]) AND v.status = 'active' AND v.onboarding_completed = true ORDER BY v.name`, [orgIds] ); venues = vRes.rows; + + const draftRes = await c.query( + `SELECT v.id, v.org_id, v.name, v.category, v.neighbourhood, v.capacity, v.status, + v.address_public, v.address_private, v.city_id, c.name AS city_name, + v.locality_id, l.name AS locality_name, v.photos, v.facilities, + v.operating_hours, v.contact_name, v.contact_phone, v.contact_email, + v.rules, v.onboarding_completed, v.onboarding_step, v.created_at, v.updated_at, + o.name AS org_name, o.verified_at IS NOT NULL AS org_verified + FROM venues v + JOIN organisations o ON o.id = v.org_id + LEFT JOIN location_cities c ON c.id = v.city_id + LEFT JOIN location_localities l ON l.id = v.locality_id + WHERE v.org_id = ANY($1::uuid[]) AND (v.status = 'draft' OR v.onboarding_completed = false) + ORDER BY v.updated_at DESC + LIMIT 1`, + [orgIds] + ); + if (draftRes.rows[0]) { + const d = draftRes.rows[0]; + draftVenue = { + id: d.id, + orgId: d.org_id, + orgName: d.org_name, + orgVerified: d.org_verified, + name: d.name, + category: d.category || null, + neighbourhood: d.neighbourhood || null, + capacity: d.capacity, + cityId: d.city_id, + cityName: d.city_name, + localityId: d.locality_id, + localityName: d.locality_name, + addressPublic: d.address_public, + addressPrivate: d.address_private, + photos: d.photos || [], + facilities: d.facilities || [], + operatingHours: d.operating_hours || {}, + contactName: d.contact_name, + contactPhone: d.contact_phone, + contactEmail: d.contact_email, + rules: d.rules, + status: d.status, + onboardingCompleted: Boolean(d.onboarding_completed), + onboardingStep: d.onboarding_step || 1, + profileStrength: calculateProfileStrength(d), + updatedAt: d.updated_at + }; + } } // Check for any submitted applications / leads by this user @@ -138,6 +227,7 @@ export async function getVenueContext(user, requestedVenueId = null, c = db) { userRole: isSuperAdmin ? 'owner' : (orgRows[0]?.role || null), orgs: orgRows.map((o) => ({ id: o.id, name: o.name, verified: Boolean(o.verified_at) })), venues: [], + draftVenue, activeVenueId: null, activeVenue: null, permissions: { @@ -185,11 +275,15 @@ export async function getVenueContext(user, requestedVenueId = null, c = db) { id: v.id, orgId: v.org_id, name: v.name, + category: v.category || null, + neighbourhood: v.neighbourhood || null, capacity: v.capacity, cityName: v.city_name, localityName: v.locality_name, - status: v.status + status: v.status, + onboardingCompleted: Boolean(v.onboarding_completed) })), + draftVenue, activeVenueId: activeVenue.id, activeVenue: { id: activeVenue.id, @@ -197,6 +291,8 @@ export async function getVenueContext(user, requestedVenueId = null, c = db) { orgName: activeVenue.org_name, orgVerified: activeVenue.org_verified, name: activeVenue.name, + category: activeVenue.category || null, + neighbourhood: activeVenue.neighbourhood || null, capacity: activeVenue.capacity, cityId: activeVenue.city_id, cityName: activeVenue.city_name, @@ -210,7 +306,10 @@ export async function getVenueContext(user, requestedVenueId = null, c = db) { contactName: activeVenue.contact_name, contactPhone: activeVenue.contact_phone, contactEmail: activeVenue.contact_email, - status: activeVenue.status + rules: activeVenue.rules, + status: activeVenue.status, + onboardingCompleted: Boolean(activeVenue.onboarding_completed), + profileStrength: calculateProfileStrength(activeVenue) }, permissions: { canManage, @@ -247,6 +346,8 @@ export async function getVenueProfile(venueId, user, c = db) { orgName: row.org_name, orgVerified: row.org_verified, name: row.name, + category: row.category || null, + neighbourhood: row.neighbourhood || null, capacity: row.capacity, cityId: row.city_id, cityName: row.city_name, @@ -265,6 +366,8 @@ export async function getVenueProfile(venueId, user, c = db) { contactEmail: row.contact_email, rules: row.rules, status: row.status, + onboardingCompleted: Boolean(row.onboarding_completed), + profileStrength: calculateProfileStrength(row), createdAt: row.created_at, updatedAt: row.updated_at }; @@ -281,6 +384,8 @@ export async function updateVenueProfile(venueId, user, patch, c = db) { const next = { name: patch.name !== undefined ? patch.name : cur.name, + category: patch.category !== undefined ? patch.category : cur.category, + neighbourhood: patch.neighbourhood !== undefined ? patch.neighbourhood : cur.neighbourhood, capacity: patch.capacity !== undefined ? patch.capacity : cur.capacity, city_id: patch.city_id !== undefined ? patch.city_id : cur.city_id, locality_id: patch.locality_id !== undefined ? patch.locality_id : cur.locality_id, @@ -300,18 +405,20 @@ export async function updateVenueProfile(venueId, user, patch, c = db) { const updated = (await tx.query( `UPDATE venues - SET name = $2, capacity = $3, city_id = $4, locality_id = $5, - address_public = $6, address_private = $7, lat = $8, lng = $9, - description = $10, photos = $11::jsonb, facilities = $12::jsonb, - operating_hours = $13::jsonb, contact_name = $14, contact_phone = $15, - contact_email = $16, rules = $17, updated_at = now() + SET name = $2, category = $3, neighbourhood = $4, capacity = $5, + city_id = $6, locality_id = $7, address_public = $8, + address_private = $9, lat = $10, lng = $11, description = $12, + photos = $13::jsonb, facilities = $14::jsonb, operating_hours = $15::jsonb, + contact_name = $16, contact_phone = $17, contact_email = $18, + rules = $19, updated_at = now() WHERE id = $1 RETURNING *`, [ - venueId, next.name, next.capacity, next.city_id, next.locality_id, - next.address_public, next.address_private, next.lat, next.lng, - next.description, next.photos, next.facilities, next.operating_hours, - next.contact_name, next.contact_phone, next.contact_email, next.rules + venueId, next.name, next.category, next.neighbourhood, next.capacity, + next.city_id, next.locality_id, next.address_public, next.address_private, + next.lat, next.lng, next.description, next.photos, next.facilities, + next.operating_hours, next.contact_name, next.contact_phone, next.contact_email, + next.rules ] )).rows[0]; @@ -326,8 +433,10 @@ export async function updateVenueProfile(venueId, user, patch, c = db) { */ export async function getVenueEvents(venueId, user, { filter = 'all' } = {}, c = db) { await authorize(user, 'venue.view_events', { venueId }, c); - const venue = (await c.query('SELECT name, capacity FROM venues WHERE id = $1', [venueId])).rows[0]; - if (!venue) throw new HttpError(404, 'not_found', 'Venue not found'); + const venue = (await c.query('SELECT name, capacity, status, onboarding_completed FROM venues WHERE id = $1', [venueId])).rows[0]; + if (!venue || venue.status !== 'active' || !venue.onboarding_completed) { + throw new HttpError(404, 'not_found', 'Venue not found or not published'); + } let timeClause = ''; if (filter === 'upcoming') { @@ -383,8 +492,10 @@ export async function getVenueEvents(venueId, user, { filter = 'all' } = {}, c = */ export async function getVenueAnalytics(venueId, user, c = db) { await authorize(user, 'venue.view_analytics', { venueId }, c); - const venue = (await c.query('SELECT name, capacity FROM venues WHERE id = $1', [venueId])).rows[0]; - if (!venue) throw new HttpError(404, 'not_found', 'Venue not found'); + const venue = (await c.query('SELECT name, capacity, status, onboarding_completed FROM venues WHERE id = $1', [venueId])).rows[0]; + if (!venue || venue.status !== 'active' || !venue.onboarding_completed) { + throw new HttpError(404, 'not_found', 'Venue not found or not published'); + } const stats = (await c.query( `SELECT @@ -480,8 +591,10 @@ export async function getVenueEnquiries(venueId, user, { status = 'all' } = {}, * Creates an organiser booking enquiry for a venue. */ export async function createVenueEnquiry(venueId, data, requesterUser = null, c = db) { - const venue = (await c.query('SELECT org_id FROM venues WHERE id = $1', [venueId])).rows[0]; - if (!venue) throw new HttpError(404, 'not_found', 'Venue not found'); + const venue = (await c.query('SELECT org_id, status, onboarding_completed FROM venues WHERE id = $1', [venueId])).rows[0]; + if (!venue || venue.status !== 'active' || !venue.onboarding_completed) { + throw new HttpError(404, 'not_found', 'Venue not found or not available for enquiries'); + } const row = (await c.query( `INSERT INTO venue_enquiries ( @@ -678,3 +791,385 @@ export async function applyForVenue(user, data, c = db) { await audit(`user:${user.id}`, 'venue.apply', row.id, { venueName: data.venue_name }, c); return row; } + +/** + * Direct self-service venue onboarding and profile setup. + * Supports complete publishing (status: active, onboarding_completed: true) + * as well as save-progress draft flow (is_draft: true). + */ +export async function onboardVenue(user, data, c = db) { + if (!user?.id) throw new HttpError(401, 'unauthorized', 'Please sign in'); + + const isDraft = Boolean(data.is_draft); + const name = data.name?.trim(); + if (!name && !isDraft) { + throw new HttpError(400, 'validation', 'Venue name is required'); + } + + return await c.tx(async (tx) => { + // 1. Resolve or create user's venue_operator organisation + let org = (await tx.query( + `SELECT o.id, o.name FROM organisations o + JOIN org_memberships m ON m.org_id = o.id + WHERE m.user_id = $1 AND m.role = 'owner' AND o.status = 'active' + AND (o.kind = 'venue_operator' OR o.kind = 'business') + ORDER BY o.created_at ASC + LIMIT 1`, + [user.id] + )).rows[0]; + + if (!org) { + const orgName = name ? `${name} Management` : (user.alias ? `${user.alias} Venues` : 'Venue Operator'); + org = (await tx.query( + `INSERT INTO organisations (kind, name, status, verified_at, created_at) + VALUES ('venue_operator', $1, 'active', NULL, now()) + RETURNING id, name`, + [orgName] + )).rows[0]; + + await tx.query( + `INSERT INTO org_memberships (user_id, org_id, role, status) + VALUES ($1, $2, 'owner', 'active') + ON CONFLICT (user_id, org_id) DO NOTHING`, + [user.id, org.id] + ); + } + + // 2. Grant capabilities: manage_venue and organise_events + for (const code of ['manage_venue', 'organise_events']) { + await tx.query( + `INSERT INTO user_capabilities (user_id, capability_code, status) + VALUES ($1, $2, 'claimed') + ON CONFLICT (user_id, capability_code) DO NOTHING`, + [user.id, code] + ); + } + await tx.query('UPDATE users SET organiser_enabled = true WHERE id = $1', [user.id]); + + // 3. Resolve city_id if city name or slug provided + let cityId = null; + if (data.city_id) { + cityId = data.city_id; + } else if (data.city) { + const cRow = (await tx.query( + `SELECT id FROM location_cities + WHERE lower(name) = lower($1) OR lower(slug) = lower($1) + LIMIT 1`, + [data.city.trim()] + )).rows[0]; + if (cRow) cityId = cRow.id; + } + + // 4. Duplicate / Anti-Hijacking Check + if (name && (cityId || data.address_public)) { + const dup = (await tx.query( + `SELECT v.id, v.org_id, o.name AS org_name + FROM venues v + JOIN organisations o ON o.id = v.org_id + WHERE lower(trim(v.name)) = lower(trim($1)) + AND ( + ($2::uuid IS NOT NULL AND v.city_id = $2) + OR ($3::text IS NOT NULL AND lower(trim(v.address_public)) = lower(trim($3))) + ) + AND v.status = 'active' + AND v.org_id != $4 + LIMIT 1`, + [name, cityId, data.address_public?.trim() || null, org.id] + )).rows[0]; + + if (dup) { + throw new HttpError( + 409, + 'duplicate_venue', + `A venue named '${name}' is already registered at this location. If you are the rightful owner, you can file a verified ownership claim via NIGHTLIFEZ self-service recovery.`, + { + existingVenueId: dup.id, + claimAllowed: true + } + ); + } + } + + // 5. Check if updating existing venue (by venue_id or existing draft in org) + let venue = null; + if (data.venue_id) { + venue = (await tx.query( + `SELECT * FROM venues WHERE id = $1 AND org_id = $2 FOR UPDATE`, + [data.venue_id, org.id] + )).rows[0]; + if (!venue) throw new HttpError(404, 'not_found', 'Venue not found in your organization'); + } else { + // Check if user has an existing uncompleted venue draft in this org + venue = (await tx.query( + `SELECT * FROM venues WHERE org_id = $1 AND (status = 'draft' OR onboarding_completed = false) ORDER BY updated_at DESC LIMIT 1 FOR UPDATE`, + [org.id] + )).rows[0]; + } + + // Clean up facilities array and photos array + const facilitiesJson = JSON.stringify(Array.isArray(data.facilities) ? data.facilities : (venue?.facilities || [])); + let photosList = venue?.photos || []; + if (Array.isArray(data.photos)) { + photosList = data.photos; + } else if (typeof data.photos === 'string' && data.photos.trim()) { + photosList = data.photos.split(',').map((s) => s.trim()).filter(Boolean); + } + const photosJson = JSON.stringify(photosList); + + let operatingHours = venue?.operating_hours || {}; + if (data.operating_hours) { + if (typeof data.operating_hours === 'object') { + operatingHours = data.operating_hours; + } else if (typeof data.operating_hours === 'string') { + operatingHours = { general: data.operating_hours.trim() }; + } + } + + const onboardingCompleted = !isDraft; + const capacityVal = data.capacity ? Number(data.capacity) : (venue?.capacity || 50); + const targetStatus = isDraft + ? (venue && venue.status === 'active' && venue.onboarding_completed ? 'active' : 'draft') + : 'active'; + + if (venue) { + // Update existing venue + venue = (await tx.query( + `UPDATE venues SET + name = COALESCE($3, name), + category = COALESCE($4, category), + description = COALESCE($5, description), + address_public = COALESCE($6, address_public), + address_private = COALESCE($7, address_private), + city_id = COALESCE($8, city_id), + neighbourhood = COALESCE($9, neighbourhood), + capacity = COALESCE($10, capacity), + facilities = $11::jsonb, + operating_hours = $12::jsonb, + contact_name = COALESCE($13, contact_name), + contact_phone = COALESCE($14, contact_phone), + contact_email = COALESCE($15, contact_email), + rules = COALESCE($16, rules), + photos = $17::jsonb, + status = $18, + onboarding_completed = $19, + onboarding_step = COALESCE($20, onboarding_step), + updated_at = now() + WHERE id = $1 AND org_id = $2 + RETURNING *`, + [ + venue.id, + org.id, + name || null, + data.category?.trim() || null, + data.description?.trim() || null, + data.address_public?.trim() || null, + data.address_private?.trim() || null, + cityId, + data.neighbourhood?.trim() || null, + capacityVal, + facilitiesJson, + JSON.stringify(operatingHours), + data.contact_name?.trim() || null, + data.contact_phone?.trim() || null, + data.contact_email?.trim() || null, + data.rules?.trim() || null, + photosJson, + targetStatus, + onboardingCompleted, + data.onboarding_step || (onboardingCompleted ? 4 : 2) + ] + )).rows[0]; + } else { + // Insert new venue + venue = (await tx.query( + `INSERT INTO venues ( + org_id, name, category, description, address_public, address_private, + city_id, neighbourhood, capacity, facilities, operating_hours, + contact_name, contact_phone, contact_email, rules, photos, + status, onboarding_completed, onboarding_step, created_at, updated_at + ) VALUES ( + $1, $2, $3, $4, $5, $6, + $7, $8, $9, $10::jsonb, $11::jsonb, + $12, $13, $14, $15, $16::jsonb, + $17, $18, $19, now(), now() + ) RETURNING *`, + [ + org.id, + name || 'Untitled Venue Draft', + data.category?.trim() || 'event_space', + data.description?.trim() || null, + data.address_public?.trim() || null, + data.address_private?.trim() || null, + cityId, + data.neighbourhood?.trim() || null, + capacityVal, + facilitiesJson, + JSON.stringify(operatingHours), + data.contact_name?.trim() || user.alias || null, + data.contact_phone?.trim() || null, + data.contact_email?.trim() || user.email || null, + data.rules?.trim() || null, + photosJson, + targetStatus, + onboardingCompleted, + data.onboarding_step || (onboardingCompleted ? 4 : 1) + ] + )).rows[0]; + } + + const strength = calculateProfileStrength(venue); + await audit(`user:${user.id}`, isDraft ? 'venue.save_draft' : 'venue.onboard', venue.id, { + name: venue.name, + orgId: org.id, + isDraft, + completion: strength.percentage + }, tx); + + return { + venue, + orgId: org.id, + isDraft, + completionPercentage: strength.percentage, + missingFields: strength.missing + }; + }); +} + +/** + * Submits a self-service venue ownership claim/recovery request. + * Does NOT automatically transfer ownership. Initiates auditable verification. + */ +export async function submitVenueClaim(user, data, c = db) { + if (!user?.id) throw new HttpError(401, 'unauthorized', 'Please sign in to submit an ownership claim'); + + return await c.tx(async (tx) => { + // 1. Verify target venue exists and is an active published venue + const venue = (await tx.query( + `SELECT v.id, v.org_id, v.name, v.contact_email, v.status, o.name AS org_name + FROM venues v + JOIN organisations o ON o.id = v.org_id + WHERE v.id = $1`, + [data.venue_id] + )).rows[0]; + if (!venue) throw new HttpError(404, 'not_found', 'Venue not found'); + + // 2. Claimant cannot claim a venue their own org already owns + const isMember = (await tx.query( + `SELECT 1 FROM org_memberships WHERE user_id = $1 AND org_id = $2 AND status = 'active'`, + [user.id, venue.org_id] + )).rows[0]; + if (isMember) { + throw new HttpError(400, 'already_owned', 'You are already a member of the organisation that owns this venue'); + } + + // 3. Resolve claimant's venue_operator organisation + let claimantOrg = (await tx.query( + `SELECT o.id FROM organisations o + JOIN org_memberships m ON m.org_id = o.id + WHERE m.user_id = $1 AND m.role = 'owner' AND o.status = 'active' + ORDER BY o.created_at ASC LIMIT 1`, + [user.id] + )).rows[0]; + + if (!claimantOrg) { + claimantOrg = (await tx.query( + `INSERT INTO organisations (kind, name, status, verified_at, created_at) + VALUES ('venue_operator', $1, 'active', NULL, now()) + RETURNING id`, + [`${data.contact_name || user.alias || 'Claimant'} Organisation`] + )).rows[0]; + + await tx.query( + `INSERT INTO org_memberships (user_id, org_id, role, status) + VALUES ($1, $2, 'owner', 'active') + ON CONFLICT (user_id, org_id) DO NOTHING`, + [user.id, claimantOrg.id] + ); + } + + // 4. Check for existing pending claim by this user for this venue + const existingClaim = (await tx.query( + `SELECT id, status, created_at FROM venue_claims + WHERE venue_id = $1 AND claimant_user_id = $2 AND status IN ('pending_verification', 'reviewing') + LIMIT 1`, + [venue.id, user.id] + )).rows[0]; + + if (existingClaim) { + throw new HttpError( + 409, + 'claim_already_pending', + 'An ownership claim for this venue is already pending verification under your account' + ); + } + + // 5. Insert auditable claim record (NO automatic ownership transfer!) + const claim = (await tx.query( + `INSERT INTO venue_claims ( + venue_id, claimant_user_id, claimant_org_id, claimant_role, + business_proof_type, business_proof_ref, contact_name, contact_email, + contact_phone, notes, status, created_at, updated_at + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'pending_verification', now(), now()) + RETURNING *`, + [ + venue.id, + user.id, + claimantOrg.id, + data.claimant_role.trim(), + data.business_proof_type.trim(), + data.business_proof_ref.trim(), + data.contact_name.trim(), + data.contact_email.trim(), + data.contact_phone?.trim() || null, + data.notes?.trim() || null + ] + )).rows[0]; + + // Audit the claim submission + await audit(`user:${user.id}`, 'venue.claim.submit', claim.id, { + venueId: venue.id, + venueName: venue.name, + proofType: data.business_proof_type, + proofRef: data.business_proof_ref + }, tx); + + return { + claim, + venue: { id: venue.id, name: venue.name }, + message: 'Ownership claim submitted successfully. Verification challenge recorded.' + }; + }); +} + +/** + * Returns all venue ownership claims submitted by the user. + */ +export async function getVenueClaims(user, c = db) { + if (!user?.id) throw new HttpError(401, 'unauthorized', 'Please sign in'); + const { rows } = await c.query( + `SELECT vc.*, v.name AS venue_name, v.address_public + FROM venue_claims vc + JOIN venues v ON v.id = vc.venue_id + WHERE vc.claimant_user_id = $1 + ORDER BY vc.created_at DESC`, + [user.id] + ); + return rows.map((r) => ({ + id: r.id, + venueId: r.venue_id, + venueName: r.venue_name, + addressPublic: r.address_public, + claimantRole: r.claimant_role, + businessProofType: r.business_proof_type, + businessProofRef: r.business_proof_ref, + contactName: r.contact_name, + contactEmail: r.contact_email, + contactPhone: r.contact_phone, + notes: r.notes, + status: r.status, + resolutionNotes: r.resolution_notes, + resolvedAt: r.resolved_at, + createdAt: r.created_at, + updatedAt: r.updated_at + })); +} diff --git a/lib/views/pages.js b/lib/views/pages.js index 5f1b7fa..727f622 100644 --- a/lib/views/pages.js +++ b/lib/views/pages.js @@ -80,15 +80,6 @@ const FORMS = { ['name', 'Your name', 'text', true], ['telegram', 'Telegram username', 'text', true], ['email', 'Email (optional)', 'email', false], ['city', 'City', 'text', true], ['experience', 'Hosting or community experience', 'textarea', true], ['idea', 'An event you would like to host', 'textarea', false] ] - }, - venue: { - path: '/list-your-venue', title: 'List Your Venue', eyebrow: 'Venues', - lede: 'Cafés, restaurants, bars, studios and resorts that welcome small groups.', - fields: [ - ['name', 'Your name', 'text', true], ['venue_name', 'Venue name', 'text', true], ['email', 'Email', 'email', true], - ['phone', 'Phone (optional)', 'tel', false], ['city', 'City', 'text', true], ['area', 'Area / neighbourhood', 'text', false], - ['capacity', 'Comfortable group size', 'number', false], ['message', 'Anything else we should know?', 'textarea', false] - ] } }; @@ -96,6 +87,136 @@ export function formDefinition(type) { return FORMS[type]; } +/** + * Polished, responsive venue-partner landing page. + * Replaces the old manual application form with full self-service entry. + */ +export function renderListYourVenuePage({ user = null, isOperator = false } = {}) { + const getStartedHref = user ? (isOperator ? '/venue' : '/venue?step=onboard') : `/signin?next=${encodeURIComponent('/venue')}`; + const signInHref = user ? '/venue' : `/signin?next=${encodeURIComponent('/venue')}`; + const getStartedLabel = user ? (isOperator ? 'Go to Venue Dashboard →' : 'Complete Venue Onboarding →') : 'Get Started →'; + const signInLabel = user ? 'Dashboard' : 'Sign In'; + + const body = html` + ${pageHeader('Venues & Spaces', 'List Your Venue on NIGHTLIFEZ', 'Turn quiet nights into curated, high-margin experiences. Join premier rooftop lounges, speakeasies, private dinner clubs, and boutique spaces hosting South India’s vibrant 21+ community.')} + +
+
+ + +
+
+ ⚡ 100% Self-Service Onboarding +

Instant Venue Partner Command Centre

+

Skip manual waitlists and enquiry forms. Set up your space, publish house rules, and begin accepting event bookings immediately.

+
+ +
+ + ${isOperator ? html` +
+ Active Venue Partner +

You already have an active venue registered!

+

Access your venue dashboard to manage your space, view attendee capacity, and coordinate with event hosts.

+ +
` : ''} + + +
+
+ +

Direct Self-Service Listing

+

Create and customize your venue profile in minutes. Update photos, facilities, operating hours, and location directly with zero manual staff approvals.

+
+
+ +

Curated 21+ Community

+

Connect with vetted event organisers, dinner clubs, listening sessions, and weekend mixers across Chennai, Bengaluru, Hyderabad, Kochi, and Goa.

+
+
+ +

Secret Venue Privacy

+

Choose between public discovery and confidential addresses. Secret venue coordinates and private directions are disclosed only to confirmed ticket holders.

+
+
+ +

Real-Time Command Centre

+

Track upcoming event schedules, average capacity utilization, lifetime guest footfall, and on-ground team staff assignments in one unified console.

+
+
+ +

Full Event Curation Control

+

Review organizer event concepts, approve or decline dates with 1-click, or publish and ticket your own in-house nightlife experiences.

+
+
+ +

Zero Listing Fees

+

100% free to list your space. You retain full control over your venue hire terms, minimum spends, or door splits directly with organisers.

+
+
+ + +
+

How Self-Service Venue Listing Works

+
+
+ 1 +

Sign In & Create Profile

+

Sign in with Telegram and enter your venue name, category, capacity, neighbourhood, and amenities.

+
+
+ 2 +

Set Operating Rules

+

Configure your operating hours, photo gallery, bar licensing, and house guidelines for private hosts.

+
+
+ 3 +

Activate & Host

+

Your venue profile activates instantly. Receive booking requests or launch ticketed events through your dashboard.

+
+
+
+ + +
+

Welcoming Premier Spaces Across South India

+
    +
  • Rooftop Lounges & Skybars: Open-air terraces with sound systems and sunset views.
  • +
  • Speakeasies & Cocktail Bars: Intimate spaces for tasting menus, cocktail mixers, and vinyl sessions.
  • +
  • Nightclubs & Dance Venues: Premier sound & light setups for club nights and weekend raves.
  • +
  • Creative Lofts & Art Studios: Multi-purpose spaces for pop-ups, creator dinners, and listening parties.
  • +
  • Private Resorts & Farmhouses: Dedicated getaways for weekend retreats and private celebrations.
  • +
+
+ + +
+

Ready to list your space on NIGHTLIFEZ?

+

Join South India's premier nightlife and social discovery network. Get started in minutes.

+
+ Get Started → + Sign In +
+
+ +
+
+ `; + + return layout({ + title: 'List Your Venue · NIGHTLIFEZ', + description: 'Self-service venue partner onboarding. List your rooftop, lounge, bar or private space for curated 21+ experiences across South India.', + path: '/list-your-venue', + body, + current: '/list-your-venue' + }); +} + export function renderForm(type, { user = null, isOrg = false } = {}) { const f = FORMS[type]; if (type === 'host') { diff --git a/lib/views/venue.js b/lib/views/venue.js index 1d16271..c679f78 100644 --- a/lib/views/venue.js +++ b/lib/views/venue.js @@ -2,8 +2,9 @@ // Interactive client functionality mounts from public/js/venue.js with styles in public/css/venue.css. import { html, raw, esc } from './html.js'; import { layout, pageHeader } from './layout.js'; +import { VENUE_CATEGORIES, VENUE_FACILITIES } from '../services/venue.js'; -const ASSETS = raw(''); +const ASSETS = raw(''); function gate(state, user = null, csrf = '') { if (state === 'signed_out') { @@ -20,43 +21,217 @@ function gate(state, user = null, csrf = '') { `; } - // Onboarding / Application state for logged-in users who do not yet operate an active venue + // Direct Self-Service Venue Onboarding for authenticated users who do not yet operate an active venue return html`
-
-
- Partner With NIGHTLIFEZ -

Turn quiet nights into curated, high-margin experiences

-

NIGHTLIFEZ connects vetted event organisers, dinner clubs, and party hosts with South India’s finest venues.

-
    -
  • Direct Organiser Enquiries: Receive verified booking requests for private dinners, listening sessions, and weekend mixers.
  • -
  • Capacity & Schedule Control: Review event concepts and approve dates that fit your operating calendar.
  • -
  • Zero Attendee Chaos: Organisers handle RSVPs, ticketing, and door coordination through NIGHTLIFEZ.
  • -
  • Verified Operator Status: Trusted badge across our South India discovery feed.
  • -
- +
+
+ ⚡ Instant Self-Service Setup +

Launch Your Venue on NIGHTLIFEZ

+

Zero waitlists or manual approvals. Fill in your space details to immediately unlock your venue dashboard, event scheduling, and host bookings.

-
-

Submit Venue Application

-

Tell us about your space. Our venue curation team reviews every application within 24 to 48 hours.

-
-
- - + +
+
+
+ Profile Completion: + 0% + Incomplete (Draft)
-
- - -
-
- - + Fill in venue name, category, and city to start +
+
+
+
+
+ +
+ + + +
+ 1. Venue Identity & Concept +
+ + +
+ +
+ + +
+ 2. Location & Addresses +
+ + +
+ + +
+ + +
+ 3. Capacity & Point of Contact +
+ + +
+
+ + +
+
+ + +
+ 4. Facilities & Amenities +

Select all features available at your venue for event organisers.

+
+ ${VENUE_FACILITIES.map(fac => html` + + `)} +
+
+ + +
+ 5. Operating Hours & Guidelines + + +
+ + +
+ 6. Photos & Visual Showcase +

Add photo URLs (Unsplash, Cloudinary, AWS S3, etc.) showcasing your space.

+
+ + +
+
+ + +
+ +
- - - -

+

+ + + +
+
+

Submit Venue Ownership Claim

+ +
+
+ +

+ NIGHTLIFEZ protects venues against unauthorized claims. Provide verifiable business credentials (GSTIN, FSSAI, or official utility bill) to initiate a self-service ownership dispute challenge. +

+
+ + +
+
+ + +
+
+ + +
+ + +

+
+
+
`; @@ -88,8 +263,9 @@ export function renderVenuePage({ state = 'ok', user = null, csrf = '' } = {}) { + + Host / Create Event - + @@ -190,6 +366,22 @@ export function renderVenuePage({ state = 'ok', user = null, csrf = '' } = {}) {

Operating Hours & Guidelines

+ +
+ +
+
+

Photo Gallery & Showcase

+

Visual imagery shown on your venue listing and event pages.

+
+
+ +
+ + +
@@ -201,10 +393,13 @@ export function renderVenuePage({ state = 'ok', user = null, csrf = '' } = {}) {

Associated Events Schedule

Events hosted at your venue. Strictly isolated: individual attendee PII is protected.

-
- - - +
+ + Create Event at Venue +
+ + + +
@@ -314,6 +509,16 @@ export function renderVenuePage({ state = 'ok', user = null, csrf = '' } = {}) { +
+ + +
@@ -323,6 +528,7 @@ export function renderVenuePage({ state = 'ok', user = null, csrf = '' } = {}) { +

Facilities & Equipment

diff --git a/migrations/031_venue_self_service_onboarding.sql b/migrations/031_venue_self_service_onboarding.sql new file mode 100644 index 0000000..547bf4a --- /dev/null +++ b/migrations/031_venue_self_service_onboarding.sql @@ -0,0 +1,42 @@ +-- migrations/031_venue_self_service_onboarding.sql +-- NIGHTLIFEZ Full Self-Service Venue Onboarding & Direct Management. +-- Additive columns on venues for self-service categorization, neighbourhood, and progress tracking. +-- Fully safe, idempotent, non-destructive, and backward compatible. + +-- 1. Extend venue_status enum to include 'draft' for isolated uncompleted drafts +ALTER TYPE venue_status ADD VALUE IF NOT EXISTS 'draft'; + +-- 2. Extend venues table with self-service metadata +ALTER TABLE venues ADD COLUMN IF NOT EXISTS category TEXT; +ALTER TABLE venues ADD COLUMN IF NOT EXISTS neighbourhood TEXT; +ALTER TABLE venues ADD COLUMN IF NOT EXISTS onboarding_completed BOOLEAN NOT NULL DEFAULT true; +ALTER TABLE venues ADD COLUMN IF NOT EXISTS onboarding_step INTEGER NOT NULL DEFAULT 1; + +-- 3. Indexes for discovery, filtering, and onboarding lookups +CREATE INDEX IF NOT EXISTS idx_venues_category ON venues (category) WHERE category IS NOT NULL; +CREATE INDEX IF NOT EXISTS idx_venues_neighbourhood ON venues (neighbourhood) WHERE neighbourhood IS NOT NULL; +CREATE INDEX IF NOT EXISTS idx_venues_onboarding_completed ON venues (org_id, onboarding_completed); +CREATE INDEX IF NOT EXISTS idx_venues_active_discovery ON venues (id, org_id) WHERE status = 'active' AND onboarding_completed = true; + +-- 4. Self-service ownership claims & recovery for duplicate/unclaimed venues +CREATE TABLE IF NOT EXISTS venue_claims ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + venue_id UUID NOT NULL REFERENCES venues(id) ON DELETE CASCADE, + claimant_user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + claimant_org_id UUID REFERENCES organisations(id) ON DELETE SET NULL, + claimant_role TEXT NOT NULL, + business_proof_type TEXT NOT NULL, + business_proof_ref TEXT NOT NULL, + contact_name TEXT NOT NULL, + contact_email TEXT NOT NULL, + contact_phone TEXT, + notes TEXT, + status TEXT NOT NULL DEFAULT 'pending_verification', + resolution_notes TEXT, + resolved_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_venue_claims_venue ON venue_claims (venue_id, status); +CREATE INDEX IF NOT EXISTS idx_venue_claims_user ON venue_claims (claimant_user_id, status); diff --git a/public/css/venue.css b/public/css/venue.css index a3baf21..cbc3972 100644 --- a/public/css/venue.css +++ b/public/css/venue.css @@ -589,3 +589,188 @@ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus- outline: 2px solid var(--neon-cyan, #00D9FF); outline-offset: 2px; } + +/* Self-Service Onboarding Wizard Styles */ +.venue-onboarding-container { + max-width: 860px; + margin: 0 auto; + padding: 10px 0 60px; +} +.venue-onboard-title { + font-size: clamp(1.8rem, 4vw, 2.6rem); + margin: 12px 0 10px; + font-weight: 800; + letter-spacing: -0.02em; +} +.venue-onboard-lede { + max-width: 620px; + margin: 0 auto 28px; + color: var(--muted, #8a8a9a); + font-size: 1.05rem; +} +.venue-strength-card { + background: var(--surface, #121218); + border: 1px solid var(--line, #242432); + border-radius: var(--radius, 12px); + padding: 18px 24px; + margin-bottom: 24px; +} +.venue-strength-header { + display: flex; + justify-content: space-between; + align-items: center; + flex-wrap: wrap; + gap: 12px; + margin-bottom: 12px; +} +.venue-strength-info { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} +.strength-label { + font-weight: 600; + font-size: 0.95rem; +} +.strength-percent { + font-weight: 800; + color: var(--neon-cyan, #00D9FF); + font-size: 1.15rem; +} +.strength-hint { + color: var(--muted, #8a8a9a); +} +.venue-progress-track { + width: 100%; + height: 8px; + background: rgba(255, 255, 255, 0.08); + border-radius: 999px; + overflow: hidden; +} +.venue-progress-fill { + height: 100%; + background: linear-gradient(90deg, #00D9FF 0%, #38ef7d 100%); + border-radius: 999px; + transition: width 0.3s ease; +} +.venue-onboarding-card { + background: var(--surface, #121218); + border: 1px solid var(--line, #242432); + border-radius: var(--radius, 12px); + padding: 32px 28px; +} +.venue-form-section { + border: 0; + padding: 0; + margin: 0 0 32px; +} +.venue-form-section:last-of-type { + margin-bottom: 24px; +} +.venue-section-title { + font-size: 1.15rem; + font-weight: 700; + color: #fff; + padding: 0; + margin-bottom: 16px; + border-bottom: 1px solid var(--line, #242432); + width: 100%; + padding-bottom: 8px; +} +.field-hint { + display: block; + margin-top: 4px; + color: var(--muted, #8a8a9a); + font-size: 0.82rem; +} +.facilities-checkbox-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 10px; +} +.venue-checkbox-item { + display: flex; + align-items: center; + gap: 8px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid var(--line, #242432); + border-radius: 8px; + padding: 10px 14px; + cursor: pointer; + font-size: 0.9rem; + transition: background 0.15s, border-color 0.15s; +} +.venue-checkbox-item:hover { + background: rgba(0, 217, 255, 0.06); + border-color: rgba(0, 217, 255, 0.3); +} +.venue-checkbox-item input[type="checkbox"] { + accent-color: var(--neon-cyan, #00D9FF); + width: 16px; + height: 16px; +} +.venue-onboard-actions-row { + display: flex; + gap: 16px; + align-items: center; + flex-wrap: wrap; + margin-top: 28px; +} + +/* Gallery & Thumbnails */ +.venue-gallery-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); + gap: 14px; + margin-top: 14px; +} +.venue-gallery-item { + position: relative; + aspect-ratio: 4 / 3; + border-radius: 8px; + overflow: hidden; + border: 1px solid var(--line, #242432); + background: #000; +} +.venue-gallery-thumb { + width: 100%; + height: 100%; + object-fit: cover; + display: block; +} +.venue-gallery-remove { + position: absolute; + top: 6px; + right: 6px; + background: rgba(0, 0, 0, 0.75); + color: #ff6b6b; + border: 1px solid rgba(255, 107, 107, 0.4); + border-radius: 50%; + width: 24px; + height: 24px; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + line-height: 1; + cursor: pointer; + padding: 0; + transition: background 0.15s, color 0.15s; +} +.venue-gallery-remove:hover { + background: #ff6b6b; + color: #fff; +} +.event-action-cell { + display: inline-flex; + gap: 6px; +} + +/* Accessible and Subtle :user-invalid Styling */ +.lead-form input:user-invalid, +.lead-form select:user-invalid, +.lead-form textarea:user-invalid { + border-color: #ff6b6b; + box-shadow: 0 0 0 1px rgba(255, 107, 107, 0.25); +} diff --git a/public/js/venue.js b/public/js/venue.js index 2c29f51..cc9992e 100644 --- a/public/js/venue.js +++ b/public/js/venue.js @@ -79,6 +79,17 @@ { id: 'wifi_highspeed', label: 'High-Speed Wi-Fi', icon: '📶' } ]; + var ALL_CATEGORIES = [ + { id: 'rooftop_lounge', label: 'Rooftop Lounge & Skybar' }, + { id: 'cocktail_speakeasy', label: 'Cocktail Bar & Speakeasy' }, + { id: 'nightclub', label: 'Nightclub & Dance Venue' }, + { id: 'cafe_bistro', label: 'Café & Intimate Bistro' }, + { id: 'studio_loft', label: 'Art Studio & Creative Loft' }, + { id: 'resort_farmhouse', label: 'Resort, Villa & Farmhouse' }, + { id: 'brewery_pub', label: 'Microbrewery & Social Pub' }, + { id: 'event_space', label: 'Boutique Event Space' } + ]; + var DAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']; // ---------- Initialization ---------- @@ -89,9 +100,9 @@ state.csrf = appRoot.getAttribute('data-csrf') || ''; // If onboarding form exists - var applyForm = $('#venueApplyForm'); - if (applyForm) { - initOnboarding(applyForm); + var onboardForm = $('#venueOnboardForm') || $('#venueApplyForm'); + if (onboardForm) { + initSelfServiceOnboarding(onboardForm); return; } @@ -117,51 +128,301 @@ }); } - // ---------- Onboarding Flow ---------- - function initOnboarding(form) { - // Check if user has past applications + // ---------- Self-Service Direct Onboarding Flow ---------- + function initSelfServiceOnboarding(form) { + var updateStrength = function () { + var fd = new FormData(form); + var name = (fd.get('name') || fd.get('venue_name') || '').toString().trim(); + var category = (fd.get('category') || '').toString().trim(); + var city = (fd.get('city') || '').toString().trim(); + var desc = (fd.get('description') || fd.get('message') || '').toString().trim(); + var cap = Number(fd.get('capacity')) || 0; + var facs = $$('input[name="facilities"]:checked', form); + var photo1 = (fd.get('photo_url_1') || '').toString().trim(); + var photo2 = (fd.get('photo_url_2') || '').toString().trim(); + var hoursNote = (fd.get('operating_hours_note') || '').toString().trim(); + var rules = (fd.get('rules') || '').toString().trim(); + + var score = 0; + if (name) score += 15; + if (category) score += 15; + if (city) score += 20; + if (desc) score += 10; + if (cap > 0) score += 10; + if (facs.length > 0) score += 10; + if (photo1 || photo2) score += 10; + if (hoursNote || rules) score += 10; + + var percentEl = $('#strengthPercent'); + var barEl = $('#strengthProgressBar'); + var pillEl = $('#onboardStatusPill'); + var hintEl = $('#strengthHint'); + + if (percentEl) percentEl.textContent = score + '%'; + if (barEl) { + barEl.style.width = score + '%'; + if (barEl.parentElement) barEl.parentElement.setAttribute('aria-valuenow', score); + } + if (pillEl) { + if (score >= 70) { + pillEl.textContent = 'Ready to Launch'; + pillEl.className = 'venue-pill venue-pill-status'; + } else if (score >= 40) { + pillEl.textContent = 'In Progress'; + pillEl.className = 'venue-pill venue-pill-pending'; + } else { + pillEl.textContent = 'Incomplete (Draft)'; + pillEl.className = 'venue-pill venue-pill-pending'; + } + } + if (hintEl) { + if (!name) hintEl.textContent = 'Add venue name to begin'; + else if (!category) hintEl.textContent = 'Choose space category'; + else if (!city) hintEl.textContent = 'Specify city and address'; + else if (score < 70) hintEl.textContent = 'Add capacity, description and amenities'; + else hintEl.textContent = 'Profile ready! Click Launch to activate immediately'; + } + return score; + }; + + // Live strength calculation on input changes + form.addEventListener('input', updateStrength); + form.addEventListener('change', updateStrength); + updateStrength(); + + // Check if user has an existing draft venue to prefill api('GET', '/api/venue/context').then(function (res) { - if (res.ok && res.context && res.context.applications && res.context.applications.length > 0) { - var box = $('#applicationStatusBox'); - if (box) { - var app = res.context.applications[0]; - box.hidden = false; - box.innerHTML = '

Recent Application: ' + esc(app.venueName) + '

' + - '

Status: ' + esc(app.status.toUpperCase()) + ' — Submitted on ' + - new Date(app.submittedAt).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' }) + '

' + - '

Our venue team is reviewing your space details. You will receive an update once verified.

'; + if (res.ok && res.context) { + var existing = res.context.draftVenue || (res.context.venues && res.context.venues[0]); + if (existing) { + var setVal = function (name, val) { + var inp = form.elements[name]; + if (inp && val != null) inp.value = val; + }; + setVal('venue_id', existing.id); + setVal('name', existing.name); + setVal('category', existing.category); + setVal('city', existing.cityName || existing.city); + setVal('neighbourhood', existing.neighbourhood); + setVal('address_public', existing.addressPublic); + setVal('address_private', existing.addressPrivate); + setVal('capacity', existing.capacity); + setVal('contact_name', existing.contactName); + setVal('contact_phone', existing.contactPhone); + setVal('contact_email', existing.contactEmail); + setVal('description', existing.description); + setVal('rules', existing.rules); + if (existing.facilities && Array.isArray(existing.facilities)) { + existing.facilities.forEach(function (f) { + var cb = $('input[name="facilities"][value="' + f + '"]', form); + if (cb) cb.checked = true; + }); + } + if (existing.photos && Array.isArray(existing.photos)) { + if (existing.photos[0]) setVal('photo_url_1', typeof existing.photos[0] === 'string' ? existing.photos[0] : existing.photos[0].url); + if (existing.photos[1]) setVal('photo_url_2', typeof existing.photos[1] === 'string' ? existing.photos[1] : existing.photos[1].url); + } + if (existing.operatingHours) { + if (typeof existing.operatingHours === 'string') setVal('operating_hours_note', existing.operatingHours); + else if (existing.operatingHours.general) setVal('operating_hours_note', existing.operatingHours.general); + else if (existing.operatingHours.friday) setVal('operating_hours_note', existing.operatingHours.friday); + } + updateStrength(); } } }).catch(function () {}); + var collectData = function (isDraft) { + var fd = new FormData(form); + var facs = $$('input[name="facilities"]:checked', form).map(function (cb) { return cb.value; }); + var photos = []; + var p1 = (fd.get('photo_url_1') || '').toString().trim(); + var p2 = (fd.get('photo_url_2') || '').toString().trim(); + if (p1) photos.push(p1); + if (p2) photos.push(p2); + + var operatingHours = {}; + var hoursNote = (fd.get('operating_hours_note') || '').toString().trim(); + if (hoursNote) { + DAYS.forEach(function (d) { operatingHours[d] = hoursNote; }); + } + + var venueIdVal = (fd.get('venue_id') || '').toString().trim() || undefined; + + return { + venue_id: venueIdVal, + name: (fd.get('name') || fd.get('venue_name') || '').toString().trim(), + category: (fd.get('category') || undefined), + description: (fd.get('description') || fd.get('message') || undefined), + city: (fd.get('city') || '').toString().trim(), + neighbourhood: (fd.get('neighbourhood') || fd.get('area') || undefined), + address_public: (fd.get('address_public') || undefined), + address_private: (fd.get('address_private') || undefined), + capacity: fd.get('capacity') ? Number(fd.get('capacity')) : 50, + contact_name: (fd.get('contact_name') || undefined), + contact_phone: (fd.get('contact_phone') || undefined), + contact_email: (fd.get('contact_email') || fd.get('email') || undefined), + facilities: facs, + operating_hours: Object.keys(operatingHours).length > 0 ? operatingHours : undefined, + rules: (fd.get('rules') || undefined), + photos: photos, + is_draft: Boolean(isDraft) + }; + }; + + // Save Progress (Draft) button + var btnDraft = $('#btnSaveVenueDraft'); + if (btnDraft) { + btnDraft.addEventListener('click', async function (e) { + e.preventDefault(); + var msg = $('#onboardMsg') || $('#applyMsg'); + if (msg) { + msg.textContent = 'Saving progress…'; + msg.className = 'form-msg'; + } + + var payload = collectData(true); + if (!payload.name) { + if (msg) { + msg.textContent = 'Please enter a venue name to save your draft.'; + msg.className = 'form-msg error'; + } + return; + } + + try { + var res = await api('POST', '/api/venue/onboard', payload); + if (msg) { + msg.textContent = 'Progress saved! Profile is at ' + (res.completionPercentage || 0) + '%. You can resume anytime.'; + msg.className = 'form-msg ok'; + } + if (res.venue && res.venue.id) { + var vInp = form.elements['venue_id']; + if (vInp) vInp.value = res.venue.id; + } + updateStrength(); + } catch (err) { + if (msg) { + if (err.data && err.data.error === 'duplicate_venue') { + msg.innerHTML = esc(err.message) + '
'; + var btnClaim = $('#btnTriggerClaimDraft'); + if (btnClaim) { + btnClaim.addEventListener('click', function () { + var modalClaim = $('#modalClaimVenue'); + if (modalClaim && err.data.existingVenueId) { + var vInp = $('#claimVenueId'); + if (vInp) vInp.value = err.data.existingVenueId; + modalClaim.showModal(); + } + }); + } + } else { + msg.textContent = err.message || 'Error saving progress.'; + } + msg.className = 'form-msg error'; + } + } + }); + } + + // Submit / Launch form form.addEventListener('submit', async function (ev) { ev.preventDefault(); - var msg = $('#applyMsg'); - msg.textContent = 'Submitting application…'; - msg.className = 'form-msg'; + var msg = $('#onboardMsg') || $('#applyMsg'); + if (msg) { + msg.textContent = 'Launching venue profile…'; + msg.className = 'form-msg'; + } - var fd = new FormData(form); - var payload = { - name: fd.get('name'), - venue_name: fd.get('venue_name'), - email: fd.get('email'), - phone: fd.get('phone') || undefined, - city: fd.get('city'), - area: fd.get('area') || undefined, - capacity: fd.get('capacity') ? Number(fd.get('capacity')) : undefined, - message: fd.get('message') || undefined - }; + var payload = collectData(false); + + if (!payload.name || !payload.category || !payload.city) { + if (msg) { + msg.textContent = 'Please fill in required fields: Venue Name, Category, and City.'; + msg.className = 'form-msg error'; + } + return; + } try { - var res = await api('POST', '/api/venue/apply', payload); - msg.textContent = 'Application submitted successfully! Our team will contact you shortly.'; - msg.className = 'form-msg ok'; - form.reset(); + var res = await api('POST', '/api/venue/onboard', payload); + if (msg) { + msg.textContent = 'Venue profile activated successfully! Redirecting to command centre…'; + msg.className = 'form-msg ok'; + } + setTimeout(function () { + window.location.href = res.redirect || '/venue'; + }, 500); } catch (err) { - msg.textContent = err.message || 'Could not submit application.'; - msg.className = 'form-msg error'; + if (msg) { + if (err.data && err.data.error === 'duplicate_venue') { + msg.innerHTML = esc(err.message) + '
'; + var btnClaim = $('#btnTriggerClaim'); + if (btnClaim) { + btnClaim.addEventListener('click', function () { + var modalClaim = $('#modalClaimVenue'); + if (modalClaim && err.data.existingVenueId) { + var vInp = $('#claimVenueId'); + if (vInp) vInp.value = err.data.existingVenueId; + modalClaim.showModal(); + } + }); + } + } else { + msg.textContent = err.message || 'Error launching venue profile.'; + } + msg.className = 'form-msg error'; + } } }); + + // Wire up dialog close handlers inside onboarding state + $$('[data-close-dialog]', form.parentElement).forEach(function (btn) { + btn.addEventListener('click', function () { + var dlg = btn.closest('dialog'); + if (dlg) dlg.close(); + }); + }); + + // Wire up ownership claim submission + var formClaim = $('#formClaimVenue'); + if (formClaim) { + formClaim.addEventListener('submit', async function (e) { + e.preventDefault(); + var cMsg = $('#claimMsg'); + if (cMsg) { + cMsg.textContent = 'Submitting ownership claim…'; + cMsg.className = 'form-msg'; + } + var fd = new FormData(formClaim); + try { + var payload = { + venue_id: fd.get('venue_id'), + claimant_role: fd.get('claimant_role'), + business_proof_type: fd.get('business_proof_type'), + business_proof_ref: fd.get('business_proof_ref'), + contact_name: fd.get('contact_name'), + contact_email: fd.get('contact_email'), + contact_phone: fd.get('contact_phone') || undefined, + notes: fd.get('notes') || undefined + }; + var res = await api('POST', '/api/venue/claim', payload); + if (cMsg) { + cMsg.textContent = res.message || 'Ownership claim submitted. Verification challenge recorded.'; + cMsg.className = 'form-msg success'; + } + setTimeout(function () { + var modal = $('#modalClaimVenue'); + if (modal) modal.close(); + }, 3000); + } catch (err) { + if (cMsg) { + cMsg.textContent = err.message || 'Failed to submit ownership claim'; + cMsg.className = 'form-msg error'; + } + } + }); + } } // ---------- Tab Navigation ---------- @@ -672,16 +933,21 @@ var el = $('#profileDetailsView'); if (!el) return; + var catObj = ALL_CATEGORIES.find(function (c) { return c.id === p.category; }); + var catLabel = catObj ? catObj.label : (p.category ? esc(p.category) : 'Not specified'); + el.innerHTML = [ '
Venue Display Name
' + esc(p.name) + '
', + '
Space Category
' + catLabel + '
', '
Operating Organisation
' + esc(p.orgName) + (p.orgVerified ? ' (Verified)' : '') + '
', '
Maximum Capacity
' + esc(p.capacity || 'Not specified') + ' guests
', - '
City & Locality
' + esc((p.cityName || '') + (p.localityName ? ', ' + p.localityName : '')) + '
', - '
Public Area
' + esc(p.addressPublic || 'Not specified') + '
', + '
City & Locality
' + esc((p.cityName || '') + (p.localityName ? ', ' + p.localityName : '')) + '
', + '
Neighbourhood / Area
' + esc(p.neighbourhood || p.localityName || 'Not specified') + '
', + '
Public Street Address
' + esc(p.addressPublic || 'Not specified') + '
', '
Private Gate / Exact Entry
' + esc(p.addressPrivate || 'Private address shared only with confirmed attendees') + '
', '
Primary Contact
' + esc((p.contactName || '') + (p.contactPhone ? ' (' + p.contactPhone + ')' : '') + (p.contactEmail ? ' · ' + p.contactEmail : '')) + '
', - '
About & Ambiance
' + esc(p.description || 'No description provided yet.') + '
', - '
House Rules & Entry Policy
' + esc(p.rules || 'Standard NIGHTLIFEZ community and safety guidelines apply.') + '
' + '
About & Ambiance
' + esc(p.description || 'No description provided yet.') + '
', + '
House Rules & Entry Policy
' + esc(p.rules || 'Standard NIGHTLIFEZ community and safety guidelines apply.') + '
' ].join(''); // Facilities @@ -707,11 +973,51 @@ return '
' + d + '' + esc(val) + '
'; }).join(''); } + + // Photo Gallery + renderGalleryView(p); + } + + function renderGalleryView(p) { + var gEl = $('#profileGalleryView'); + if (!gEl) return; + var photos = Array.isArray(p.photos) ? p.photos : []; + if (photos.length === 0) { + gEl.innerHTML = '

No photos uploaded yet. Add photos showcasing your interior, seating, bar, and rooftop.

'; + return; + } + gEl.innerHTML = photos.map(function (item, idx) { + var url = typeof item === 'string' ? item : (item && item.url ? item.url : ''); + if (!url) return ''; + return ''; + }).join(''); + + $$('[data-remove-photo]', gEl).forEach(function (btn) { + btn.addEventListener('click', async function () { + var idx = Number(btn.getAttribute('data-remove-photo')); + var updated = photos.slice(); + updated.splice(idx, 1); + try { + await api('PATCH', '/api/venue/profile?venueId=' + state.venueId, { photos: updated }); + p.photos = updated; + renderGalleryView(p); + showAlert('Photo removed.'); + } catch (err) { + showAlert(err.message || 'Error removing photo', true); + } + }); + }); } function renderEventsList(events, container) { if (!events || events.length === 0) { - container.innerHTML = '

No events matching this filter.

'; + container.innerHTML = '
' + + '

No events matching this filter.

' + + '+ Create Event at Venue' + + '
'; return; } @@ -738,12 +1044,13 @@ '
' + '' + '' + esc(e.status.toUpperCase()) + '' + + '
View Edit
' + ''; }).join(''); container.innerHTML = '
' + '' + - '' + + '' + '' + rows + '' + '
EventDate & Time (IST)Host / OrganiserAttendance / CapacityStatus
EventDate & Time (IST)Host / OrganiserAttendance / CapacityStatusActions
' + '
'; @@ -877,8 +1184,13 @@ if (val) hours[d] = val; }); + var photosText = fd.get('photos_text') || ''; + var photosArr = photosText.split(/[\r\n,]+/).map(function (s) { return s.trim(); }).filter(Boolean); + var payload = { name: fd.get('name'), + category: fd.get('category') || undefined, + neighbourhood: fd.get('neighbourhood') || null, capacity: fd.get('capacity') ? Number(fd.get('capacity')) : null, contact_name: fd.get('contact_name') || null, contact_phone: fd.get('contact_phone') || null, @@ -888,7 +1200,8 @@ description: fd.get('description') || null, rules: fd.get('rules') || null, facilities: selectedFacs, - operating_hours: hours + operating_hours: hours, + photos: photosArr.length > 0 ? photosArr : undefined }; try { @@ -908,6 +1221,30 @@ }); } + // 1b. Add Photo Form + var formAddPhoto = $('#formAddPhoto'); + if (formAddPhoto) { + formAddPhoto.addEventListener('submit', async function (e) { + e.preventDefault(); + var inp = $('#newPhotoUrl'); + var url = inp ? inp.value.trim() : ''; + if (!url || !state.venueId) return; + + var photos = Array.isArray(state.profile.photos) ? state.profile.photos.slice() : []; + photos.push(url); + + try { + await api('PATCH', '/api/venue/profile?venueId=' + state.venueId, { photos: photos }); + state.profile.photos = photos; + renderGalleryView(state.profile); + if (inp) inp.value = ''; + showAlert('Photo added to gallery.'); + } catch (err) { + showAlert(err.message || 'Error adding photo', true); + } + }); + } + // 2. New Enquiry Form var formNewEnquiry = $('#formNewEnquiry'); if (formNewEnquiry) { @@ -1150,6 +1487,8 @@ }; setVal('name', p.name); + setVal('category', p.category); + setVal('neighbourhood', p.neighbourhood); setVal('capacity', p.capacity); setVal('contact_name', p.contactName); setVal('contact_phone', p.contactPhone); @@ -1159,6 +1498,12 @@ setVal('description', p.description); setVal('rules', p.rules); + var photosEl = $('#editProfilePhotos'); + if (photosEl) { + var photosList = Array.isArray(p.photos) ? p.photos.map(function (x) { return typeof x === 'string' ? x : (x && x.url ? x.url : ''); }).filter(Boolean) : []; + photosEl.value = photosList.join('\n'); + } + // Facilities checkboxes var facsContainer = $('#modalFacilitiesCheckboxes'); if (facsContainer) { diff --git a/test/m10-operational-hardening.test.js b/test/m10-operational-hardening.test.js index 6f29c27..57ec0c4 100644 --- a/test/m10-operational-hardening.test.js +++ b/test/m10-operational-hardening.test.js @@ -97,14 +97,15 @@ test('2. Role-Specific Empty States: Organiser with 0 events renders clear call assert.deepEqual(orgEventsRes.json.events, []); }); -test('3. Post-Submission Lifecycle: Venue Owner 3-step expectation timeline', async () => { +test('3. Self-Service Venue Partner Entry: /list-your-venue delivers direct onboarding and timeline', async () => { const client = new Client(); - const res = await client.get('/list-your-venue?sent=1'); + const res = await client.get('/list-your-venue'); assert.equal(res.status, 200); - assert.match(res.text, /Venue & Safety Review|Venue & Safety Review/i); - assert.match(res.text, /Organiser & Format Matching|Organiser & Format Matching/i); - assert.match(res.text, /Guaranteed Headcounts/i); - assert.match(res.text, /24 to 48 hours/i); + assert.match(res.text, /Get Started|Complete Venue Onboarding/i); + assert.match(res.text, /Sign In|Dashboard/i); + assert.match(res.text, /Sign In & Create Profile|Sign In & Create Profile/i); + assert.match(res.text, /Set Operating Rules/i); + assert.match(res.text, /Activate & Host|Activate & Host/i); }); test('4. Post-Submission Lifecycle: Partner / Service Provider 3-step expectation timeline', async () => { diff --git a/test/migrations.test.js b/test/migrations.test.js index a9ef477..5a35208 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 28 migrations currently exist: 003 through 030 - assert.equal(files.length, 28, `expected 28 migration files, got ${files.length}: ${files.join(', ')}`); + // Exactly 29 migrations currently exist: 003 through 031 + assert.equal(files.length, 29, `expected 29 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_' + '009_', '010_', '011_', '012_', '013_', '014_', '015_', '016_', '017_', '018_', '019_', '020_', '021_', '022_', '023_', '024_', '025_', '026_', '027_', '028_', '029_', '030_', '031_' ]; 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 28 migrations in correct order', async () => { +test('schema_migrations table records all 29 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, 28); + assert.equal(rows.length, 29); 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 28 + // Total count in schema_migrations must remain exactly 29 const countRes = await db.one('SELECT count(*)::int AS n FROM schema_migrations'); - assert.equal(countRes.n, 28); + assert.equal(countRes.n, 29); }); test('migration policy respects environment boundaries', () => { @@ -541,3 +541,21 @@ test('migration 030: infrastructure fee accounting schema integrity and default assert.ok(bookingCols.includes('infrastructure_fee_paise'), 'bookings must have infrastructure_fee_paise'); assert.ok(bookingCols.includes('fee_calculation_snapshot'), 'bookings must have fee_calculation_snapshot'); }); + +test('migration 031: venue self-service onboarding schema objects exist', async () => { + const venueCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'venues'` + )).rows.map((r) => r.column_name); + assert.ok(venueCols.includes('category'), 'venues must have category column'); + assert.ok(venueCols.includes('neighbourhood'), 'venues must have neighbourhood column'); + assert.ok(venueCols.includes('onboarding_completed'), 'venues must have onboarding_completed column'); + assert.ok(venueCols.includes('onboarding_step'), 'venues must have onboarding_step column'); + + const claimsCols = (await db.query( + `SELECT column_name FROM information_schema.columns WHERE table_name = 'venue_claims'` + )).rows.map((r) => r.column_name); + assert.ok(claimsCols.includes('venue_id'), 'venue_claims must have venue_id'); + assert.ok(claimsCols.includes('claimant_user_id'), 'venue_claims must have claimant_user_id'); + assert.ok(claimsCols.includes('business_proof_type'), 'venue_claims must have business_proof_type'); + assert.ok(claimsCols.includes('status'), 'venue_claims must have status'); +}); diff --git a/test/venue-self-service-onboarding.test.js b/test/venue-self-service-onboarding.test.js new file mode 100644 index 0000000..fce62f5 --- /dev/null +++ b/test/venue-self-service-onboarding.test.js @@ -0,0 +1,390 @@ +// test/venue-self-service-onboarding.test.js - Comprehensive tests for Venue Self-Service Onboarding, +// Draft Isolation, Organization Verification Protection, and Safe Ownership Recovery. +import test, { before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { resetDb, startServer, stopServer, db, signedInClient, Client } from './helpers.js'; + +before(async () => { + await resetDb(); + await startServer(); +}); + +after(async () => { + await stopServer(); +}); + +test('1. GET /list-your-venue: renders self-service landing page with no legacy form', async () => { + const c = new Client(); + const res = await c.get('/list-your-venue'); + assert.equal(res.status, 200); + + // Must have primary and secondary CTAs + assert.ok(res.text.includes('Get Started')); + assert.ok(res.text.includes('Sign In')); + assert.ok(res.text.includes('Instant Venue Partner Command Centre')); + assert.ok(res.text.includes('100% Self-Service Onboarding')); + + // Must NOT have legacy enquiry form or consent checkbox + assert.ok(!res.text.includes('id="leadForm"')); + assert.ok(!res.text.includes('id="venueApplyForm"')); + assert.ok(!res.text.includes('I consent to NIGHTLIFEZ')); + assert.ok(!res.text.includes('Send submission')); + assert.ok(!res.text.includes('Our venue curation team reviews every application')); +}); + +test('2. GET /venue: unauthenticated vs authenticated onboarding gate', async () => { + const anon = new Client(); + const anonRes = await anon.get('/venue'); + assert.equal(anonRes.status, 200); + assert.ok(anonRes.text.includes('Sign in to manage your venue')); + assert.ok(anonRes.text.includes('/signin?next=%2Fvenue')); + + const authed = await signedInClient(); + const authedRes = await authed.get('/venue'); + assert.equal(authedRes.status, 200); + assert.ok(authedRes.text.includes('Launch Your Venue on NIGHTLIFEZ')); + assert.ok(authedRes.text.includes('venueOnboardForm')); + assert.ok(authedRes.text.includes('Profile Completion:')); + assert.ok(authedRes.text.includes('Zero waitlists or manual approvals')); +}); + +test('3. Draft publication isolation: draft venue is isolated, not discoverable, and not bookable', async () => { + const draftUser = await signedInClient(); + const outsider = await signedInClient(); + + // Save an incomplete draft + const draftRes = await draftUser.post('/api/venue/onboard', { + name: 'Secret Speakeasy Draft', + category: 'cocktail_speakeasy', + city: 'Bengaluru', + is_draft: true + }); + assert.equal(draftRes.status, 201); + assert.equal(draftRes.json.isDraft, true); + const draftId = draftRes.json.venue.id; + + // DB verification: status must be 'draft' and onboarding_completed = false + const dbVenue = await db.one('SELECT * FROM venues WHERE id = $1', [draftId]); + assert.equal(dbVenue.status, 'draft', 'Draft venue status must be draft'); + assert.equal(dbVenue.onboarding_completed, false, 'onboarding_completed must be false for draft'); + + // Must NOT appear in active venues discovery query + const activeCount = await db.one("SELECT count(*)::int AS cnt FROM venues WHERE status = 'active' AND id = $1", [draftId]); + assert.equal(activeCount.cnt, 0, 'Draft venue must not be counted among active venues'); + + // Draft owner context: hasVenue is false, but draftVenue is populated for resuming + const ownerCtx = await draftUser.get('/api/venue/context'); + assert.equal(ownerCtx.status, 200); + assert.equal(ownerCtx.json.context.hasVenue, false, 'Draft venue must not set hasVenue to true'); + assert.equal(ownerCtx.json.context.venues.length, 0, 'Draft venue must not appear in published venues list'); + assert.ok(ownerCtx.json.context.draftVenue, 'Draft venue must be attached as draftVenue for owner'); + assert.equal(ownerCtx.json.context.draftVenue.id, draftId); + assert.equal(ownerCtx.json.context.draftVenue.name, 'Secret Speakeasy Draft'); + + // Draft venue page: owner visiting /venue still renders onboarding wizard so they can resume + const ownerPage = await draftUser.get('/venue'); + assert.equal(ownerPage.status, 200); + assert.ok(ownerPage.text.includes('venueOnboardForm'), 'Owner must see onboarding form to resume draft'); + assert.ok(!ownerPage.text.includes('Venue Command Centre'), 'Command centre must not render for incomplete draft'); + + // Outsider / attendee cannot book or submit enquiry on a draft venue + const enqRes = await outsider.post(`/api/venue/enquiries?venueId=${draftId}`, { + event_name: 'Private Party', + event_date: '2026-12-31', + requester_name: 'Outsider Test', + expected_guests: 50 + }); + assert.equal(enqRes.status, 404, 'Enquiries on draft venue must return 404'); + + // Draft events and analytics queries must return 404 + const evRes = await draftUser.get(`/api/venue/events?venueId=${draftId}`); + assert.equal(evRes.status, 404, 'Events on draft venue must return 404'); + const anaRes = await draftUser.get(`/api/venue/analytics?venueId=${draftId}`); + assert.equal(anaRes.status, 404, 'Analytics on draft venue must return 404'); +}); + +test('4. Resuming and completing draft publishes venue to active state', async () => { + const user = await signedInClient(); + + // 1. Save draft + const draftRes = await user.post('/api/venue/onboard', { + name: 'The Glasshouse Terrace', + category: 'rooftop_lounge', + city: 'Hyderabad', + is_draft: true + }); + const venueId = draftRes.json.venue.id; + + // 2. Resume and complete onboarding + const completeRes = await user.post('/api/venue/onboard', { + venue_id: venueId, + name: 'The Glasshouse Terrace', + category: 'rooftop_lounge', + city: 'Hyderabad', + neighbourhood: 'Jubilee Hills', + address_public: 'Road 36, Jubilee Hills', + capacity: 180, + facilities: ['sound_system', 'outdoor_terrace', 'valet_parking'], + photos: ['https://images.unsplash.com/photo-1517457373958-b7bdd4587205'], + is_draft: false + }); + assert.equal(completeRes.status, 201); + assert.equal(completeRes.json.isDraft, false); + + // DB verification: status becomes 'active', onboarding_completed becomes true + const updatedVenue = await db.one('SELECT * FROM venues WHERE id = $1', [venueId]); + assert.equal(updatedVenue.status, 'active', 'Published venue status must be active'); + assert.equal(updatedVenue.onboarding_completed, true, 'Published venue onboarding_completed must be true'); + + // User context now has hasVenue: true + const ctxRes = await user.get('/api/venue/context'); + assert.equal(ctxRes.status, 200); + assert.equal(ctxRes.json.context.hasVenue, true); + assert.equal(ctxRes.json.context.activeVenue.name, 'The Glasshouse Terrace'); + + // Venue page now renders Venue Command Centre shell + const pageRes = await user.get('/venue'); + assert.equal(pageRes.status, 200); + assert.ok(pageRes.text.includes('Venue Command Centre')); + assert.ok(!pageRes.text.includes('venueOnboardForm')); +}); + +test('5. Organisation verification protection: new organisations are unverified; verified cannot be self-assigned', async () => { + const user = await signedInClient(); + + // Complete self-service onboarding + const onboardRes = await user.post('/api/venue/onboard', { + name: 'Pinnacle Club', + category: 'nightclub', + city: 'Bengaluru', + capacity: 200, + is_draft: false + }); + assert.equal(onboardRes.status, 201); + const venueId = onboardRes.json.venue.id; + const orgId = onboardRes.json.venue.org_id; + + // 1. Verify in database: organisation.verified_at MUST be NULL + const orgRow = await db.one('SELECT verified_at FROM organisations WHERE id = $1', [orgId]); + assert.equal(orgRow.verified_at, null, 'New self-service organisation MUST NOT be automatically verified'); + + // 2. Context verification: org_verified must be false + const ctxRes = await user.get('/api/venue/context'); + assert.equal(ctxRes.json.context.activeVenue.orgVerified, false, 'activeVenue.orgVerified must be false'); + assert.equal(ctxRes.json.context.orgs[0].verified, false, 'org.verified must be false'); + + // 3. Profile verification: orgVerified must be false + const profRes = await user.get(`/api/venue/profile?venueId=${venueId}`); + assert.equal(profRes.json.profile.orgVerified, false, 'profile.orgVerified must be false'); + + // 4. Attack: Attempt to self-assign verified status via PATCH /api/venue/profile + const hackPatch = await user.patch(`/api/venue/profile?venueId=${venueId}`, { + verified_at: new Date().toISOString() + }); + assert.equal(hackPatch.status, 400, 'Zod strict schema must reject extra verified_at field'); + + // Verify in DB that verified_at is still NULL + const orgAfterAttack = await db.one('SELECT verified_at FROM organisations WHERE id = $1', [orgId]); + assert.equal(orgAfterAttack.verified_at, null, 'Organisation verified_at must remain NULL'); +}); + +test('6. Existing verified organisations and venues remain verified', async () => { + const client = await signedInClient(); + + // Create an admin-verified organization + const verifiedOrg = await db.one( + `INSERT INTO organisations (kind, name, status, verified_at) + VALUES ('venue_operator', 'Royal Heritage Spaces', 'active', now()) + RETURNING id` + ); + await db.query( + `INSERT INTO org_memberships (user_id, org_id, role, status) VALUES ($1, $2, 'owner', 'active')`, + [client.userId, verifiedOrg.id] + ); + const venue = await db.one( + `INSERT INTO venues (org_id, name, category, capacity, status, onboarding_completed) + VALUES ($1, 'The Grand Ballroom', 'event_space', 500, 'active', true) + RETURNING id`, + [verifiedOrg.id] + ); + + // Context must report verified = true + const ctx = await client.get('/api/venue/context'); + assert.equal(ctx.status, 200); + assert.equal(ctx.json.context.activeVenue.orgVerified, true, 'Pre-verified venue must report orgVerified = true'); + + // Profile must report verified = true + const prof = await client.get(`/api/venue/profile?venueId=${venue.id}`); + assert.equal(prof.status, 200); + assert.equal(prof.json.profile.orgVerified, true); +}); + +test('7. Duplicate venue protection: triggers 409 and safe self-service ownership claim', async () => { + const originalOwner = await signedInClient(); + const legitimateClaimant = await signedInClient(); + + // 1. Original owner onboards venue + const origRes = await originalOwner.post('/api/venue/onboard', { + name: 'Celestial Sky Deck', + category: 'rooftop_lounge', + city: 'Kochi', + address_public: 'Marine Drive, Kochi', + capacity: 150, + is_draft: false + }); + assert.equal(origRes.status, 201); + const targetVenueId = origRes.json.venue.id; + const originalOrgId = origRes.json.venue.org_id; + + // 2. Duplicate registration attempt by claimant triggers 409 Conflict with claim challenge info + const clashRes = await legitimateClaimant.post('/api/venue/onboard', { + name: 'Celestial Sky Deck', + category: 'rooftop_lounge', + city: 'Kochi', + address_public: 'Marine Drive, Kochi', + capacity: 150, + is_draft: false + }); + assert.equal(clashRes.status, 409); + assert.equal(clashRes.json.ok, false); + assert.equal(clashRes.json.error, 'duplicate_venue'); + assert.equal(clashRes.json.existingVenueId, targetVenueId); + assert.equal(clashRes.json.claimAllowed, true); + + // 3. INVARIANT: Ownership is NOT transferred automatically! + const venueCheck1 = await db.one('SELECT org_id FROM venues WHERE id = $1', [targetVenueId]); + assert.equal(venueCheck1.org_id, originalOrgId, 'Venue MUST remain owned by original organisation'); + + // 4. Claimant files a structured self-service ownership claim with business proof + const claimRes = await legitimateClaimant.post('/api/venue/claim', { + venue_id: targetVenueId, + claimant_role: 'Managing Partner', + business_proof_type: 'gstin', + business_proof_ref: '32AABCC1234D1Z9', + contact_name: 'Rahul Nair', + contact_email: 'rahul@celestialdeck.test', + contact_phone: '+91 98450 12345', + notes: 'Registered business partner with physical lease agreement for 5th floor terrace.' + }); + assert.equal(claimRes.status, 201); + assert.equal(claimRes.json.ok, true); + assert.equal(claimRes.json.claim.status, 'pending_verification'); + assert.equal(claimRes.json.claim.business_proof_ref, '32AABCC1234D1Z9'); + + // 5. INVARIANT: Even after claim submission, ownership is NEVER transferred automatically! + const venueCheck2 = await db.one('SELECT org_id FROM venues WHERE id = $1', [targetVenueId]); + assert.equal(venueCheck2.org_id, originalOrgId, 'Ownership must NOT transfer automatically upon claim submission'); + + // 6. Claimant can list their active claims self-service + const claimsList = await legitimateClaimant.get('/api/venue/claims'); + assert.equal(claimsList.status, 200); + assert.equal(claimsList.json.ok, true); + assert.equal(claimsList.json.claims.length, 1); + assert.equal(claimsList.json.claims[0].venueId, targetVenueId); + assert.equal(claimsList.json.claims[0].status, 'pending_verification'); + + // 7. Duplicate claim spam prevention: submitting second claim for same venue returns 409 + const dupClaim = await legitimateClaimant.post('/api/venue/claim', { + venue_id: targetVenueId, + claimant_role: 'Managing Partner', + business_proof_type: 'gstin', + business_proof_ref: '32AABCC1234D1Z9', + contact_name: 'Rahul Nair', + contact_email: 'rahul@celestialdeck.test' + }); + assert.equal(dupClaim.status, 409); + assert.equal(dupClaim.json.error, 'claim_already_pending'); + + // 8. Existing owner cannot claim their own venue + const selfClaim = await originalOwner.post('/api/venue/claim', { + venue_id: targetVenueId, + claimant_role: 'Owner', + business_proof_type: 'gstin', + business_proof_ref: '32AABCC1234D1Z9', + contact_name: 'Self', + contact_email: 'self@celestialdeck.test' + }); + assert.equal(selfClaim.status, 400); + assert.equal(selfClaim.json.error, 'already_owned'); +}); + +test('8. Cross-organisation ownership isolation: outsiders cannot read or edit other venues', async () => { + const owner = await signedInClient(); + const intruder = await signedInClient(); + + const onboardRes = await owner.post('/api/venue/onboard', { + name: 'Sanctuary Lounge', + category: 'cocktail_speakeasy', + city: 'Chennai', + capacity: 90, + is_draft: false + }); + const venueId = onboardRes.json.venue.id; + + // Intruder cannot view profile + const getRes = await intruder.get(`/api/venue/profile?venueId=${venueId}`); + assert.equal(getRes.status, 404); + + // Intruder cannot patch profile + const patchRes = await intruder.patch(`/api/venue/profile?venueId=${venueId}`, { + name: 'Hacked Sanctuary' + }); + assert.equal(patchRes.status, 404); + + // Verify name in DB remains unaltered + const v = await db.one('SELECT name FROM venues WHERE id = $1', [venueId]); + assert.equal(v.name, 'Sanctuary Lounge'); +}); + +test('9. Profile management: owner updates category, neighbourhood, and photos', async () => { + const owner = await signedInClient(); + + const onboardRes = await owner.post('/api/venue/onboard', { + name: 'Loft 42', + category: 'studio_loft', + city: 'Bengaluru', + capacity: 60, + is_draft: false + }); + const venueId = onboardRes.json.venue.id; + + const patchRes = await owner.patch(`/api/venue/profile?venueId=${venueId}`, { + category: 'event_space', + neighbourhood: 'Koramangala 4th Block', + facilities: ['wifi_highspeed', 'projector_av'], + photos: [ + 'https://images.unsplash.com/photo-1522158637959-30385a09e0da', + 'https://images.unsplash.com/photo-1543007630-9710e4a00a20' + ] + }); + + assert.equal(patchRes.status, 200); + assert.equal(patchRes.json.ok, true); + + const profileRes = await owner.get(`/api/venue/profile?venueId=${venueId}`); + assert.equal(profileRes.status, 200); + assert.equal(profileRes.json.profile.category, 'event_space'); + assert.equal(profileRes.json.profile.neighbourhood, 'Koramangala 4th Block'); + assert.equal(profileRes.json.profile.photos.length, 2); +}); + +test('10. Cross-functional enablement: venue operator has organiser capabilities', async () => { + const owner = await signedInClient(); + + await owner.post('/api/venue/onboard', { + name: 'The Terrace Bistro', + category: 'cafe_bistro', + city: 'Chennai', + capacity: 120, + is_draft: false + }); + + // Check organiser permissions in DB + const userRow = await db.one('SELECT organiser_enabled FROM users WHERE id = $1', [owner.userId]); + assert.equal(userRow.organiser_enabled, true); + + // User can access organiser draft creation + const orgPageRes = await owner.get('/organiser/new'); + assert.equal(orgPageRes.status, 200); + assert.ok(orgPageRes.text.includes('Event') || orgPageRes.text.includes('Host')); +}); diff --git a/test/venue.test.js b/test/venue.test.js index a86cc5a..cfe458d 100644 --- a/test/venue.test.js +++ b/test/venue.test.js @@ -93,12 +93,12 @@ test('GET /venue: unauthenticated request renders sign-in gate with Telegram but assert.ok(res.text.includes('/signin?next=%2Fvenue')); }); -test('GET /venue: authenticated user without venue org renders onboarding and application form', async () => { +test('GET /venue: authenticated user without venue org renders direct onboarding wizard', async () => { const nonVenue = await signedInClient(); const res = await nonVenue.get('/venue'); assert.equal(res.status, 200); - assert.ok(res.text.includes('Submit Venue Application')); - assert.ok(res.text.includes('venueApplyForm')); + assert.ok(res.text.includes('Launch Your Venue on NIGHTLIFEZ')); + assert.ok(res.text.includes('venueOnboardForm')); }); test('GET /venue: venue operator owner renders Venue Command Centre shell and assets', async () => { @@ -389,7 +389,7 @@ test('GET /api/venue/reports: outsider gets 404', async () => { // ---------- 9. Venue Application Flow ---------- -test('POST /api/venue/apply: signed-in user submits venue application', async () => { +test('POST /api/venue/apply: signed-in user directly onboards venue via legacy/alias route', async () => { const applicant = await signedInClient(); const appData = { name: 'Vikram Seth', @@ -404,15 +404,14 @@ test('POST /api/venue/apply: signed-in user submits venue application', async () const res = await applicant.post('/api/venue/apply', appData); assert.equal(res.status, 201); assert.equal(res.json.ok, true); - assert.ok(res.json.leadId); + assert.ok(res.json.venueId); - // Context now includes pending application + // User is now an active venue operator with immediate dashboard access const ctxRes = await applicant.get('/api/venue/context'); assert.equal(ctxRes.status, 200); - assert.equal(ctxRes.json.context.hasVenue, false); - assert.ok(ctxRes.json.context.applications.length >= 1); - assert.equal(ctxRes.json.context.applications[0].venueName, 'The Glasshouse Studio'); - assert.equal(ctxRes.json.context.applications[0].status, 'new'); + assert.equal(ctxRes.json.context.hasVenue, true); + assert.ok(ctxRes.json.context.venues.length >= 1); + assert.equal(ctxRes.json.context.venues[0].name, 'The Glasshouse Studio'); }); // ---------- 10. Super Admin & Zero-Venues Resilience ----------