Add group tickets with named attendees
Events can take a name (and optional email/phone) for each main-ticket place. Each named person gets their own quantity-1 ticket and attendee form; unnamed places share one ticket. Tickets go to the payer or to each person, attendees matching one existing account are linked to it, and the payer can edit names and send form links from My Events. Ticket generation is now planned per line (utils/attendees.js), free registrations use the same generator, and guest registration matches accounts by phone too, refusing conflicting email/phone pairs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Finding an existing account from an email and/or phone number.
|
||||
*
|
||||
* Email and phone are looked up separately rather than with one OR query, so an email
|
||||
* belonging to one account and a phone belonging to another can never be silently
|
||||
* collapsed into whichever matches first — that would let a registration hijack or
|
||||
* corrupt someone else's account. Phones are tried in both 27xxx and 0xxx forms.
|
||||
*/
|
||||
|
||||
const prisma = require('../config/db');
|
||||
|
||||
function hasValidEmail(email) {
|
||||
return !!(email && typeof email === 'string' && email.includes('@'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<{ phone: string, emailUser: object|null, phoneUser: object|null,
|
||||
* conflict: boolean, user: object|null }>}
|
||||
* `user` is the single matched account (null when none, or when email and phone point
|
||||
* at two different accounts — `conflict` is then true).
|
||||
*/
|
||||
async function findAccountByContact({ email, phone: rawPhone }, db = prisma) {
|
||||
const { normalizeZAPhone } = require('./whatsapp');
|
||||
const phone = normalizeZAPhone(rawPhone) || String(rawPhone || '').replace(/\D/g, '');
|
||||
const phoneAlt = phone && phone.startsWith('27') ? '0' + phone.slice(2) : (phone && phone.length === 9 ? '27' + phone : null);
|
||||
|
||||
const [emailUser, phoneUser] = await Promise.all([
|
||||
hasValidEmail(email) ? db.user.findUnique({ where: { email: String(email).trim() } }) : null,
|
||||
phone ? db.user.findFirst({ where: { OR: [{ phoneNumber: phone }, ...(phoneAlt ? [{ phoneNumber: phoneAlt }] : [])] } }) : null,
|
||||
]);
|
||||
|
||||
const conflict = !!(emailUser && phoneUser && emailUser.id !== phoneUser.id);
|
||||
return { phone, emailUser, phoneUser, conflict, user: conflict ? null : (emailUser || phoneUser || null) };
|
||||
}
|
||||
|
||||
module.exports = { findAccountByContact, hasValidEmail };
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Group tickets — named attendees on a registration.
|
||||
*
|
||||
* Rules:
|
||||
* - Only main-ticket places can be named, and only on events with
|
||||
* allowNamedAttendees. Each named attendee gets their own quantity-1 ticket; any
|
||||
* places left unnamed share one quantity ticket, as before.
|
||||
* - The payer stays the registration owner (billing, invoices, payments). An attendee
|
||||
* whose email/phone matches an existing account is linked to it, so the ticket also
|
||||
* shows in that person's dashboard — unless email and phone point at two different
|
||||
* accounts, in which case nothing is linked.
|
||||
* - Registration.ticketDelivery = 'each' sends each attendee their own ticket by
|
||||
* email/WhatsApp; attendees with no contact details fall back to the payer.
|
||||
*/
|
||||
|
||||
const prisma = require('../config/db');
|
||||
const { findAccountByContact } = require('./accountMatch');
|
||||
|
||||
const lineKey = (eventOptionId, variantId) => `${eventOptionId}::${variantId || ''}`;
|
||||
|
||||
function attendeeError(message) {
|
||||
const err = new Error(message);
|
||||
err.statusCode = 400;
|
||||
return err;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks attendees against the event and the number of places on each line. Pure.
|
||||
* Returns the cleaned list (trimmed strings, nulls for blanks).
|
||||
*
|
||||
* @param {object} event - with allowNamedAttendees and eventOptions[{ id, isMainTicket, name }]
|
||||
* @param {object} placesByKey - total places each line will have, keyed by lineKey()
|
||||
* @param {Array} attendees - [{ eventOptionId, variantId?, name, email?, phone? }]
|
||||
* @param {object} [namedByKey] - places on those lines already named (and being kept)
|
||||
*/
|
||||
function validateAttendees(event, placesByKey, attendees, namedByKey = {}) {
|
||||
if (!attendees || attendees.length === 0) return [];
|
||||
if (!event.allowNamedAttendees) throw attendeeError('This event doesn\'t take attendee names.');
|
||||
if (!Array.isArray(attendees)) throw attendeeError('attendees must be a list');
|
||||
|
||||
const countByKey = {};
|
||||
return attendees.map((a, i) => {
|
||||
const option = (event.eventOptions || []).find(o => o.id === a?.eventOptionId);
|
||||
if (!option) throw attendeeError(`Attendee ${i + 1}: unknown ticket option.`);
|
||||
if (!option.isMainTicket) throw attendeeError(`Attendee ${i + 1}: names can only be given for "${option.name}" main tickets.`);
|
||||
const name = String(a.name || '').trim();
|
||||
if (!name) throw attendeeError(`Attendee ${i + 1}: enter a name.`);
|
||||
const email = String(a.email || '').trim() || null;
|
||||
if (email && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) throw attendeeError(`Attendee ${i + 1}: "${email}" isn't a valid email address.`);
|
||||
const phone = String(a.phone || '').trim() || null;
|
||||
const key = lineKey(a.eventOptionId, a.variantId);
|
||||
countByKey[key] = (countByKey[key] || 0) + 1;
|
||||
if (countByKey[key] + (namedByKey[key] || 0) > (placesByKey[key] || 0)) {
|
||||
throw attendeeError(`More names than "${option.name}" tickets.`);
|
||||
}
|
||||
return { eventOptionId: a.eventOptionId, variantId: a.variantId || null, name, email, phone };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Works out the tickets one registration line should have, given its named attendees.
|
||||
* Pure — returns operations for the caller to run.
|
||||
*
|
||||
* - Every attendee gets a quantity-1 ticket (holderUserId follows the attendee's account).
|
||||
* - Unnamed places share one quantity ticket; a scanned one is never deleted or shrunk
|
||||
* below what's been redeemed.
|
||||
* - Tickets for attendees that no longer exist are removed unless already scanned.
|
||||
*
|
||||
* @param {object} line - { quantity }
|
||||
* @param {Array} attendees - [{ id, userId }]
|
||||
* @param {Array} tickets - existing [{ id, attendeeId, quantity, holderUserId, usages: [] }]
|
||||
* @returns {{ create: Array<{attendeeId, holderUserId, quantity}>, update: Array<{id, data}>, remove: string[] }}
|
||||
*/
|
||||
function planLineTickets(line, attendees, tickets) {
|
||||
const scanned = (t) => (t.usages || []).length > 0;
|
||||
const redeemed = (t) => (t.usages || []).reduce((s, u) => s + (u.quantityRedeemed || 0), 0);
|
||||
const ops = { create: [], update: [], remove: [] };
|
||||
const attendeeIds = new Set(attendees.map(a => a.id));
|
||||
|
||||
const byAttendee = new Map();
|
||||
const orphanNamed = [];
|
||||
const shared = [];
|
||||
for (const t of tickets) {
|
||||
if (t.attendeeId && attendeeIds.has(t.attendeeId)) byAttendee.set(t.attendeeId, t);
|
||||
else if (t.attendeeId) orphanNamed.push(t);
|
||||
else shared.push(t);
|
||||
}
|
||||
|
||||
// Tickets whose attendee was removed: drop unless already used (then keep, as shared).
|
||||
let keptScannedOrphans = 0;
|
||||
for (const t of orphanNamed) {
|
||||
if (scanned(t)) keptScannedOrphans += t.quantity || 1;
|
||||
else ops.remove.push(t.id);
|
||||
}
|
||||
|
||||
for (const a of attendees) {
|
||||
const t = byAttendee.get(a.id);
|
||||
if (!t) {
|
||||
ops.create.push({ attendeeId: a.id, holderUserId: a.userId || null, quantity: 1 });
|
||||
} else if ((t.holderUserId || null) !== (a.userId || null) || (t.quantity || 1) !== 1) {
|
||||
ops.update.push({ id: t.id, data: { holderUserId: a.userId || null, ...(scanned(t) ? {} : { quantity: 1 }) } });
|
||||
}
|
||||
}
|
||||
|
||||
// Unnamed places share one ticket.
|
||||
const remainder = Math.max(0, (line.quantity || 0) - attendees.length - keptScannedOrphans);
|
||||
const sorted = [...shared].sort((a, b) => (scanned(b) ? 1 : 0) - (scanned(a) ? 1 : 0));
|
||||
const [primary, ...extras] = sorted;
|
||||
if (primary) {
|
||||
const floor = scanned(primary) ? redeemed(primary) : 0;
|
||||
if (remainder === 0 && !scanned(primary)) ops.remove.push(primary.id);
|
||||
else {
|
||||
const qty = Math.max(remainder, floor);
|
||||
if (qty !== primary.quantity) ops.update.push({ id: primary.id, data: { quantity: qty } });
|
||||
}
|
||||
} else if (remainder > 0) {
|
||||
ops.create.push({ attendeeId: null, holderUserId: null, quantity: remainder });
|
||||
}
|
||||
for (const t of extras) if (!scanned(t)) ops.remove.push(t.id);
|
||||
|
||||
return ops;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves new attendees on a registration, linking each to its registration line and to
|
||||
* a matching account when there is exactly one.
|
||||
*/
|
||||
async function createAttendees(registrationId, attendees, db = prisma) {
|
||||
if (!attendees || attendees.length === 0) return [];
|
||||
const lines = await db.registrationOption.findMany({ where: { registrationId } });
|
||||
const existing = await db.attendee.findMany({ where: { registrationId }, select: { registrationOptionId: true } });
|
||||
const orderByLine = {};
|
||||
existing.forEach(a => { orderByLine[a.registrationOptionId] = (orderByLine[a.registrationOptionId] || 0) + 1; });
|
||||
|
||||
const created = [];
|
||||
for (const a of attendees) {
|
||||
const line = lines.find(l => l.eventOptionId === a.eventOptionId && (l.variantId || null) === (a.variantId || null));
|
||||
const match = (a.email || a.phone) ? await findAccountByContact({ email: a.email, phone: a.phone }, db) : { user: null };
|
||||
const order = orderByLine[line?.id] || 0;
|
||||
orderByLine[line?.id] = order + 1;
|
||||
created.push(await db.attendee.create({
|
||||
data: {
|
||||
registrationId,
|
||||
registrationOptionId: line?.id || null,
|
||||
eventOptionId: a.eventOptionId,
|
||||
variantId: a.variantId || null,
|
||||
name: a.name,
|
||||
email: a.email,
|
||||
phone: a.phone,
|
||||
userId: match.user?.id || null,
|
||||
order,
|
||||
},
|
||||
}));
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
/** Named places already on a registration, per line key — for validating additions. */
|
||||
async function namedPlacesByKey(registrationId, db = prisma) {
|
||||
const rows = await db.attendee.findMany({ where: { registrationId }, select: { eventOptionId: true, variantId: true } });
|
||||
const out = {};
|
||||
rows.forEach(r => { const k = lineKey(r.eventOptionId, r.variantId); out[k] = (out[k] || 0) + 1; });
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = { lineKey, validateAttendees, planLineTickets, createAttendees, namedPlacesByKey, attendeeError };
|
||||
@@ -103,11 +103,31 @@ async function loadTicketFull(ticketId) {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true } },
|
||||
event: true,
|
||||
registrationOption: { include: { eventOption: true, variant: true } },
|
||||
registrationOption: { include: { eventOption: true, variant: true, registration: { select: { ticketDelivery: true } } } },
|
||||
attendee: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Who a ticket's messages go to: a named attendee with contact details when the
|
||||
* registration sends each person their own tickets, otherwise the payer.
|
||||
*/
|
||||
function ticketRecipient(ticket) {
|
||||
const a = ticket.attendee;
|
||||
if (a && (a.email || a.phone) && ticket.registrationOption?.registration?.ticketDelivery === 'each') {
|
||||
const hasEmail = !!(a.email && a.email.includes('@'));
|
||||
return {
|
||||
id: a.userId || null,
|
||||
name: a.name,
|
||||
email: hasEmail ? a.email : null,
|
||||
phoneNumber: a.phone || null,
|
||||
notificationPreference: hasEmail && a.phone ? 'both' : hasEmail ? 'email' : 'whatsapp',
|
||||
};
|
||||
}
|
||||
return ticket.user;
|
||||
}
|
||||
|
||||
async function loadPaymentFull(paymentId) {
|
||||
return prisma.payment.findUnique({
|
||||
where: { id: paymentId },
|
||||
@@ -1154,7 +1174,7 @@ async function sendCheckInEmails(ticketId, qtyRedeemed, totalRedeemed, remaining
|
||||
try {
|
||||
const ticket = await loadTicketFull(ticketId);
|
||||
if (!ticket) return;
|
||||
const user = ticket.user;
|
||||
const user = ticketRecipient(ticket);
|
||||
const { shouldEmail, waText, waTextAny } = require('./notify');
|
||||
const { buildWACheckIn } = require('./waMessages');
|
||||
|
||||
@@ -1446,7 +1466,44 @@ async function sendDailyEventSummaries(now = new Date()) {
|
||||
}
|
||||
}
|
||||
|
||||
// Sent when a payer (or staff) asks for a named attendee to fill in their own form.
|
||||
// Always tries both channels the attendee has, regardless of anyone's preference.
|
||||
async function sendAttendeeFormLinkMessage(attendee) {
|
||||
const org = getOrg();
|
||||
const reg = attendee.registration;
|
||||
const eventTitle = reg?.event?.title || 'the event';
|
||||
const link = `${org.url}/forms?registrationId=${encodeURIComponent(attendee.registrationId)}&attendeeId=${encodeURIComponent(attendee.id)}`;
|
||||
const payer = reg?.user?.name || 'Someone';
|
||||
const sent = [];
|
||||
|
||||
if (attendee.email && attendee.email.includes('@')) {
|
||||
const html = emailWrapper(`
|
||||
<p style="font-size:22px;font-weight:800;color:#0f172a;margin:0 0 8px 0">Please fill in your form</p>
|
||||
<p style="margin:0 0 8px 0;color:#374151;font-family:${ff}">Hi <strong>${attendee.name}</strong>,</p>
|
||||
<p style="margin:0 0 24px 0;color:#374151;font-family:${ff}">${payer} registered you for <strong>${eventTitle}</strong>. Please fill in your attendee form.</p>
|
||||
${ctaButton('Fill in my form', link)}
|
||||
${fallbackLink(link)}
|
||||
`, { preheader: `Your attendee form for ${eventTitle}` });
|
||||
try {
|
||||
await sendMail({ to: attendee.email, subject: `Your attendee form for ${eventTitle}`, html, text: `Hi ${attendee.name},\n\n${payer} registered you for ${eventTitle}. Please fill in your attendee form:\n${link}\n\n${org.name}` });
|
||||
sent.push('email');
|
||||
} catch (e) {
|
||||
console.warn('[attendee form link] email failed:', e?.message || e);
|
||||
}
|
||||
}
|
||||
if (attendee.phone) {
|
||||
const { waTextAny } = require('./notify');
|
||||
const { isValidZAPhone } = require('./whatsapp');
|
||||
if (isValidZAPhone(attendee.phone)) {
|
||||
await waTextAny({ name: attendee.name, phoneNumber: attendee.phone }, `Hi ${attendee.name}, ${payer} registered you for *${eventTitle}*. Please fill in your attendee form: ${link}`);
|
||||
sent.push('WhatsApp');
|
||||
}
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sendAttendeeFormLinkMessage,
|
||||
sendRegistrationEmails,
|
||||
sendRegistrationUpdatedEmails,
|
||||
sendPaymentEmails,
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
const prisma = require('../config/db');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const { planLineTickets } = require('./attendees');
|
||||
|
||||
/**
|
||||
* Generate tickets for a registration when payment status is "paid".
|
||||
*
|
||||
* Rules:
|
||||
* - Exactly ONE ticket per registrationOption (keyed by eventOptionId).
|
||||
* - Each named attendee (group tickets) gets their own quantity-1 ticket; the rest of a
|
||||
* line's places share ONE quantity ticket per registrationOption (see
|
||||
* utils/attendees.js planLineTickets).
|
||||
* - If duplicate registrationOptions exist for the same eventOptionId (old data),
|
||||
* consolidate them: merge quantities, keep the one with scan history, delete the rest.
|
||||
* - If duplicate ticket records exist for the same registrationOption (old data),
|
||||
@@ -90,55 +93,40 @@ const generateTicketsForRegistration = async (registrationId) => {
|
||||
});
|
||||
}));
|
||||
|
||||
// ── Step 2: For each unique option, ensure exactly one ticket with correct qty ──
|
||||
// ── Step 2: For each unique option, sync its tickets: one per named attendee, plus
|
||||
// one shared quantity ticket for any unnamed places ──
|
||||
// Re-read fresh list (some options may have been deleted above)
|
||||
const freshOptions = await prisma.registrationOption.findMany({
|
||||
where: { registrationId },
|
||||
include: {
|
||||
tickets: { include: { usages: true }, orderBy: { createdAt: 'asc' } }
|
||||
tickets: { include: { usages: true }, orderBy: { createdAt: 'asc' } },
|
||||
attendees: { orderBy: { order: 'asc' } },
|
||||
}
|
||||
});
|
||||
|
||||
// Each option owns disjoint tickets, so resolve them concurrently instead of one at a time.
|
||||
const perOptionResults = await Promise.all(freshOptions.map(async (option) => {
|
||||
const targetQty = option.quantity || 1;
|
||||
const existingTickets = option.tickets || [];
|
||||
|
||||
if (existingTickets.length === 0) {
|
||||
// Create one ticket
|
||||
return prisma.ticket.create({
|
||||
data: {
|
||||
id: uuidv4(),
|
||||
qrCode: uuidv4(),
|
||||
registrationOptionId: option.id,
|
||||
userId: registration.userId,
|
||||
eventId: registration.eventId,
|
||||
quantity: targetQty,
|
||||
updatedAt: new Date()
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Pick primary: prefer scanned, otherwise oldest
|
||||
const withUsages = existingTickets.filter(t => (t.usages || []).length > 0);
|
||||
const primary = withUsages.length > 0 ? withUsages[0] : existingTickets[0];
|
||||
|
||||
const updates = [];
|
||||
// Update quantity on primary if needed
|
||||
if (primary.quantity !== targetQty) {
|
||||
updates.push(prisma.ticket.update({ where: { id: primary.id }, data: { quantity: targetQty, updatedAt: new Date() } }));
|
||||
}
|
||||
|
||||
// Delete unscanned duplicates
|
||||
const dups = existingTickets.filter(t => t.id !== primary.id && (t.usages || []).length === 0);
|
||||
if (dups.length > 0) {
|
||||
updates.push(prisma.ticket.deleteMany({ where: { id: { in: dups.map(t => t.id) } } }));
|
||||
}
|
||||
if (updates.length > 0) await Promise.all(updates);
|
||||
return null;
|
||||
const plan = planLineTickets({ quantity: option.quantity || 1 }, option.attendees || [], option.tickets || []);
|
||||
await Promise.all([
|
||||
plan.remove.length ? prisma.ticket.deleteMany({ where: { id: { in: plan.remove } } }) : null,
|
||||
...plan.update.map(u => prisma.ticket.update({ where: { id: u.id }, data: { ...u.data, updatedAt: new Date() } })),
|
||||
]);
|
||||
return Promise.all(plan.create.map(c => prisma.ticket.create({
|
||||
data: {
|
||||
id: uuidv4(),
|
||||
qrCode: uuidv4(),
|
||||
registrationOptionId: option.id,
|
||||
userId: registration.userId,
|
||||
eventId: registration.eventId,
|
||||
quantity: c.quantity,
|
||||
attendeeId: c.attendeeId,
|
||||
holderUserId: c.holderUserId,
|
||||
updatedAt: new Date()
|
||||
}
|
||||
})));
|
||||
}));
|
||||
|
||||
return perOptionResults.filter(Boolean);
|
||||
return perOptionResults.flat();
|
||||
} catch (error) {
|
||||
console.error('Error generating tickets:', error);
|
||||
throw error;
|
||||
|
||||
Reference in New Issue
Block a user