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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions e2e/multi-date-wizard.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () =>
// Verify Payment contradiction notice
const payNotice = page.locator('.notice-warn');
await expect(payNotice).toBeVisible();
await expect(payNotice).toContainText('Online payment is not configured yet');
await expect(payNotice).toContainText(/Online payment is (?:pending gateway configuration|not configured yet)/);

// Verify quick-add chips exist and are accessible
const quickAddGeneral = page.locator('button.chip[data-act="add-tier"][data-preset="general"]');
Expand All @@ -101,7 +101,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () =>
// Check that paid tier displays draft indicator and warning
const draftPill = page.locator('.pill-draft').first();
await expect(draftPill).toBeVisible();
await expect(draftPill).toContainText('Draft — External Checkout Pending');
await expect(draftPill).toContainText(/Paid \((?:Gateway Pending|Draft — External Checkout Pending)\)/);

// Capture Step 2 evidence
await page.screenshot({ path: path.join(ARTIFACT_DIR, 'multi-date-tickets-draft-state.png'), fullPage: true });
Expand Down
1 change: 1 addition & 0 deletions lib/admin-roles.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const ADMIN_TABS = [
['insights', 'Insights', R.INSIGHTS],
['discovery', 'Discovery', R.DISCOVERY],
['events', 'Events', R.ANY],
['finance', 'Finance & Fees', R.FINANCE_VIEW],
['bookings', 'Bookings & payments', R.BOOKINGS],
['orders', 'Orders (SuperProfile)', R.ORDERS],
['memberships', 'Memberships', R.MEMBERSHIPS],
Expand Down
160 changes: 160 additions & 0 deletions lib/handlers/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@ import {
getSuppressionsList
} from '../services/notification-dispatcher.js';
import { listOnboardingAudits } from '../services/community-onboarding.js';
import {
getAdminFinanceOverview,
getVerificationQueue,
confirmFeePayment,
rejectFeePayment,
investigateFeePayment,
setFeeRule,
getActiveFeeRule,
extendPaymentDeadline,
generateAdminFinanceCsv
} from '../services/finance.js';
import { uuid } from '../validate.js';


/** Resolve the admin for this request (bootstrapping the owner once), or throw 401/403. */
Expand Down Expand Up @@ -1284,4 +1296,152 @@ export async function updateCityStatus(ctx) {
sendJson(ctx.res, 200, { ok: true, city });
}

// ---------- NIGHTLIFEZ Admin Finance & Commission Infrastructure ----------

export async function adminFinanceOverview(ctx) {
await guard(ctx, R.FINANCE_VIEW);
const organiserId = ctx.query?.get?.('organiser_id') || null;
const eventId = ctx.query?.get?.('event_id') || null;
const status = ctx.query?.get?.('status') || null;
const minOutstanding = ctx.query?.get?.('min_outstanding') || null;

const overview = await getAdminFinanceOverview({
organiserId,
eventId,
status,
minOutstanding
});

const activeRule = await getActiveFeeRule();
const rules = (await db.query(
`SELECT r.*, a.telegram_user_id AS created_by_tg
FROM infrastructure_fee_rules r
LEFT JOIN admin_users a ON a.id = r.created_by
ORDER BY r.effective_from DESC LIMIT 10`
)).rows;

const auditLogs = (await db.query(
`SELECT * FROM finance_audit_logs ORDER BY created_at DESC LIMIT 30`
)).rows;

sendJson(ctx.res, 200, {
ok: true,
...overview,
activeRule,
rules,
auditLogs
});
}

export async function adminFinanceQueue(ctx) {
await guard(ctx, R.FINANCE_VIEW);
const status = ctx.query?.get?.('status') || 'pending';
const organiserId = ctx.query?.get?.('organiser_id') || null;
const eventId = ctx.query?.get?.('event_id') || null;

const queue = await getVerificationQueue({ status, organiserId, eventId });
sendJson(ctx.res, 200, { ok: true, queue });
}

const ConfirmPaymentBody = z.object({
submissionId: uuid,
bankTxId: z.string().min(4).max(80),
verifiedAmountPaise: z.coerce.number().int().positive().nullable().optional(),
notes: z.string().max(500).default(''),
allocations: z.array(z.object({
invoiceId: uuid,
amountPaise: z.coerce.number().int().positive()
})).optional()
}).strict();

export async function adminConfirmPayment(ctx) {
const a = await guard(ctx, R.FINANCE_VIEW, { write: true });
const body = parse(ConfirmPaymentBody, await readJson(ctx.req));
const result = await confirmFeePayment({
submissionId: body.submissionId,
bankTxId: body.bankTxId,
verifiedAmountPaise: body.verifiedAmountPaise,
notes: body.notes,
adminUser: a.admin,
allocations: body.allocations || []
});
sendJson(ctx.res, 200, { ok: true, ...result });
}

const RejectPaymentBody = z.object({
submissionId: uuid,
reason: z.string().min(5).max(500)
}).strict();

export async function adminRejectPayment(ctx) {
const a = await guard(ctx, R.FINANCE_VIEW, { write: true });
const body = parse(RejectPaymentBody, await readJson(ctx.req));
const result = await rejectFeePayment({
submissionId: body.submissionId,
reason: body.reason,
adminUser: a.admin
});
sendJson(ctx.res, 200, { ok: true, ...result });
}

const InvestigatePaymentBody = z.object({
submissionId: uuid,
notes: z.string().min(3).max(500)
}).strict();

export async function adminInvestigatePayment(ctx) {
const a = await guard(ctx, R.FINANCE_VIEW, { write: true });
const body = parse(InvestigatePaymentBody, await readJson(ctx.req));
const result = await investigateFeePayment({
submissionId: body.submissionId,
notes: body.notes,
adminUser: a.admin
});
sendJson(ctx.res, 200, { ok: true, ...result });
}

const SetFeeRuleBody = z.object({
percentage: z.coerce.number().min(0).max(100),
name: z.string().max(100).default('Platform Infrastructure Fee'),
notes: z.string().max(500).default('')
}).strict();

export async function adminSetFeeRule(ctx) {
const a = await guard(ctx, R.FINANCE_VIEW, { write: true });
const body = parse(SetFeeRuleBody, await readJson(ctx.req));
const rule = await setFeeRule({
percentage: body.percentage,
name: body.name,
notes: body.notes,
adminUser: a.admin
});
sendJson(ctx.res, 201, { ok: true, rule });
}

const ExtendDeadlineBody = z.object({
eventId: uuid,
newDeadline: z.string().min(10).max(80),
reason: z.string().min(5).max(500)
}).strict();

export async function adminExtendDeadline(ctx) {
const a = await guard(ctx, R.FINANCE_VIEW, { write: true });
const body = parse(ExtendDeadlineBody, await readJson(ctx.req));
const event = await extendPaymentDeadline({
eventId: body.eventId,
newDeadline: body.newDeadline,
reason: body.reason,
adminUser: a.admin
});
sendJson(ctx.res, 200, { ok: true, event });
}

export async function adminFinanceExport(ctx) {
await guard(ctx, R.FINANCE_VIEW);
const csv = await generateAdminFinanceCsv();
ctx.res.setHeader('Content-Type', 'text/csv; charset=utf-8');
ctx.res.setHeader('Content-Disposition', 'attachment; filename="nightlifez-admin-finance.csv"');
ctx.res.end(csv);
}


69 changes: 69 additions & 0 deletions lib/handlers/organiser.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ import {
import {
listEventAnnouncements, createEventAnnouncement
} from '../services/event-announcements.js';
import {
getOrganiserFinanceSummary,
submitFeePayment,
generateOrganiserStatementCsv
} from '../services/finance.js';

const id = (v) => {
if (!uuid.safeParse(v).success) throw new HttpError(404, 'not_found', 'Not found');
Expand Down Expand Up @@ -63,6 +68,7 @@ function wizardConfig(user, draftId) {
templates: Object.entries(O.TEMPLATES).map(([key, t]) => ({ key, label: t.label, hint: t.hint, defaults: O.initialDraftData(key) })),
cities: CITIES.map((c) => c.name),
ticketPresets: O.TICKET_PRESETS,
ticketCategories: O.TICKET_CATEGORIES,
questionPresets: O.QUESTION_PRESETS,
categories: Object.entries(CATEGORY_LABELS),
timezones: TIMEZONES,
Expand Down Expand Up @@ -478,3 +484,66 @@ export async function guestTicket(ctx) {
const tickets = await getBookingTickets(id(ctx.params.id), user);
sendJson(ctx.res, 200, { ok: true, tickets });
}

// ---------- Organiser Finance & Infrastructure Fee ----------

export async function organiserFinance(ctx) {
const user = await organiser(ctx);
await rateLimit(`org:finance:${user.id}`, 60, 60);
const data = await getOrganiserFinanceSummary(user.id);
sendJson(ctx.res, 200, { ok: true, ...data });
}

export async function eventFinance(ctx) {
const user = await requireUser(ctx.req);
const eventId = id(ctx.params.id);
await authorize(user, 'event.manage', { eventId });
await rateLimit(`org:evtfinance:${user.id}`, 60, 60);
const data = await getOrganiserFinanceSummary(user.id);
const eventData = data.events.find((e) => e.eventId === eventId);
if (!eventData) throw new HttpError(404, 'event_not_found', 'Event finance record not found');
const submissions = data.submissions.filter((s) => s.payment_reference === eventData.paymentReference || s.invoice_number === eventData.invoiceNumber);
sendJson(ctx.res, 200, {
ok: true,
event: eventData,
account: data.account,
submissions,
platformUpi: data.platformUpi
});
}

const SubmitPaymentBody = z.object({
invoiceId: uuid.nullable().optional(),
paymentReference: z.string().max(80).nullable().optional(),
amountPaise: z.coerce.number().int().positive(),
utrNumber: z.string().min(6).max(50),
payerUpiId: z.string().max(100).nullable().optional(),
notes: z.string().max(500).nullable().optional(),
screenshotUrl: z.string().max(2000).nullable().optional()
}).strict();

export async function submitOrganiserFeePayment(ctx) {
const user = await organiser(ctx, { write: true, scope: 'fee_payment' });
await rateLimit(`org:feepay:${user.id}`, 20, 600);
const body = parse(SubmitPaymentBody, await readJson(ctx.req));
const res = await submitFeePayment({
organiserId: user.id,
invoiceId: body.invoiceId || null,
paymentReference: body.paymentReference || null,
amountPaise: body.amountPaise,
utrNumber: body.utrNumber,
payerUpiId: body.payerUpiId || null,
notes: body.notes || '',
screenshotUrl: body.screenshotUrl || null
});
sendJson(ctx.res, 201, { ok: true, ...res });
}

export async function downloadOrganiserStatement(ctx) {
const user = await organiser(ctx);
await rateLimit(`org:statement:${user.id}`, 15, 60);
const csv = await generateOrganiserStatementCsv(user.id);
ctx.res.setHeader('Content-Type', 'text/csv; charset=utf-8');
ctx.res.setHeader('Content-Disposition', 'attachment; filename="nightlifez-financial-statement.csv"');
ctx.res.end(csv);
}
4 changes: 2 additions & 2 deletions lib/handlers/upi-checkout.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ export async function upiCheckoutPage({ req, res, params, query, ip }) {
let tier;
if (tierId) {
tier = await db.one(
`SELECT id, name, kind, price_paise, max_per_booking FROM ticket_types
`SELECT id, name, kind, price_paise, max_per_booking, category, admit_count, session_id, valid_on FROM ticket_types
WHERE id = $1 AND event_id = $2 AND active`,
[tierId, event.id]
);
} else {
tier = await db.one(
`SELECT id, name, kind, price_paise, max_per_booking FROM ticket_types
`SELECT id, name, kind, price_paise, max_per_booking, category, admit_count, session_id, valid_on FROM ticket_types
WHERE event_id = $1 AND active AND kind = 'paid'
ORDER BY sort_order ASC, price_paise ASC LIMIT 1`,
[event.id]
Expand Down
Loading
Loading