Skip to content
Merged
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
4 changes: 4 additions & 0 deletions lib/handlers/organiser.js
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,7 @@ export async function guestTicket(ctx) {

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 });
}
Expand All @@ -497,6 +498,7 @@ 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');
Expand All @@ -522,6 +524,7 @@ const SubmitPaymentBody = z.object({

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,
Expand All @@ -538,6 +541,7 @@ export async function submitOrganiserFeePayment(ctx) {

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"');
Expand Down
98 changes: 92 additions & 6 deletions lib/services/finance.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,28 @@ import crypto from 'node:crypto';
import { db } from '../db.js';
import { HttpError } from '../http.js';
import { logger } from '../logger.js';
import { env } from '../config.js';
import { env, isProductionRuntime } from '../config.js';

export const DEFAULT_FEE_PERCENTAGE = 5.00;

export function getPlatformFinanceUpi() {
return env('NIGHTLIFEZ_FINANCE_UPI_ID') || 'nightlifez.finance@icici';
const configured = env('NIGHTLIFEZ_FINANCE_UPI_ID');
if (isProductionRuntime()) {
// In production runtime, development fallback, placeholder, mock, or test VPAs are strictly prohibited.
if (!configured || configured === 'nightlifez.finance@icici') return null;
if (/^(test|dummy|mock|placeholder|fake|none|null)/i.test(configured)) return null;
return configured;
}
return configured || 'nightlifez.finance@icici';
}

export function getPlatformFinanceName() {
return env('NIGHTLIFEZ_FINANCE_NAME') || 'NIGHTLIFEZ Experiences Private Limited';
const configured = env('NIGHTLIFEZ_FINANCE_NAME');
if (isProductionRuntime()) {
// In production, do not silently fabricate a legal entity name
return configured || null;
}
return configured || 'NIGHTLIFEZ Experiences Private Limited';
}

/**
Expand All @@ -32,6 +44,33 @@ export function isValidUtr(ref) {
return true;
}

/**
* Validates screenshot or evidence proof URLs.
* Allows valid https:// URLs or local relative paths in /uploads/ or /media/.
* Strictly forbids javascript:, data:, file:, and control characters.
*/
export function isValidEvidenceUrl(url) {
if (!url || typeof url !== 'string') return false;
const trimmed = url.trim();
if (trimmed.length > 2048) return false;
if (/[\r\n\t\0]/.test(trimmed)) return false;
if (/^(javascript|data|file|vbscript):/i.test(trimmed)) return false;

// Allow relative upload paths e.g. /uploads/evidence.jpg
if (/^\/(uploads|media|assets)\/[A-Za-z0-9_\-./]+$/.test(trimmed)) {
if (trimmed.includes('..')) return false;
return true;
}

// Allow absolute https URLs
try {
const parsed = new URL(trimmed);
return parsed.protocol === 'https:' && !parsed.username && !parsed.password;
} catch {
return false;
}
}

/**
* Verifies finance or super_admin authorization from an active admin_users row.
*/
Expand Down Expand Up @@ -222,6 +261,15 @@ export async function recordBookingFeeEntry(booking, event, tier, c = db) {
return null;
}

// 0. Upfront Idempotency Check: if an entry already exists for this booking, return immediately
const existingEntry = (await c.query(
`SELECT * FROM infrastructure_fee_entries WHERE booking_id = $1`,
[booking.id]
)).rows[0];
if (existingEntry) {
return { feeEntry: existingEntry, duplicate: true };
}

const snapshot = {
ruleId: activeRule.id,
feePercentage: feePct,
Expand Down Expand Up @@ -498,11 +546,23 @@ export async function submitFeePayment({
throw new HttpError(400, 'validation', 'Submitted amount must be greater than zero');
}

if (isProductionRuntime() && !getPlatformFinanceUpi()) {
throw new HttpError(503, 'platform_upi_not_configured', 'Official platform settlement UPI is not configured. Direct fee submission claims are disabled until the official platform account is active.');
}

const cleanUtr = String(utrNumber || '').trim();
if (!isValidUtr(cleanUtr)) {
throw new HttpError(400, 'validation', 'Please enter a valid 12-character bank UTR reference number');
}

let cleanScreenshotUrl = null;
if (screenshotUrl) {
cleanScreenshotUrl = String(screenshotUrl).trim();
if (!isValidEvidenceUrl(cleanScreenshotUrl)) {
throw new HttpError(400, 'validation', 'Invalid screenshot URL: only HTTPS or safe upload paths are permitted');
}
}

return c.tx(async (tx) => {
// 1. Prevent duplicate UTR
const dupSubmission = (await tx.query(
Expand All @@ -528,11 +588,17 @@ export async function submitFeePayment({
`SELECT * FROM organiser_fee_invoices WHERE id = $1 AND organiser_id = $2`,
[invoiceId, organiserId]
)).rows[0];
if (!inv) {
throw new HttpError(404, 'invoice_not_found', 'Invoice not found or does not belong to this organiser');
}
} else if (paymentReference) {
inv = (await tx.query(
`SELECT * FROM organiser_fee_invoices WHERE payment_reference = $1 AND organiser_id = $2`,
[paymentReference, organiserId]
)).rows[0];
if (!inv) {
throw new HttpError(404, 'invoice_not_found', 'Payment reference not found or does not belong to this organiser');
}
}

const ref = inv?.payment_reference || paymentReference || generatePaymentReference();
Expand Down Expand Up @@ -560,7 +626,7 @@ export async function submitFeePayment({
cleanUtr,
payerUpiId ? String(payerUpiId).trim() : null,
notes ? String(notes).trim() : null,
screenshotUrl || null
cleanScreenshotUrl
]
)).rows[0];

Expand Down Expand Up @@ -735,6 +801,14 @@ export async function confirmFeePayment({

if (!inv) throw new HttpError(404, 'invoice_not_found', `Invoice ${alloc.invoiceId} not found`);

if (inv.organiser_id !== submission.organiser_id) {
throw new HttpError(400, 'cross_organiser_allocation', `Invoice ${inv.invoice_number} does not belong to the payment organiser`);
}

if (inv.status === 'cancelled') {
throw new HttpError(400, 'invalid_invoice_status', `Cannot allocate payment to cancelled invoice ${inv.invoice_number}`);
}

if (alloc.amountPaise > inv.outstanding_amount_paise) {
throw new HttpError(400, 'excess_allocation', `Allocation of ₹${(alloc.amountPaise / 100).toFixed(2)} exceeds invoice ${inv.invoice_number} outstanding amount of ₹${(inv.outstanding_amount_paise / 100).toFixed(2)}`);
}
Expand Down Expand Up @@ -868,6 +942,10 @@ export async function rejectFeePayment({ submissionId, reason, adminUser }, c =
throw new HttpError(409, 'already_verified', 'Cannot reject an already confirmed and verified payment');
}

if (sub.status === 'rejected') {
throw new HttpError(409, 'already_rejected', 'This payment submission has already been rejected');
}

const updated = (await tx.query(
`UPDATE organiser_fee_payment_submissions SET
status = 'rejected',
Expand Down Expand Up @@ -930,6 +1008,14 @@ export async function investigateFeePayment({ submissionId, notes, adminUser },
throw new HttpError(404, 'not_found', 'Payment submission not found');
}

if (sub.status === 'verified') {
throw new HttpError(409, 'already_verified', 'Cannot investigate an already verified and settled payment');
}

if (sub.status === 'rejected') {
throw new HttpError(409, 'already_rejected', 'Cannot investigate an already rejected payment');
}

const updated = (await tx.query(
`UPDATE organiser_fee_payment_submissions SET
status = 'under_investigation',
Expand Down Expand Up @@ -1134,12 +1220,12 @@ export async function getOrganiserFinanceSummary(organiserId, c = db) {
platformUpi: {
vpa: getPlatformFinanceUpi(),
name: getPlatformFinanceName(),
instructions: [
instructions: getPlatformFinanceUpi() ? [
'1. Transfer the exact fee amount via UPI or Net Banking to our official NIGHTLIFEZ UPI ID.',
'2. Add your unique Payment Reference in the transaction remarks/notes.',
'3. Enter the 12-digit bank UTR reference number below and submit your claim.',
'4. Our finance team verifies the incoming credit with our bank before marking the invoice settled.'
]
] : []
}
};
}
Expand Down
22 changes: 17 additions & 5 deletions lib/services/upi-payments.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,13 +292,25 @@ export async function createUpiPaymentIntent({
}
}

// 4. Generate Order ID, calculate transparent 5% platform fee & call Payment Adapter
// 4. Generate Order ID, calculate transparent 5% platform fee for organiser events & call Payment Adapter
const orderId = newUpiOrderId();
const guestToken = crypto.randomBytes(24).toString('base64url');
const baseAmountPaise = tier.price_paise * qty;
const activeRule = await getActiveFeeRule(c);
const feePct = Number(activeRule?.fee_percentage ?? DEFAULT_FEE_PERCENTAGE);
const calc = calculateInfrastructureFee(baseAmountPaise, feePct);
let feePct = 0;
let feeRuleId = null;
let calc = {
basePaise: baseAmountPaise,
feePaise: 0,
totalPaise: baseAmountPaise,
feePercentage: 0
};

if (event.organiser_user_id) {
const activeRule = await getActiveFeeRule(c);
feePct = Number(activeRule?.fee_percentage ?? DEFAULT_FEE_PERCENTAGE);
feeRuleId = activeRule?.id || null;
calc = calculateInfrastructureFee(baseAmountPaise, feePct);
}
const amountPaise = calc.totalPaise;
const adapter = getAdapter();

Expand Down Expand Up @@ -356,7 +368,7 @@ export async function createUpiPaymentIntent({
feePaise: calc.feePaise,
totalAmountPaise: calc.totalPaise,
feePercentage: feePct,
feeRuleId: activeRule?.id || null,
feeRuleId: feeRuleId,
organiserUpiId: event.organiser_upi_id || null
})
]
Expand Down
1 change: 1 addition & 0 deletions public/css/organiser.css
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,7 @@
.org-fin-table { width: 100%; border-collapse: collapse; font-size: 0.88rem; }
.org-fin-table th, .org-fin-table td { padding: 10px 12px; text-align: left; border-bottom: 1px solid var(--line); }
.org-fin-table th { color: var(--muted); font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.05em; }
.org-fin-btn, .org-fin-card a.btn, .org-fin-card button.btn { max-width: 100%; white-space: normal; text-align: center; word-break: break-word; }
.pill-ok { background: rgba(0, 255, 136, 0.15); border-color: rgba(0, 255, 136, 0.4); color: var(--neon-green, #00FF88); }
.pill-info { background: rgba(0, 217, 255, 0.15); border-color: rgba(0, 217, 255, 0.4); color: var(--neon-cyan, #00D9FF); }
.pill-warn { background: rgba(255, 184, 0, 0.15); border-color: rgba(255, 184, 0, 0.4); color: #ffb800; }
Expand Down
10 changes: 10 additions & 0 deletions public/js/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,16 @@
['Bank UTR Reference', function (s) { return el('code', { text: s.utr_number }); }],
['Submitted On', function (s) { return fmtDT(s.created_at); }],
['Outstanding Before', function (s) { return rupees(s.outstanding_before_confirmation_paise); }],
['Proof', function (s) {
if (!s.screenshot_url) return el('span', { class: 'muted small', text: 'None' });
return el('a', {
href: s.screenshot_url,
target: '_blank',
rel: 'noopener noreferrer',
class: 'link-subtle small',
text: 'View Proof ↗'
});
}],
['Status', function (s) { return pill(s.status); }],
['', function (s) {
if (s.status === 'verified') return el('span', { class: 'muted small', text: 'Verified' });
Expand Down
Loading
Loading