Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
1de0cc6940
|
|||
|
b6499eb7b3
|
|||
| b05f6b9da0 |
+6
-1
@@ -16,7 +16,12 @@ FEEDBACK_RATE_LIMIT_MAX=5
|
|||||||
FEEDBACK_RATE_LIMIT_WINDOW_MIN=10
|
FEEDBACK_RATE_LIMIT_WINDOW_MIN=10
|
||||||
SALESFORCE_ENABLED=false
|
SALESFORCE_ENABLED=false
|
||||||
SALESFORCE_API_URL=
|
SALESFORCE_API_URL=
|
||||||
SALESFORCE_API_TOKEN=
|
SALESFORCE_CLIENT_ID=
|
||||||
|
SALESFORCE_CLIENT_SECRET=
|
||||||
|
|
||||||
|
TICKETS_DB=
|
||||||
|
TICKETS_RATE_LIMIT_MAX=10
|
||||||
|
TICKETS_RATE_LIMIT_WINDOW_MIN=10
|
||||||
|
|
||||||
MEMBER_CREDENTIAL=123
|
MEMBER_CREDENTIAL=123
|
||||||
CHOIR_CREDENTIAL=123
|
CHOIR_CREDENTIAL=123
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ npx jest test/some.test.ts
|
|||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
Express.js REST API in TypeScript with a service-oriented layering. Domains: `Calendar` (events, users) and `Feedback` (concert feedback forms, mounted at `/feedback`, backed by its own `FEEDBACK_DB` — see `src/models/feedback/`, still scaffolding-only as of this writing).
|
Express.js REST API in TypeScript with a service-oriented layering. Domains: `Calendar` (events, users) and `Feedback` (concert feedback forms, mounted at `/feedback`, backed by its own `FEEDBACK_DB` — see `src/models/feedback/`: public submission flow, admin CRUD, reporting, and a Salesforce newsletter-sync integration).
|
||||||
|
|
||||||
**Request path:**
|
**Request path:**
|
||||||
1. `app.ts` mounts `Calendar.router.ts` at `/calendar`
|
1. `app.ts` mounts `Calendar.router.ts` at `/calendar`
|
||||||
@@ -59,7 +59,8 @@ FEEDBACK_RATE_LIMIT_MAX=
|
|||||||
FEEDBACK_RATE_LIMIT_WINDOW_MIN=
|
FEEDBACK_RATE_LIMIT_WINDOW_MIN=
|
||||||
SALESFORCE_ENABLED=
|
SALESFORCE_ENABLED=
|
||||||
SALESFORCE_API_URL=
|
SALESFORCE_API_URL=
|
||||||
SALESFORCE_API_TOKEN=
|
SALESFORCE_CLIENT_ID=
|
||||||
|
SALESFORCE_CLIENT_SECRET=
|
||||||
EMAIL_HOST=
|
EMAIL_HOST=
|
||||||
EMAIL_USERNAME=
|
EMAIL_USERNAME=
|
||||||
EMAIL_PASSWORD=
|
EMAIL_PASSWORD=
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import logger from './src/middleware/logger';
|
|||||||
// Router imports
|
// Router imports
|
||||||
import {calendarRouter} from './src/models/calendar/Calendar.router';
|
import {calendarRouter} from './src/models/calendar/Calendar.router';
|
||||||
import {feedbackRouter} from './src/models/feedback/Feedback.router';
|
import {feedbackRouter} from './src/models/feedback/Feedback.router';
|
||||||
|
import {ticketsRouter} from './src/models/tickets/Tickets.router';
|
||||||
|
|
||||||
|
|
||||||
let cors = require('cors');
|
let cors = require('cors');
|
||||||
@@ -36,7 +37,8 @@ app.use(express.json());
|
|||||||
let allowedHosts = [
|
let allowedHosts = [
|
||||||
'https://www.nachklang.art',
|
'https://www.nachklang.art',
|
||||||
'https://calendar.nachklang.art',
|
'https://calendar.nachklang.art',
|
||||||
'https://feedback.nachklang.art'
|
'https://feedback.nachklang.art',
|
||||||
|
'https://tickets.nachklang.art'
|
||||||
];
|
];
|
||||||
const isDev = process.env.NODE_ENV !== 'production';
|
const isDev = process.env.NODE_ENV !== 'production';
|
||||||
const localhostRegex = /^http:\/\/localhost:\d+$/;
|
const localhostRegex = /^http:\/\/localhost:\d+$/;
|
||||||
@@ -104,6 +106,7 @@ app.use(
|
|||||||
// Add routers
|
// Add routers
|
||||||
app.use('/calendar', calendarRouter);
|
app.use('/calendar', calendarRouter);
|
||||||
app.use('/feedback', feedbackRouter);
|
app.use('/feedback', feedbackRouter);
|
||||||
|
app.use('/tickets', ticketsRouter);
|
||||||
|
|
||||||
// this is a simple route to make sure everything is working properly
|
// this is a simple route to make sure everything is working properly
|
||||||
app.get('/', (req: express.Request, res: express.Response) => {
|
app.get('/', (req: express.Request, res: express.Response) => {
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Local dev only — not used in production/deployment. Spins up a MariaDB
|
||||||
|
# instance with the calendar (reconstructed dev schema, see docker/init's
|
||||||
|
# disclaimer), feedback, and tickets databases pre-seeded.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# docker compose -f docker-compose.dev.yml up -d
|
||||||
|
#
|
||||||
|
# Then point .env at:
|
||||||
|
# DB_HOST=127.0.0.1
|
||||||
|
# DB_USER=nachklang
|
||||||
|
# DB_PASSWORD=devpassword
|
||||||
|
# CALENDAR_DB=nachklang_calendar
|
||||||
|
# FEEDBACK_DB=nachklang_feedback
|
||||||
|
# TICKETS_DB=nachklang_tickets
|
||||||
|
services:
|
||||||
|
mariadb:
|
||||||
|
image: mariadb:11
|
||||||
|
environment:
|
||||||
|
MARIADB_ROOT_PASSWORD: rootdevpassword
|
||||||
|
ports:
|
||||||
|
- "3306:3306"
|
||||||
|
volumes:
|
||||||
|
- nachklang_dev_db:/var/lib/mysql
|
||||||
|
- ./sql:/migrations:ro
|
||||||
|
- ./docker/init:/docker-entrypoint-initdb.d:ro
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
nachklang_dev_db:
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- Local dev only. Creates the three databases + a dev user with full access.
|
||||||
|
CREATE DATABASE IF NOT EXISTS nachklang_calendar CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
CREATE DATABASE IF NOT EXISTS nachklang_feedback CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
CREATE DATABASE IF NOT EXISTS nachklang_tickets CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
CREATE USER IF NOT EXISTS 'nachklang'@'%' IDENTIFIED BY 'devpassword';
|
||||||
|
GRANT ALL PRIVILEGES ON nachklang_calendar.* TO 'nachklang'@'%';
|
||||||
|
GRANT ALL PRIVILEGES ON nachklang_feedback.* TO 'nachklang'@'%';
|
||||||
|
GRANT ALL PRIVILEGES ON nachklang_tickets.* TO 'nachklang'@'%';
|
||||||
|
FLUSH PRIVILEGES;
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
-- Local dev only. Real schema, provided directly by the repo owner
|
||||||
|
-- (calendars, events, event_versions, sessions, users) - not a guess.
|
||||||
|
USE nachklang_calendar;
|
||||||
|
|
||||||
|
CREATE TABLE `calendars` (
|
||||||
|
`calendar_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
`name` text NOT NULL,
|
||||||
|
`includes_calendars` text DEFAULT NULL,
|
||||||
|
PRIMARY KEY (`calendar_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
|
CREATE TABLE `users` (
|
||||||
|
`user_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
`full_name` text NOT NULL,
|
||||||
|
`password_hash` text DEFAULT NULL,
|
||||||
|
`email` text NOT NULL,
|
||||||
|
`is_active` tinyint(1) DEFAULT 0,
|
||||||
|
`pw_reset_token_hash` text DEFAULT NULL,
|
||||||
|
`activation_token` text DEFAULT NULL,
|
||||||
|
PRIMARY KEY (`user_id`),
|
||||||
|
UNIQUE KEY `email` (`email`) USING HASH
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
|
CREATE TABLE `sessions` (
|
||||||
|
`session_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
`user_id` int(11) NOT NULL,
|
||||||
|
`session_key_hash` text DEFAULT NULL,
|
||||||
|
`created_date` datetime DEFAULT current_timestamp(),
|
||||||
|
`valid_until` datetime DEFAULT (current_timestamp() + interval 30 day),
|
||||||
|
`last_ip` text DEFAULT NULL,
|
||||||
|
PRIMARY KEY (`session_id`),
|
||||||
|
KEY `sessions_users_user_id_fk` (`user_id`),
|
||||||
|
CONSTRAINT `sessions_users_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
|
CREATE TABLE `events` (
|
||||||
|
`event_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
`calendar_id` int(11) NOT NULL,
|
||||||
|
`uuid` text NOT NULL,
|
||||||
|
`created_date` datetime DEFAULT current_timestamp(),
|
||||||
|
`created_by_id` int(11) NOT NULL,
|
||||||
|
PRIMARY KEY (`event_id`),
|
||||||
|
KEY `events_calendars_calendar_id_fk` (`calendar_id`),
|
||||||
|
KEY `events_users_user_id_fk` (`created_by_id`),
|
||||||
|
CONSTRAINT `events_calendars_calendar_id_fk` FOREIGN KEY (`calendar_id`) REFERENCES `calendars` (`calendar_id`),
|
||||||
|
CONSTRAINT `events_users_user_id_fk` FOREIGN KEY (`created_by_id`) REFERENCES `users` (`user_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
|
CREATE TABLE `event_versions` (
|
||||||
|
`event_version_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
`event_id` int(11) NOT NULL,
|
||||||
|
`name` text DEFAULT NULL,
|
||||||
|
`description` text DEFAULT NULL,
|
||||||
|
`start_datetime` datetime DEFAULT NULL,
|
||||||
|
`end_datetime` datetime DEFAULT NULL,
|
||||||
|
`whole_day` tinyint(1) DEFAULT NULL,
|
||||||
|
`repeat_frequency` text DEFAULT NULL,
|
||||||
|
`location` text DEFAULT NULL,
|
||||||
|
`url` text DEFAULT NULL,
|
||||||
|
`version_created_by_id` int(11) DEFAULT NULL,
|
||||||
|
`status` text DEFAULT NULL,
|
||||||
|
`version_created_at` datetime DEFAULT current_timestamp(),
|
||||||
|
PRIMARY KEY (`event_version_id`),
|
||||||
|
KEY `event_versions_events_event_id_fk` (`event_id`),
|
||||||
|
KEY `event_versions_users_user_id_fk` (`version_created_by_id`),
|
||||||
|
CONSTRAINT `event_versions_events_event_id_fk` FOREIGN KEY (`event_id`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `event_versions_users_user_id_fk` FOREIGN KEY (`version_created_by_id`) REFERENCES `users` (`user_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
|
INSERT INTO calendars (calendar_id, name, includes_calendars) VALUES
|
||||||
|
(1, 'public', '[]'),
|
||||||
|
(2, 'members', '[]'),
|
||||||
|
(3, 'management', '[]'),
|
||||||
|
(4, 'choir', '[]'),
|
||||||
|
(5, 'birthdays', '[]');
|
||||||
|
|
||||||
|
-- Dev admin, password: devpassword
|
||||||
|
INSERT INTO users (email, password_hash, full_name, is_active) VALUES
|
||||||
|
('dev@nachklang.art', '$2b$10$vmj7POS/68SGE.eI7pGjMegrw0vNNZ2HVSUTra5NRsl8iOLwiMgZK', 'Dev Admin', 1);
|
||||||
|
|
||||||
|
INSERT INTO events (calendar_id, uuid, created_by_id) VALUES
|
||||||
|
(1, UUID(), 1),
|
||||||
|
(1, UUID(), 1),
|
||||||
|
(1, UUID(), 1);
|
||||||
|
|
||||||
|
INSERT INTO event_versions (event_id, name, description, start_datetime, end_datetime, whole_day, location, url, status, version_created_by_id) VALUES
|
||||||
|
(1, 'Frühlingskonzert 2026', 'Erstes Konzert der Reihe', '2026-04-18 19:00:00', '2026-04-18 21:00:00', 0, 'Musikhochschule, Karlsruhe', 'https://www.nachklang.art/events/fruehlingskonzert-2026', 'PUBLIC', 1),
|
||||||
|
(2, 'Sommerkonzert 2026', 'Zweites Konzert der Reihe', '2026-07-11 19:00:00', '2026-07-11 21:00:00', 0, 'Christuskirche, Karlsruhe', 'https://www.nachklang.art/events/sommerkonzert-2026', 'PUBLIC', 1),
|
||||||
|
(3, 'Adventskonzert 2026', 'Drittes Konzert der Reihe', '2026-12-05 19:00:00', '2026-12-05 21:00:00', 0, 'Stadtkirche, Karlsruhe', 'https://www.nachklang.art/events/adventskonzert-2026', 'DRAFT', 1);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
USE nachklang_feedback;
|
||||||
|
SOURCE /migrations/feedback/001_init.sql;
|
||||||
|
SOURCE /migrations/feedback/002_add_poster_image_url.sql;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
USE nachklang_tickets;
|
||||||
|
SOURCE /migrations/tickets/001_init.sql;
|
||||||
|
SOURCE /migrations/tickets/002_add_require_address.sql;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Nachklang e.V. Feedback module — adds a per-event poster image URL.
|
||||||
|
-- Apply manually against the FEEDBACK_DB database, after 001_init.sql:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <FEEDBACK_DB> < 002_add_poster_image_url.sql
|
||||||
|
--
|
||||||
|
-- Stores a URL only (e.g. an existing nachklang.art poster image) rather
|
||||||
|
-- than an uploaded file — the concert posters already live on the public
|
||||||
|
-- website, so there is no need for the feedback app to host its own copy.
|
||||||
|
ALTER TABLE events
|
||||||
|
ADD COLUMN poster_image_url VARCHAR(500) NULL AFTER intro_text;
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
-- Nachklang e.V. Tickets module — initial schema for TICKETS_DB
|
||||||
|
-- Apply manually against the TICKETS_DB database (separate from CALENDAR_DB
|
||||||
|
-- and FEEDBACK_DB). See nachklang-tickets/docs/plan-ticket-shop.md for the
|
||||||
|
-- full design rationale.
|
||||||
|
--
|
||||||
|
-- Apply with e.g.:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <TICKETS_DB> < 001_init.sql
|
||||||
|
--
|
||||||
|
-- Deliberately no USE statement here: the target database is selected via
|
||||||
|
-- the mysql command line above (whatever TICKETS_DB is actually named in
|
||||||
|
-- .env), not hardcoded to a literal schema name.
|
||||||
|
--
|
||||||
|
-- `event_id` columns below refer to Calendar's `events.event_id` (a
|
||||||
|
-- different database). Deliberately no cross-database foreign key —
|
||||||
|
-- Tickets reads Calendar events via events.service.ts in the same Node
|
||||||
|
-- process, not via a DB-level join.
|
||||||
|
|
||||||
|
-- 1. voucher_codes --------------------------------------------------------
|
||||||
|
CREATE TABLE voucher_codes (
|
||||||
|
code VARCHAR(12) NOT NULL PRIMARY KEY,
|
||||||
|
status ENUM('UNUSED','REDEEMED','VOID') NOT NULL DEFAULT 'UNUSED',
|
||||||
|
max_guests INT NOT NULL DEFAULT 2,
|
||||||
|
prefill_name VARCHAR(255) NULL,
|
||||||
|
prefill_email VARCHAR(255) NULL,
|
||||||
|
batch_id VARCHAR(36) NULL,
|
||||||
|
created_by_email VARCHAR(255) NOT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
KEY idx_vc_batch (batch_id),
|
||||||
|
KEY idx_vc_status (status)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 2. voucher_code_events (join: which concerts a code may be redeemed for) -
|
||||||
|
CREATE TABLE voucher_code_events (
|
||||||
|
voucher_code_event_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
code VARCHAR(12) NOT NULL,
|
||||||
|
event_id INT NOT NULL,
|
||||||
|
CONSTRAINT fk_vce_code FOREIGN KEY (code) REFERENCES voucher_codes(code) ON DELETE CASCADE,
|
||||||
|
UNIQUE KEY uq_vce_code_event (code, event_id),
|
||||||
|
KEY idx_vce_event (event_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 3. event_ticket_settings (per-concert voucher config) ---------------------
|
||||||
|
-- One row per Calendar event_id that has ever had voucher settings
|
||||||
|
-- configured. Absent row == uncapped, no deadline, address not collected
|
||||||
|
-- (see docs/plan-ticket-shop.md — "absence over sentinels").
|
||||||
|
CREATE TABLE event_ticket_settings (
|
||||||
|
event_id INT NOT NULL PRIMARY KEY,
|
||||||
|
capacity INT NULL,
|
||||||
|
redemption_deadline DATETIME NULL,
|
||||||
|
collect_address TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 4. redemptions ------------------------------------------------------------
|
||||||
|
-- `status` is soft-state rather than a hard delete on undo, so guest data
|
||||||
|
-- and history survive an undo for the audit trail. Capacity/reporting
|
||||||
|
-- queries filter status = 'ACTIVE'. A code that gets redeemed again after
|
||||||
|
-- being undone creates a new row here rather than reviving the old one.
|
||||||
|
CREATE TABLE redemptions (
|
||||||
|
redemption_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
code VARCHAR(12) NOT NULL,
|
||||||
|
event_id INT NOT NULL,
|
||||||
|
status ENUM('ACTIVE','UNDONE') NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
contact_name VARCHAR(255) NOT NULL,
|
||||||
|
contact_email VARCHAR(255) NOT NULL,
|
||||||
|
contact_address TEXT NULL,
|
||||||
|
guest_count INT NOT NULL,
|
||||||
|
redeemed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT fk_red_code FOREIGN KEY (code) REFERENCES voucher_codes(code),
|
||||||
|
KEY idx_red_event_status (event_id, status),
|
||||||
|
KEY idx_red_code (code)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 5. redemption_guests --------------------------------------------------------
|
||||||
|
-- One row per attendee, including the primary contact (position 0).
|
||||||
|
CREATE TABLE redemption_guests (
|
||||||
|
redemption_guest_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
redemption_id INT NOT NULL,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
position INT NOT NULL DEFAULT 0,
|
||||||
|
CONSTRAINT fk_rg_redemption FOREIGN KEY (redemption_id) REFERENCES redemptions(redemption_id) ON DELETE CASCADE,
|
||||||
|
KEY idx_rg_redemption (redemption_id, position)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 6. voucher_audit_log ----------------------------------------------------
|
||||||
|
-- Lightweight admin-action history per code (not a full version-history
|
||||||
|
-- system) — who did what and why. Covers EDIT/VOID/UNDO only; the guest's
|
||||||
|
-- own redemption isn't an admin action so it isn't logged here (it's
|
||||||
|
-- already timestamped on `redemptions.redeemed_at`).
|
||||||
|
CREATE TABLE voucher_audit_log (
|
||||||
|
audit_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
code VARCHAR(12) NOT NULL,
|
||||||
|
redemption_id INT NULL,
|
||||||
|
admin_email VARCHAR(255) NOT NULL,
|
||||||
|
action ENUM('EDIT','VOID','UNDO') NOT NULL,
|
||||||
|
change_summary JSON NULL,
|
||||||
|
reason VARCHAR(500) NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT fk_val_code FOREIGN KEY (code) REFERENCES voucher_codes(code) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT fk_val_redemption FOREIGN KEY (redemption_id) REFERENCES redemptions(redemption_id) ON DELETE SET NULL,
|
||||||
|
KEY idx_val_code_time (code, created_at)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Nachklang e.V. Tickets module — adds a per-event "address required" flag,
|
||||||
|
-- distinct from collect_address (which only controls whether the field is
|
||||||
|
-- shown/collected at all). Apply manually against TICKETS_DB, after
|
||||||
|
-- 001_init.sql:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <TICKETS_DB> < 002_add_require_address.sql
|
||||||
|
ALTER TABLE event_ticket_settings
|
||||||
|
ADD COLUMN require_address TINYINT(1) NOT NULL DEFAULT 0 AFTER collect_address;
|
||||||
@@ -13,26 +13,30 @@ export namespace MailService {
|
|||||||
tls: {rejectUnauthorized: false}
|
tls: {rejectUnauthorized: false}
|
||||||
});
|
});
|
||||||
|
|
||||||
const mailConfigurations = {
|
export interface MailAttachment {
|
||||||
|
filename: string;
|
||||||
|
content: string | Buffer;
|
||||||
|
contentType?: string;
|
||||||
|
}
|
||||||
|
|
||||||
// It should be a string of sender email
|
export interface SendMailOptions {
|
||||||
|
html?: string;
|
||||||
|
attachments?: MailAttachment[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Builds a fresh options object per call rather than mutating a shared
|
||||||
|
// module-level one - the transporter is pooled, so overlapping sendMail
|
||||||
|
// calls (e.g. two guests redeeming at once) previously risked one
|
||||||
|
// call's recipient/subject/body being overwritten by another's before
|
||||||
|
// transporter.sendMail() read it.
|
||||||
|
export const sendMail = async (recipientAddress: string, subject: string, body: string, options?: SendMailOptions) => {
|
||||||
|
await transporter.sendMail({
|
||||||
from: 'noreply@nachklang.art',
|
from: 'noreply@nachklang.art',
|
||||||
|
to: recipientAddress,
|
||||||
// Comma Separated list of mails
|
subject: subject,
|
||||||
to: 'mail@pmueller.me',
|
text: body,
|
||||||
|
html: options?.html,
|
||||||
// Subject of Email
|
attachments: options?.attachments
|
||||||
subject: '',
|
});
|
||||||
|
|
||||||
// This would be the text of email body
|
|
||||||
text: ''
|
|
||||||
};
|
|
||||||
|
|
||||||
export const sendMail = async (recipientAddress: string, subject: string, body: string) => {
|
|
||||||
mailConfigurations.to = recipientAddress;
|
|
||||||
mailConfigurations.subject = subject;
|
|
||||||
mailConfigurations.text = body;
|
|
||||||
|
|
||||||
await transporter.sendMail(mailConfigurations);
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -126,6 +126,64 @@ export const getAllEventsAdmin = async (calendarId: number): Promise<Event[]> =>
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a single event by id (latest version, any status), or null if it
|
||||||
|
* doesn't exist. Unlike getAllEvents/getAllEventsAdmin this isn't scoped to
|
||||||
|
* a calendar - callers that need to enforce calendar/status visibility
|
||||||
|
* should check the returned event's calendarId/status themselves.
|
||||||
|
* @param eventId The event id
|
||||||
|
*/
|
||||||
|
export const getEventById = async (eventId: number): Promise<Event | null> => {
|
||||||
|
let conn = await NachklangCalendarDB.getConnection();
|
||||||
|
try {
|
||||||
|
const eventsQuery = `
|
||||||
|
SELECT e.calendar_id, e.uuid, e.created_date, e.created_by_id, u.full_name as created_by_name, u2.full_name as last_modified_by_name, v.* FROM events e
|
||||||
|
INNER JOIN (
|
||||||
|
SELECT event_id, MAX(event_version_id) AS latest_version
|
||||||
|
FROM event_versions
|
||||||
|
GROUP BY event_id
|
||||||
|
) latest_versions
|
||||||
|
ON e.event_id = latest_versions.event_id
|
||||||
|
INNER JOIN event_versions v
|
||||||
|
ON v.event_id = latest_versions.event_id AND v.event_version_id = latest_versions.latest_version
|
||||||
|
LEFT OUTER JOIN users u ON u.user_id = e.created_by_id
|
||||||
|
LEFT OUTER JOIN users u2 ON u2.user_id = v.version_created_by_id
|
||||||
|
WHERE e.event_id = ?`;
|
||||||
|
const eventsRes = await conn.query(eventsQuery, eventId);
|
||||||
|
|
||||||
|
if (eventsRes.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = eventsRes[0];
|
||||||
|
return {
|
||||||
|
eventId: row.event_id,
|
||||||
|
calendarId: row.calendar_id,
|
||||||
|
uuid: row.uuid,
|
||||||
|
name: row.name,
|
||||||
|
description: row.description,
|
||||||
|
startDateTime: row.start_datetime,
|
||||||
|
endDateTime: row.end_datetime,
|
||||||
|
createdDate: row.created_date,
|
||||||
|
lastModifiedDate: row.version_created_at,
|
||||||
|
location: row.location,
|
||||||
|
createdBy: row.created_by_name,
|
||||||
|
createdById: row.created_by_id,
|
||||||
|
lastModifiedBy: row.last_modified_by_name,
|
||||||
|
lastModifiedById: row.version_created_by_id,
|
||||||
|
url: row.url,
|
||||||
|
wholeDay: row.whole_day,
|
||||||
|
repeatFrequency: row.repeat_frequency,
|
||||||
|
status: row.status
|
||||||
|
} as Event;
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
// Return connection
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create the given event in the database
|
* Create the given event in the database
|
||||||
* @param event The event to create
|
* @param event The event to create
|
||||||
|
|||||||
@@ -2,10 +2,9 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../middleware/logger';
|
|
||||||
import {publicRouter} from './public/public.router';
|
import {publicRouter} from './public/public.router';
|
||||||
import {adminRouter} from './admin/admin.router';
|
import {adminRouter} from './admin/admin.router';
|
||||||
|
import {sendServerError} from './feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
@@ -52,12 +51,6 @@ feedbackRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
try {
|
try {
|
||||||
res.status(200).send('Nachklang e.V. Feedback API Endpoint');
|
res.status(200).send('Nachklang e.V. Feedback API Endpoint');
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
sendServerError(res, e);
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -33,6 +33,9 @@
|
|||||||
* feedbackDeadline:
|
* feedbackDeadline:
|
||||||
* type: string
|
* type: string
|
||||||
* format: date-time
|
* format: date-time
|
||||||
|
* posterImageUrl:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
* isPublished:
|
* isPublished:
|
||||||
* type: boolean
|
* type: boolean
|
||||||
* submissionCount:
|
* submissionCount:
|
||||||
@@ -87,6 +90,7 @@ export interface EventAdminSummary {
|
|||||||
subtitle: string | null;
|
subtitle: string | null;
|
||||||
eventDate: string;
|
eventDate: string;
|
||||||
feedbackDeadline: string;
|
feedbackDeadline: string;
|
||||||
|
posterImageUrl: string | null;
|
||||||
isPublished: boolean;
|
isPublished: boolean;
|
||||||
submissionCount: number;
|
submissionCount: number;
|
||||||
}
|
}
|
||||||
@@ -110,6 +114,7 @@ export interface CreateEventInput {
|
|||||||
eventDate: string;
|
eventDate: string;
|
||||||
feedbackDeadline?: string;
|
feedbackDeadline?: string;
|
||||||
introText?: string;
|
introText?: string;
|
||||||
|
posterImageUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateEventInput {
|
export interface UpdateEventInput {
|
||||||
@@ -119,6 +124,7 @@ export interface UpdateEventInput {
|
|||||||
feedbackDeadline?: string;
|
feedbackDeadline?: string;
|
||||||
isPublished?: boolean;
|
isPublished?: boolean;
|
||||||
introText?: string;
|
introText?: string;
|
||||||
|
posterImageUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AdminQuestion {
|
export interface AdminQuestion {
|
||||||
|
|||||||
@@ -2,9 +2,8 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../../middleware/logger';
|
|
||||||
import {requireAdminAuth} from '../feedback.auth';
|
import {requireAdminAuth} from '../feedback.auth';
|
||||||
|
import {sendServerError} from '../feedback.errors';
|
||||||
import {eventsAdminRouter} from './events.admin.router';
|
import {eventsAdminRouter} from './events.admin.router';
|
||||||
import {songsAdminRouter} from './songs.admin.router';
|
import {songsAdminRouter} from './songs.admin.router';
|
||||||
import {questionsAdminRouter} from './questions.admin.router';
|
import {questionsAdminRouter} from './questions.admin.router';
|
||||||
@@ -81,13 +80,7 @@ adminRouter.delete('/submissions/:submissionId', async (req: Request, res: Respo
|
|||||||
}
|
}
|
||||||
res.status(204).send();
|
res.status(204).send();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
sendServerError(res, e);
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
status: 'PROCESSING_ERROR',
|
|
||||||
message: 'Internal Server Error. Try again later.',
|
|
||||||
reference: errorGuid
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
|
import {formatDatetime} from '../feedback.dates';
|
||||||
|
|
||||||
const CSV_SEPARATOR = ';';
|
const CSV_SEPARATOR = ';';
|
||||||
const UTF8_BOM = '';
|
const UTF8_BOM = '';
|
||||||
@@ -23,15 +24,6 @@ export const escapeCsvField = (value: string | number | null | undefined): strin
|
|||||||
return str;
|
return str;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** mariadb returns DATETIME columns as JS Date objects - format explicitly,
|
|
||||||
* otherwise String(date) falls back to the verbose Date.toString() format. */
|
|
||||||
export const formatDatetime = (value: Date | string | null): string => {
|
|
||||||
if (!value) return '';
|
|
||||||
const d = value instanceof Date ? value : new Date(value);
|
|
||||||
const pad = (n: number) => String(n).padStart(2, '0');
|
|
||||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildCsv = (headers: string[], rows: (string | number | null | undefined)[][]): string => {
|
const buildCsv = (headers: string[], rows: (string | number | null | undefined)[][]): string => {
|
||||||
const lines = [headers.map(escapeCsvField).join(CSV_SEPARATOR)];
|
const lines = [headers.map(escapeCsvField).join(CSV_SEPARATOR)];
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
|
|||||||
@@ -2,26 +2,15 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../../middleware/logger';
|
|
||||||
import * as EventsAdminService from './events.admin.service';
|
import * as EventsAdminService from './events.admin.service';
|
||||||
import * as SongsAdminService from './songs.admin.service';
|
import * as SongsAdminService from './songs.admin.service';
|
||||||
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
*/
|
*/
|
||||||
export const eventsAdminRouter = express.Router();
|
export const eventsAdminRouter = express.Router();
|
||||||
|
|
||||||
const sendServerError = (res: Response, e: any) => {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @swagger
|
* @swagger
|
||||||
* /feedback/admin/events:
|
* /feedback/admin/events:
|
||||||
@@ -70,6 +59,8 @@ const sendServerError = (res: Response, e: any) => {
|
|||||||
* format: date-time
|
* format: date-time
|
||||||
* introText:
|
* introText:
|
||||||
* type: string
|
* type: string
|
||||||
|
* posterImageUrl:
|
||||||
|
* type: string
|
||||||
* responses:
|
* responses:
|
||||||
* 201:
|
* 201:
|
||||||
* description: Created
|
* description: Created
|
||||||
@@ -88,13 +79,13 @@ eventsAdminRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
|
|
||||||
eventsAdminRouter.post('/', async (req: Request, res: Response) => {
|
eventsAdminRouter.post('/', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const {name, subtitle, eventDate, feedbackDeadline, introText} = req.body || {};
|
const {name, subtitle, eventDate, feedbackDeadline, introText, posterImageUrl} = req.body || {};
|
||||||
if (!name || !eventDate) {
|
if (!name || !eventDate) {
|
||||||
res.status(400).send({status: 'BAD_REQUEST', message: 'name and eventDate are required'});
|
res.status(400).send({status: 'BAD_REQUEST', message: 'name and eventDate are required'});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const eventId = await EventsAdminService.createEvent(
|
const eventId = await EventsAdminService.createEvent(
|
||||||
{name, subtitle, eventDate, feedbackDeadline, introText},
|
{name, subtitle, eventDate, feedbackDeadline, introText, posterImageUrl},
|
||||||
res.locals.admin.email
|
res.locals.admin.email
|
||||||
);
|
);
|
||||||
res.status(201).send({eventId});
|
res.status(201).send({eventId});
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
import {Song} from '../feedback.interface';
|
import {Song} from '../feedback.interface';
|
||||||
import {CreateEventInput, EventAdminDetail, EventAdminQuestionAssignment, EventAdminSummary, UpdateEventInput} from './admin.interface';
|
import {CreateEventInput, EventAdminDetail, EventAdminQuestionAssignment, EventAdminSummary, UpdateEventInput} from './admin.interface';
|
||||||
|
import {formatDatetime} from '../feedback.dates';
|
||||||
|
|
||||||
const UMLAUT_MAP: Record<string, string> = {
|
const UMLAUT_MAP: Record<string, string> = {
|
||||||
'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss',
|
'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss',
|
||||||
@@ -37,6 +38,7 @@ const mapSummaryRow = (row: any): EventAdminSummary => ({
|
|||||||
subtitle: row.subtitle,
|
subtitle: row.subtitle,
|
||||||
eventDate: row.event_date,
|
eventDate: row.event_date,
|
||||||
feedbackDeadline: row.feedback_deadline,
|
feedbackDeadline: row.feedback_deadline,
|
||||||
|
posterImageUrl: row.poster_image_url,
|
||||||
isPublished: !!row.is_published,
|
isPublished: !!row.is_published,
|
||||||
submissionCount: Number(row.submission_count)
|
submissionCount: Number(row.submission_count)
|
||||||
});
|
});
|
||||||
@@ -83,11 +85,6 @@ const generateUniqueSlug = async (conn: any, name: string, eventDate: string): P
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const toMysqlDatetime = (d: Date): string => {
|
|
||||||
const pad = (n: number) => String(n).padStart(2, '0');
|
|
||||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const createEvent = async (input: CreateEventInput, createdByEmail: string): Promise<number> => {
|
export const createEvent = async (input: CreateEventInput, createdByEmail: string): Promise<number> => {
|
||||||
let conn = await NachklangFeedbackDB.getConnection();
|
let conn = await NachklangFeedbackDB.getConnection();
|
||||||
try {
|
try {
|
||||||
@@ -98,11 +95,11 @@ export const createEvent = async (input: CreateEventInput, createdByEmail: strin
|
|||||||
: computeDefaultDeadline(input.eventDate);
|
: computeDefaultDeadline(input.eventDate);
|
||||||
|
|
||||||
const query = `
|
const query = `
|
||||||
INSERT INTO events (slug, name, subtitle, event_date, feedback_deadline, intro_text, created_by_email)
|
INSERT INTO events (slug, name, subtitle, event_date, feedback_deadline, intro_text, poster_image_url, created_by_email)
|
||||||
VALUES (?,?,?,?,?,?,?) RETURNING event_id`;
|
VALUES (?,?,?,?,?,?,?,?) RETURNING event_id`;
|
||||||
const res = await conn.query(query, [
|
const res = await conn.query(query, [
|
||||||
slug, input.name, input.subtitle || null, input.eventDate, toMysqlDatetime(deadline),
|
slug, input.name, input.subtitle || null, input.eventDate, formatDatetime(deadline),
|
||||||
input.introText || null, createdByEmail
|
input.introText || null, input.posterImageUrl || null, createdByEmail
|
||||||
]);
|
]);
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
return res[0].event_id;
|
return res[0].event_id;
|
||||||
@@ -158,6 +155,7 @@ export const updateEvent = async (eventId: number, input: UpdateEventInput): Pro
|
|||||||
if (input.feedbackDeadline !== undefined) { fields.push('feedback_deadline = ?'); values.push(input.feedbackDeadline); }
|
if (input.feedbackDeadline !== undefined) { fields.push('feedback_deadline = ?'); values.push(input.feedbackDeadline); }
|
||||||
if (input.isPublished !== undefined) { fields.push('is_published = ?'); values.push(input.isPublished ? 1 : 0); }
|
if (input.isPublished !== undefined) { fields.push('is_published = ?'); values.push(input.isPublished ? 1 : 0); }
|
||||||
if (input.introText !== undefined) { fields.push('intro_text = ?'); values.push(input.introText); }
|
if (input.introText !== undefined) { fields.push('intro_text = ?'); values.push(input.introText); }
|
||||||
|
if (input.posterImageUrl !== undefined) { fields.push('poster_image_url = ?'); values.push(input.posterImageUrl || null); }
|
||||||
|
|
||||||
if (fields.length === 0) return true;
|
if (fields.length === 0) return true;
|
||||||
|
|
||||||
|
|||||||
@@ -2,25 +2,14 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../../middleware/logger';
|
|
||||||
import * as QuestionsAdminService from './questions.admin.service';
|
import * as QuestionsAdminService from './questions.admin.service';
|
||||||
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
*/
|
*/
|
||||||
export const questionsAdminRouter = express.Router();
|
export const questionsAdminRouter = express.Router();
|
||||||
|
|
||||||
const sendServerError = (res: Response, e: any) => {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @swagger
|
* @swagger
|
||||||
* /feedback/admin/questions:
|
* /feedback/admin/questions:
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ export interface EventReport {
|
|||||||
sent: number;
|
sent: number;
|
||||||
pending: number;
|
pending: number;
|
||||||
failed: number;
|
failed: number;
|
||||||
|
skipped: number;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,27 +2,16 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../../middleware/logger';
|
|
||||||
import * as ReportsAdminService from './reports.admin.service';
|
import * as ReportsAdminService from './reports.admin.service';
|
||||||
import * as CsvService from './csv.service';
|
import * as CsvService from './csv.service';
|
||||||
import * as EventsAdminService from './events.admin.service';
|
import * as EventsAdminService from './events.admin.service';
|
||||||
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
*/
|
*/
|
||||||
export const reportsAdminRouter = express.Router();
|
export const reportsAdminRouter = express.Router();
|
||||||
|
|
||||||
const sendServerError = (res: Response, e: any) => {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @swagger
|
* @swagger
|
||||||
* /feedback/admin/events/{eventId}/report:
|
* /feedback/admin/events/{eventId}/report:
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ export const aggregateReport = (
|
|||||||
submissionStats: {totalSubmissions: number; firstSubmissionAt: string | null; lastSubmissionAt: string | null},
|
submissionStats: {totalSubmissions: number; firstSubmissionAt: string | null; lastSubmissionAt: string | null},
|
||||||
answerRows: AnswerRow[],
|
answerRows: AnswerRow[],
|
||||||
guestBookCount: number,
|
guestBookCount: number,
|
||||||
newsletterCounts: {total: number; sent: number; pending: number; failed: number}
|
newsletterCounts: {total: number; sent: number; pending: number; failed: number; skipped: number}
|
||||||
): EventReport => {
|
): EventReport => {
|
||||||
const groupKey = (row: AnswerRow) => `${row.questionId ?? 'null'}::${row.questionLabel}`;
|
const groupKey = (row: AnswerRow) => `${row.questionId ?? 'null'}::${row.questionLabel}`;
|
||||||
|
|
||||||
@@ -137,13 +137,14 @@ export const getReport = async (eventId: number): Promise<EventReport | null> =>
|
|||||||
`SELECT sync_status, COUNT(*) as cnt FROM newsletter_signups WHERE event_id = ? GROUP BY sync_status`,
|
`SELECT sync_status, COUNT(*) as cnt FROM newsletter_signups WHERE event_id = ? GROUP BY sync_status`,
|
||||||
[eventId]
|
[eventId]
|
||||||
);
|
);
|
||||||
const newsletterCounts = {total: 0, sent: 0, pending: 0, failed: 0};
|
const newsletterCounts = {total: 0, sent: 0, pending: 0, failed: 0, skipped: 0};
|
||||||
for (const row of newsletterRows) {
|
for (const row of newsletterRows) {
|
||||||
const cnt = Number(row.cnt);
|
const cnt = Number(row.cnt);
|
||||||
newsletterCounts.total += cnt;
|
newsletterCounts.total += cnt;
|
||||||
if (row.sync_status === 'SENT') newsletterCounts.sent = cnt;
|
if (row.sync_status === 'SENT') newsletterCounts.sent = cnt;
|
||||||
else if (row.sync_status === 'PENDING') newsletterCounts.pending = cnt;
|
else if (row.sync_status === 'PENDING') newsletterCounts.pending = cnt;
|
||||||
else if (row.sync_status === 'FAILED') newsletterCounts.failed = cnt;
|
else if (row.sync_status === 'FAILED') newsletterCounts.failed = cnt;
|
||||||
|
else if (row.sync_status === 'SKIPPED') newsletterCounts.skipped = cnt;
|
||||||
}
|
}
|
||||||
|
|
||||||
return aggregateReport(
|
return aggregateReport(
|
||||||
|
|||||||
@@ -2,9 +2,8 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../../middleware/logger';
|
|
||||||
import * as SongsAdminService from './songs.admin.service';
|
import * as SongsAdminService from './songs.admin.service';
|
||||||
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
@@ -80,13 +79,7 @@ songsAdminRouter.put('/:songId', async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
res.status(200).send({status: 'OK'});
|
res.status(200).send({status: 'OK'});
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
sendServerError(res, e);
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -99,12 +92,6 @@ songsAdminRouter.delete('/:songId', async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
res.status(204).send();
|
res.status(204).send();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
sendServerError(res, e);
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../middleware/logger';
|
|
||||||
import * as UserService from '../calendar/users/users.service';
|
import * as UserService from '../calendar/users/users.service';
|
||||||
|
import {sendServerError} from './feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This file is the ONLY place in the feedback module that knows how admin
|
* This file is the ONLY place in the feedback module that knows how admin
|
||||||
@@ -74,12 +73,6 @@ export const requireAdminAuth: express.RequestHandler = async (req, res, next) =
|
|||||||
res.locals.admin = identity;
|
res.locals.admin = identity;
|
||||||
next();
|
next();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
sendServerError(res, e);
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* Formats a Date using its local getters (not toISOString/UTC), so the
|
||||||
|
* wall-clock time the server is running in is what gets stored/displayed -
|
||||||
|
* never silently shifted by a UTC conversion. Used both for MySQL DATETIME
|
||||||
|
* literals (events.admin.service.ts) and CSV export (csv.service.ts): same
|
||||||
|
* requirement, same format, in either context.
|
||||||
|
*/
|
||||||
|
export const formatDatetime = (value: Date | string | null): string => {
|
||||||
|
if (!value) return '';
|
||||||
|
const d = value instanceof Date ? value : new Date(value);
|
||||||
|
const pad = (n: number) => String(n).padStart(2, '0');
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||||
|
};
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import {Response} from 'express';
|
||||||
|
import {Guid} from 'guid-typescript';
|
||||||
|
import logger from '../../middleware/logger';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The feedback module's standard catch-block response: log with a
|
||||||
|
* reference guid, never leak the real error message to the client. Every
|
||||||
|
* router in this module follows this exact convention (see CLAUDE.md).
|
||||||
|
*/
|
||||||
|
export const sendServerError = (res: Response, e: any): void => {
|
||||||
|
const errorGuid = Guid.create().toString();
|
||||||
|
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||||
|
res.status(500).send({
|
||||||
|
status: 'PROCESSING_ERROR',
|
||||||
|
message: 'Internal Server Error. Try again later.',
|
||||||
|
reference: errorGuid
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -62,6 +62,10 @@
|
|||||||
* feedbackDeadline:
|
* feedbackDeadline:
|
||||||
* type: string
|
* type: string
|
||||||
* format: date-time
|
* format: date-time
|
||||||
|
* posterImageUrl:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* example: "https://www.nachklang.art/img/nk/image-20260727-214855-851.jpeg"
|
||||||
* EventConfig:
|
* EventConfig:
|
||||||
* allOf:
|
* allOf:
|
||||||
* - $ref: '#/components/schemas/EventSummary'
|
* - $ref: '#/components/schemas/EventSummary'
|
||||||
@@ -116,6 +120,7 @@ export interface EventSummary {
|
|||||||
subtitle: string | null;
|
subtitle: string | null;
|
||||||
eventDate: string;
|
eventDate: string;
|
||||||
feedbackDeadline: string;
|
feedbackDeadline: string;
|
||||||
|
posterImageUrl: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface EventConfig extends EventSummary {
|
export interface EventConfig extends EventSummary {
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import axios from 'axios';
|
||||||
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
|
import logger from '../../../middleware/logger';
|
||||||
|
|
||||||
|
// Newsletter opt-ins sync to Salesforce, which already runs a full
|
||||||
|
// double-opt-in subscription flow (Person Account for existing constituents,
|
||||||
|
// Lead for everyone else - see the Salesforce repo's
|
||||||
|
// feature/newsletter-signup-integration branch for the full design notes).
|
||||||
|
// This is the one file that knows that contract exists; submissions.service.ts
|
||||||
|
// only ever calls syncNewsletterSignup(signupId) after its own transaction
|
||||||
|
// commits, fire-and-forget, so a Salesforce outage can never delay or fail a
|
||||||
|
// visitor's feedback submission.
|
||||||
|
|
||||||
|
interface SalesforceSuccessResponse {
|
||||||
|
status: 'PENDING_CONFIRMATION' | 'ALREADY_SUBSCRIBED';
|
||||||
|
salesforceObject: 'Lead' | 'Account';
|
||||||
|
salesforceRecordId: string;
|
||||||
|
created: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NewsletterSignupRow {
|
||||||
|
signup_id: number;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
email: string;
|
||||||
|
event_name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Salesforce's client-credentials token response does not reliably include
|
||||||
|
// expires_in, so the cache lifetime is a conservative guess rather than a
|
||||||
|
// value read from the response - a 401 on the next call just triggers a
|
||||||
|
// fresh fetch (see the retry-once logic in postSignup).
|
||||||
|
const TOKEN_CACHE_MS = 15 * 60 * 1000;
|
||||||
|
let cachedToken: {accessToken: string; fetchedAt: number} | null = null;
|
||||||
|
|
||||||
|
const getAccessToken = async (forceRefresh: boolean): Promise<string> => {
|
||||||
|
if (!forceRefresh && cachedToken && Date.now() - cachedToken.fetchedAt < TOKEN_CACHE_MS) {
|
||||||
|
return cachedToken.accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
const instanceUrl = process.env.SALESFORCE_API_URL;
|
||||||
|
const clientId = process.env.SALESFORCE_CLIENT_ID;
|
||||||
|
const clientSecret = process.env.SALESFORCE_CLIENT_SECRET;
|
||||||
|
if (!instanceUrl || !clientId || !clientSecret) {
|
||||||
|
throw new Error('SALESFORCE_ENABLED is true but SALESFORCE_API_URL/SALESFORCE_CLIENT_ID/SALESFORCE_CLIENT_SECRET are not fully configured.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await axios.post(
|
||||||
|
`${instanceUrl}/services/oauth2/token`,
|
||||||
|
new URLSearchParams({grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret}).toString(),
|
||||||
|
{headers: {'Content-Type': 'application/x-www-form-urlencoded'}, timeout: 10000}
|
||||||
|
);
|
||||||
|
cachedToken = {accessToken: res.data.access_token, fetchedAt: Date.now()};
|
||||||
|
return cachedToken.accessToken;
|
||||||
|
};
|
||||||
|
|
||||||
|
const postSignup = async (payload: {firstName: string; lastName: string; email: string; eventName: string}): Promise<SalesforceSuccessResponse> => {
|
||||||
|
const instanceUrl = process.env.SALESFORCE_API_URL;
|
||||||
|
const url = `${instanceUrl}/services/apexrest/newsletter/signup`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = await getAccessToken(false);
|
||||||
|
const res = await axios.post<SalesforceSuccessResponse>(url, payload, {headers: {Authorization: `Bearer ${token}`}, timeout: 10000});
|
||||||
|
return res.data;
|
||||||
|
} catch (err: any) {
|
||||||
|
// The cached token may have expired server-side even though our
|
||||||
|
// conservative local TTL hasn't - retry once with a forced refresh
|
||||||
|
// before treating this as a real failure.
|
||||||
|
if (err?.response?.status === 401) {
|
||||||
|
const token = await getAccessToken(true);
|
||||||
|
const res = await axios.post<SalesforceSuccessResponse>(url, payload, {headers: {Authorization: `Bearer ${token}`}, timeout: 10000});
|
||||||
|
return res.data;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const markSynced = async (signupId: number, externalId: string): Promise<void> => {
|
||||||
|
let conn = await NachklangFeedbackDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.query(
|
||||||
|
`UPDATE newsletter_signups SET sync_status = 'SENT', synced_at = NOW(), external_id = ?, sync_attempts = sync_attempts + 1, last_error = NULL WHERE signup_id = ?`,
|
||||||
|
[externalId, signupId]
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const markFailed = async (signupId: number, errorMessage: string): Promise<void> => {
|
||||||
|
let conn = await NachklangFeedbackDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.query(
|
||||||
|
`UPDATE newsletter_signups SET sync_status = 'FAILED', last_error = ?, sync_attempts = sync_attempts + 1 WHERE signup_id = ?`,
|
||||||
|
[errorMessage.slice(0, 2000), signupId]
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads one newsletter_signups row and syncs it to Salesforce. Always
|
||||||
|
* called after the owning submission's transaction has committed, never
|
||||||
|
* awaited by the request handler. When SALESFORCE_ENABLED is false, this
|
||||||
|
* only logs the payload it would have sent - the row's sync_status is
|
||||||
|
* already 'SKIPPED' from the insert in submissions.service.ts, so there's
|
||||||
|
* nothing to update.
|
||||||
|
*/
|
||||||
|
export const syncNewsletterSignup = async (signupId: number): Promise<void> => {
|
||||||
|
let conn = await NachklangFeedbackDB.getConnection();
|
||||||
|
let row: NewsletterSignupRow | undefined;
|
||||||
|
try {
|
||||||
|
const rows = await conn.query(
|
||||||
|
`SELECT ns.signup_id, ns.first_name, ns.last_name, ns.email, e.name AS event_name
|
||||||
|
FROM newsletter_signups ns JOIN events e ON e.event_id = ns.event_id
|
||||||
|
WHERE ns.signup_id = ?`,
|
||||||
|
[signupId]
|
||||||
|
);
|
||||||
|
row = rows[0];
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!row) {
|
||||||
|
logger.error('syncNewsletterSignup: signup not found', {signupId});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = {firstName: row.first_name, lastName: row.last_name, email: row.email, eventName: row.event_name};
|
||||||
|
|
||||||
|
if (process.env.SALESFORCE_ENABLED !== 'true') {
|
||||||
|
logger.info('syncNewsletterSignup: SALESFORCE_ENABLED is false, would have sent', {signupId, payload});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await postSignup(payload);
|
||||||
|
await markSynced(signupId, result.salesforceRecordId);
|
||||||
|
} catch (err: any) {
|
||||||
|
const message = err?.response?.data?.message || err?.message || 'Unknown error';
|
||||||
|
logger.error('syncNewsletterSignup failed', {signupId, message});
|
||||||
|
await markFailed(signupId, message);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -9,7 +9,7 @@ export const getEligibleEvents = async (): Promise<EventSummary[]> => {
|
|||||||
let conn = await NachklangFeedbackDB.getConnection();
|
let conn = await NachklangFeedbackDB.getConnection();
|
||||||
try {
|
try {
|
||||||
const query = `
|
const query = `
|
||||||
SELECT slug, name, subtitle, event_date, feedback_deadline
|
SELECT slug, name, subtitle, event_date, feedback_deadline, poster_image_url
|
||||||
FROM events
|
FROM events
|
||||||
WHERE is_published = 1 AND event_date <= CURDATE() AND feedback_deadline >= NOW()
|
WHERE is_published = 1 AND event_date <= CURDATE() AND feedback_deadline >= NOW()
|
||||||
ORDER BY event_date DESC`;
|
ORDER BY event_date DESC`;
|
||||||
@@ -19,7 +19,8 @@ export const getEligibleEvents = async (): Promise<EventSummary[]> => {
|
|||||||
name: row.name,
|
name: row.name,
|
||||||
subtitle: row.subtitle,
|
subtitle: row.subtitle,
|
||||||
eventDate: row.event_date,
|
eventDate: row.event_date,
|
||||||
feedbackDeadline: row.feedback_deadline
|
feedbackDeadline: row.feedback_deadline,
|
||||||
|
posterImageUrl: row.poster_image_url
|
||||||
}));
|
}));
|
||||||
} finally {
|
} finally {
|
||||||
await conn.end();
|
await conn.end();
|
||||||
@@ -41,7 +42,7 @@ export const getEventConfigBySlug = async (slug: string): Promise<EventLookupRes
|
|||||||
let conn = await NachklangFeedbackDB.getConnection();
|
let conn = await NachklangFeedbackDB.getConnection();
|
||||||
try {
|
try {
|
||||||
const eventQuery = `
|
const eventQuery = `
|
||||||
SELECT event_id, slug, name, subtitle, event_date, feedback_deadline, intro_text, is_published
|
SELECT event_id, slug, name, subtitle, event_date, feedback_deadline, intro_text, poster_image_url, is_published
|
||||||
FROM events WHERE slug = ?`;
|
FROM events WHERE slug = ?`;
|
||||||
const eventRows = await conn.query(eventQuery, [slug]);
|
const eventRows = await conn.query(eventQuery, [slug]);
|
||||||
if (eventRows.length === 0) {
|
if (eventRows.length === 0) {
|
||||||
@@ -91,6 +92,7 @@ export const getEventConfigBySlug = async (slug: string): Promise<EventLookupRes
|
|||||||
subtitle: eventRow.subtitle,
|
subtitle: eventRow.subtitle,
|
||||||
eventDate: eventRow.event_date,
|
eventDate: eventRow.event_date,
|
||||||
feedbackDeadline: eventRow.feedback_deadline,
|
feedbackDeadline: eventRow.feedback_deadline,
|
||||||
|
posterImageUrl: eventRow.poster_image_url,
|
||||||
introText: eventRow.intro_text,
|
introText: eventRow.intro_text,
|
||||||
songs,
|
songs,
|
||||||
questions
|
questions
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../../middleware/logger';
|
import logger from '../../../middleware/logger';
|
||||||
import {getEligibleEvents, getEventConfigBySlug} from './events.public.service';
|
import {getEligibleEvents, getEventConfigBySlug} from './events.public.service';
|
||||||
import {submitFeedback} from './submissions.service';
|
import {submitFeedback} from './submissions.service';
|
||||||
import {hashIp, isRateLimited, recordSubmission} from '../feedback.ratelimit';
|
import {hashIp, isRateLimited, recordSubmission} from '../feedback.ratelimit';
|
||||||
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
@@ -51,13 +51,7 @@ publicRouter.get('/events', async (req: Request, res: Response) => {
|
|||||||
const events = await getEligibleEvents();
|
const events = await getEligibleEvents();
|
||||||
res.status(200).send(events);
|
res.status(200).send(events);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
sendServerError(res, e);
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -106,13 +100,7 @@ publicRouter.get('/events/:slug', async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
res.status(200).send(result.event);
|
res.status(200).send(result.event);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
sendServerError(res, e);
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -166,7 +154,7 @@ publicRouter.post('/events/:slug/submissions', async (req: Request, res: Respons
|
|||||||
// nothing, stay silent about it having failed.
|
// nothing, stay silent about it having failed.
|
||||||
if (isHoneypotTriggered(body)) {
|
if (isHoneypotTriggered(body)) {
|
||||||
logger.info('Feedback honeypot triggered', {slug: req.params.slug});
|
logger.info('Feedback honeypot triggered', {slug: req.params.slug});
|
||||||
res.status(201).send({submissionId: -1});
|
res.status(201).send({submissionId: -1, newsletterDropped: false});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,16 +184,10 @@ publicRouter.post('/events/:slug/submissions', async (req: Request, res: Respons
|
|||||||
res.status(400).send({status: 'EMPTY_SUBMISSION'});
|
res.status(400).send({status: 'EMPTY_SUBMISSION'});
|
||||||
return;
|
return;
|
||||||
case 'OK':
|
case 'OK':
|
||||||
res.status(201).send({submissionId: result.submissionId});
|
res.status(201).send({submissionId: result.submissionId, newsletterDropped: result.newsletterDropped});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
sendServerError(res, e);
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -62,6 +62,9 @@
|
|||||||
* submissionId:
|
* submissionId:
|
||||||
* type: integer
|
* type: integer
|
||||||
* example: 91
|
* example: 91
|
||||||
|
* newsletterDropped:
|
||||||
|
* type: boolean
|
||||||
|
* description: True if the newsletter opt-in was present but failed validation (e.g. a malformed email) - the rest of the submission still saved.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export interface RatingInput {
|
export interface RatingInput {
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import {NachklangFeedbackDB} from '../Feedback.db';
|
|||||||
import {QuestionType} from '../feedback.interface';
|
import {QuestionType} from '../feedback.interface';
|
||||||
import {getEventConfigBySlug} from './events.public.service';
|
import {getEventConfigBySlug} from './events.public.service';
|
||||||
import {AnswerInput, GuestBookInput, NewsletterInput, SubmissionRequestBody} from './submission.interface';
|
import {AnswerInput, GuestBookInput, NewsletterInput, SubmissionRequestBody} from './submission.interface';
|
||||||
|
import {syncNewsletterSignup} from '../integrations/salesforce.service';
|
||||||
|
import logger from '../../../middleware/logger';
|
||||||
|
|
||||||
// Bump when the privacy/consent copy shown next to the newsletter opt-in
|
// Bump when the privacy/consent copy shown next to the newsletter opt-in
|
||||||
// changes; recorded per-signup so a past consent's exact wording is provable.
|
// changes; recorded per-signup so a past consent's exact wording is provable.
|
||||||
@@ -135,7 +137,7 @@ export const validateNewsletter = (input?: NewsletterInput): ValidatedNewsletter
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type SubmitResult =
|
export type SubmitResult =
|
||||||
| { status: 'OK'; submissionId: number }
|
| { status: 'OK'; submissionId: number; newsletterDropped: boolean }
|
||||||
| { status: 'NOT_FOUND' }
|
| { status: 'NOT_FOUND' }
|
||||||
| { status: 'CLOSED' }
|
| { status: 'CLOSED' }
|
||||||
| { status: 'EMPTY' };
|
| { status: 'EMPTY' };
|
||||||
@@ -158,6 +160,12 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody,
|
|||||||
const answerRows = validateAnswers(body.answers || [], questionsById, songTitleById);
|
const answerRows = validateAnswers(body.answers || [], questionsById, songTitleById);
|
||||||
const guestBook = validateGuestBook(body.guestBook);
|
const guestBook = validateGuestBook(body.guestBook);
|
||||||
const newsletter = validateNewsletter(body.newsletter);
|
const newsletter = validateNewsletter(body.newsletter);
|
||||||
|
// body.newsletter is only sent at all when the visitor had the opt-in
|
||||||
|
// checkbox on (see FeedbackForm.tsx), so a present-but-invalid block
|
||||||
|
// (e.g. a mistyped email) is distinguishable from "didn't opt in" - the
|
||||||
|
// rest of the submission still saves, but the client can tell the
|
||||||
|
// visitor their newsletter signup specifically didn't go through.
|
||||||
|
const newsletterDropped = !!body.newsletter && !newsletter;
|
||||||
|
|
||||||
if (answerRows.length === 0 && !guestBook && !newsletter) {
|
if (answerRows.length === 0 && !guestBook && !newsletter) {
|
||||||
return {status: 'EMPTY'};
|
return {status: 'EMPTY'};
|
||||||
@@ -186,21 +194,32 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody,
|
|||||||
await conn.query(gbQuery, [submissionId, eventId, guestBook.displayName, guestBook.message]);
|
await conn.query(gbQuery, [submissionId, eventId, guestBook.displayName, guestBook.message]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let newsletterSignupId: number | null = null;
|
||||||
if (newsletter) {
|
if (newsletter) {
|
||||||
// SALESFORCE_ENABLED is false until Phase 4's contract is known; the
|
// The signup is always persisted locally first, regardless of sync
|
||||||
// signup is always persisted locally first regardless of sync outcome.
|
// outcome - syncNewsletterSignup (fired after commit, below) is what
|
||||||
|
// actually talks to Salesforce and moves PENDING to SENT/FAILED.
|
||||||
const salesforceEnabled = process.env.SALESFORCE_ENABLED === 'true';
|
const salesforceEnabled = process.env.SALESFORCE_ENABLED === 'true';
|
||||||
const nlQuery = `INSERT INTO newsletter_signups
|
const nlQuery = `INSERT INTO newsletter_signups
|
||||||
(submission_id, event_id, first_name, last_name, email, consent_text_version, sync_status)
|
(submission_id, event_id, first_name, last_name, email, consent_text_version, sync_status)
|
||||||
VALUES (?,?,?,?,?,?,?)`;
|
VALUES (?,?,?,?,?,?,?) RETURNING signup_id`;
|
||||||
await conn.query(nlQuery, [
|
const nlRes = await conn.query(nlQuery, [
|
||||||
submissionId, eventId, newsletter.firstName, newsletter.lastName, newsletter.email,
|
submissionId, eventId, newsletter.firstName, newsletter.lastName, newsletter.email,
|
||||||
CONSENT_TEXT_VERSION, salesforceEnabled ? 'PENDING' : 'SKIPPED'
|
CONSENT_TEXT_VERSION, salesforceEnabled ? 'PENDING' : 'SKIPPED'
|
||||||
]);
|
]);
|
||||||
|
newsletterSignupId = nlRes[0].signup_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
return {status: 'OK', submissionId};
|
|
||||||
|
if (newsletterSignupId !== null) {
|
||||||
|
const signupId = newsletterSignupId;
|
||||||
|
void syncNewsletterSignup(signupId).catch((err) => {
|
||||||
|
logger.error('syncNewsletterSignup threw outside its own error handling', {signupId, error: String(err)});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {status: 'OK', submissionId, newsletterDropped};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await conn.rollback();
|
await conn.rollback();
|
||||||
throw err;
|
throw err;
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import * as dotenv from 'dotenv';
|
||||||
|
|
||||||
|
const mariadb = require('mariadb');
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
export namespace NachklangTicketsDB {
|
||||||
|
const pool = mariadb.createPool({
|
||||||
|
host: process.env.DB_HOST,
|
||||||
|
user: process.env.DB_USER,
|
||||||
|
password: process.env.DB_PASSWORD,
|
||||||
|
database: process.env.TICKETS_DB,
|
||||||
|
connectionLimit: 5,
|
||||||
|
autoCommit: false
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getConnection = async () => {
|
||||||
|
return pool.getConnection();
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import {adminRouter} from './admin/admin.router';
|
||||||
|
import {publicRouter} from './public/public.router';
|
||||||
|
|
||||||
|
export const ticketsRouter = express.Router();
|
||||||
|
|
||||||
|
ticketsRouter.use('/admin', adminRouter);
|
||||||
|
ticketsRouter.use('/', publicRouter);
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import express, {Request, Response} from 'express';
|
||||||
|
import {requireAdminAuth} from '../tickets.auth';
|
||||||
|
import {vouchersAdminRouter} from './vouchers.admin.router';
|
||||||
|
import {redemptionsAdminRouter, voucherHistoryRouter} from './redemptions.admin.router';
|
||||||
|
import {eventsAdminRouter} from './events.admin.router';
|
||||||
|
|
||||||
|
export const adminRouter = express.Router();
|
||||||
|
|
||||||
|
// Applied once at the top of the admin router tree - every route below
|
||||||
|
// requires a valid admin session (mirrors Feedback's admin.router.ts).
|
||||||
|
adminRouter.use(requireAdminAuth);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/me:
|
||||||
|
* get:
|
||||||
|
* summary: Validate the current admin session
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
adminRouter.get('/me', (req: Request, res: Response) => {
|
||||||
|
res.status(200).send({email: res.locals.admin.email, fullName: res.locals.admin.displayName});
|
||||||
|
});
|
||||||
|
|
||||||
|
adminRouter.use('/vouchers', vouchersAdminRouter);
|
||||||
|
adminRouter.use('/vouchers', voucherHistoryRouter);
|
||||||
|
adminRouter.use('/redemptions', redemptionsAdminRouter);
|
||||||
|
adminRouter.use('/events', eventsAdminRouter);
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
import express, {Request, Response} from 'express';
|
||||||
|
import * as EventsAdminService from './events.admin.service';
|
||||||
|
import {sendServerError} from '../tickets.errors';
|
||||||
|
|
||||||
|
export const eventsAdminRouter = express.Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/events:
|
||||||
|
* get:
|
||||||
|
* summary: List concerts for the admin event picker
|
||||||
|
* description: Wraps the Calendar module's public-calendar admin listing (includes DRAFT events).
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
eventsAdminRouter.get('/', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
res.status(200).send(await EventsAdminService.listEventsForPicker());
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/events/available:
|
||||||
|
* get:
|
||||||
|
* summary: List public-calendar events not yet added to the ticket shop
|
||||||
|
* description: Source list for the "add a concert" picker - the public calendar holds more than concerts, so events only appear in the ticket shop once explicitly added.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
eventsAdminRouter.get('/available', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
res.status(200).send(await EventsAdminService.listAvailableEventsToAdd());
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/events/{eventId}/stats:
|
||||||
|
* get:
|
||||||
|
* summary: Get a concert's voucher/capacity stats
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: eventId
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: integer
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* $ref: '#/components/schemas/EventStats'
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
eventsAdminRouter.get('/:eventId/stats', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
res.status(200).send(await EventsAdminService.getEventStats(Number(req.params.eventId)));
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/events/{eventId}/settings:
|
||||||
|
* put:
|
||||||
|
* summary: Set a concert's voucher settings
|
||||||
|
* description: Upserts capacity (null = uncapped), redemption deadline (null = none), and whether to collect a mailing address.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: eventId
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: integer
|
||||||
|
* requestBody:
|
||||||
|
* required: true
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* capacity:
|
||||||
|
* type: integer
|
||||||
|
* nullable: true
|
||||||
|
* redemptionDeadline:
|
||||||
|
* type: string
|
||||||
|
* format: date-time
|
||||||
|
* nullable: true
|
||||||
|
* collectAddress:
|
||||||
|
* type: boolean
|
||||||
|
* requireAddress:
|
||||||
|
* type: boolean
|
||||||
|
* description: Only meaningful when collectAddress is true.
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Saved
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
eventsAdminRouter.put('/:eventId/settings', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const {capacity, redemptionDeadline, collectAddress, requireAddress} = req.body || {};
|
||||||
|
await EventsAdminService.setEventSettings(Number(req.params.eventId), {
|
||||||
|
capacity: capacity ?? null,
|
||||||
|
// The mariadb driver needs an actual Date to serialize a DATETIME
|
||||||
|
// column correctly - a raw ISO string (as arrives over JSON) gets
|
||||||
|
// rejected with "Incorrect datetime value".
|
||||||
|
redemptionDeadline: redemptionDeadline ? new Date(redemptionDeadline) : null,
|
||||||
|
collectAddress: !!collectAddress,
|
||||||
|
requireAddress: !!collectAddress && !!requireAddress
|
||||||
|
});
|
||||||
|
res.status(200).send({status: 'OK'});
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/events/{eventId}/settings:
|
||||||
|
* delete:
|
||||||
|
* summary: Remove an event from the ticket shop
|
||||||
|
* description: Deletes its settings row, so it drops out of the picker and reappears in the "add" list. Refused with 409 if vouchers already reference the event - existing vouchers/redemptions stay valid either way.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: eventId
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: integer
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Removed
|
||||||
|
* 409:
|
||||||
|
* description: Vouchers already reference this event
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
eventsAdminRouter.delete('/:eventId/settings', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const result = await EventsAdminService.removeEvent(Number(req.params.eventId));
|
||||||
|
if (result === 'HAS_VOUCHERS') {
|
||||||
|
res.status(409).send({status: 'HAS_VOUCHERS', message: 'Für dieses Konzert existieren bereits Gutscheine.'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(200).send({status: 'OK'});
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import * as CalendarEventsService from '../../calendar/events/events.service';
|
||||||
|
import {NachklangTicketsDB} from '../Tickets.db';
|
||||||
|
import {getEventTicketState} from '../tickets.capacity';
|
||||||
|
import {EventStats, EventTicketSettings} from '../tickets.interface';
|
||||||
|
|
||||||
|
// Concerts are managed on the public calendar (calendarId 1) - see
|
||||||
|
// docs/plan-ticket-shop.md. getAllEventsAdmin includes DRAFT events so
|
||||||
|
// organizers can generate vouchers for a concert before it's announced.
|
||||||
|
const PUBLIC_CALENDAR_ID = 1;
|
||||||
|
|
||||||
|
export interface EventPickerEntry {
|
||||||
|
eventId: number;
|
||||||
|
name: string;
|
||||||
|
startDateTime: Date;
|
||||||
|
location: string;
|
||||||
|
status: string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The public calendar holds more than concerts (rehearsal announcements,
|
||||||
|
* general notices, etc.), and Calendar's own Event has no category field to
|
||||||
|
* tell them apart. `event_ticket_settings` doubles as the ticket shop's
|
||||||
|
* allow-list: a Calendar event only appears here once an admin has
|
||||||
|
* explicitly added it (see addEvent/removeEvent below) - even with every
|
||||||
|
* setting left at its default (uncapped, no deadline, no address).
|
||||||
|
*/
|
||||||
|
export const listEventsForPicker = async (): Promise<EventPickerEntry[]> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
let enabledEventIds: number[];
|
||||||
|
try {
|
||||||
|
const rows = await conn.query('SELECT event_id FROM event_ticket_settings');
|
||||||
|
enabledEventIds = rows.map((r: any) => r.event_id);
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
if (enabledEventIds.length === 0) return [];
|
||||||
|
|
||||||
|
const events = await Promise.all(enabledEventIds.map(id => CalendarEventsService.getEventById(id)));
|
||||||
|
return events
|
||||||
|
.filter((e): e is NonNullable<typeof e> => e !== null && e.status !== 'DELETED')
|
||||||
|
.map(e => ({eventId: e.eventId, name: e.name, startDateTime: e.startDateTime, location: e.location, status: e.status}))
|
||||||
|
.sort((a, b) => a.startDateTime.getTime() - b.startDateTime.getTime());
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public-calendar events that could be added to the ticket shop but
|
||||||
|
* haven't been yet - source list for the "add a concert" picker.
|
||||||
|
*/
|
||||||
|
export const listAvailableEventsToAdd = async (): Promise<EventPickerEntry[]> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
let enabledEventIds: Set<number>;
|
||||||
|
try {
|
||||||
|
const rows = await conn.query('SELECT event_id FROM event_ticket_settings');
|
||||||
|
enabledEventIds = new Set(rows.map((r: any) => r.event_id));
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
const events = await CalendarEventsService.getAllEventsAdmin(PUBLIC_CALENDAR_ID);
|
||||||
|
return events
|
||||||
|
.filter(e => e.status !== 'DELETED' && !enabledEventIds.has(e.eventId))
|
||||||
|
.map(e => ({eventId: e.eventId, name: e.name, startDateTime: e.startDateTime, location: e.location, status: e.status}))
|
||||||
|
.sort((a, b) => a.startDateTime.getTime() - b.startDateTime.getTime());
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getEventStats = async (eventId: number): Promise<EventStats> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
const ticketState = await getEventTicketState(conn, eventId);
|
||||||
|
|
||||||
|
const countRows = await conn.query(
|
||||||
|
`SELECT vc.status, COUNT(DISTINCT vc.code) as cnt
|
||||||
|
FROM voucher_codes vc
|
||||||
|
INNER JOIN voucher_code_events vce ON vce.code = vc.code
|
||||||
|
WHERE vce.event_id = ?
|
||||||
|
GROUP BY vc.status`,
|
||||||
|
[eventId]
|
||||||
|
);
|
||||||
|
let unusedCodes = 0, redeemedCodes = 0, voidCodes = 0;
|
||||||
|
for (const row of countRows) {
|
||||||
|
if (row.status === 'UNUSED') unusedCodes = Number(row.cnt);
|
||||||
|
if (row.status === 'REDEEMED') redeemedCodes = Number(row.cnt);
|
||||||
|
if (row.status === 'VOID') voidCodes = Number(row.cnt);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
eventId,
|
||||||
|
capacity: ticketState.capacity,
|
||||||
|
redemptionDeadline: ticketState.redemptionDeadline,
|
||||||
|
collectAddress: ticketState.collectAddress,
|
||||||
|
requireAddress: ticketState.requireAddress,
|
||||||
|
guestsUsed: ticketState.guestsUsed,
|
||||||
|
spotsRemaining: ticketState.spotsRemaining,
|
||||||
|
unusedCodes,
|
||||||
|
redeemedCodes,
|
||||||
|
voidCodes
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upsert - also doubles as "add this event to the ticket shop" when called
|
||||||
|
* with all-default values (see listEventsForPicker).
|
||||||
|
*/
|
||||||
|
export const setEventSettings = async (eventId: number, settings: Omit<EventTicketSettings, 'eventId'>): Promise<void> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
await conn.query(
|
||||||
|
`INSERT INTO event_ticket_settings (event_id, capacity, redemption_deadline, collect_address, require_address)
|
||||||
|
VALUES (?,?,?,?,?)
|
||||||
|
ON DUPLICATE KEY UPDATE capacity = VALUES(capacity), redemption_deadline = VALUES(redemption_deadline), collect_address = VALUES(collect_address), require_address = VALUES(require_address)`,
|
||||||
|
[eventId, settings.capacity, settings.redemptionDeadline, settings.collectAddress ? 1 : 0, settings.requireAddress ? 1 : 0]
|
||||||
|
);
|
||||||
|
await conn.commit();
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RemoveEventResult = 'REMOVED' | 'HAS_VOUCHERS';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes an event from the ticket shop (deletes its settings row, so it
|
||||||
|
* drops out of listEventsForPicker and reappears in the "add" list).
|
||||||
|
* Refuses if vouchers already reference it - existing vouchers/redemptions
|
||||||
|
* stay valid and keep working even for an event no longer offered for new
|
||||||
|
* voucher generation, so this only blocks removing one that's still in use.
|
||||||
|
*/
|
||||||
|
export const removeEvent = async (eventId: number): Promise<RemoveEventResult> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
const voucherRows = await conn.query('SELECT 1 FROM voucher_code_events WHERE event_id = ? LIMIT 1', [eventId]);
|
||||||
|
if (voucherRows.length > 0) {
|
||||||
|
await conn.rollback();
|
||||||
|
return 'HAS_VOUCHERS';
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.query('DELETE FROM event_ticket_settings WHERE event_id = ?', [eventId]);
|
||||||
|
await conn.commit();
|
||||||
|
return 'REMOVED';
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
import express, {Request, Response} from 'express';
|
||||||
|
import * as RedemptionsAdminService from './redemptions.admin.service';
|
||||||
|
import {sendServerError} from '../tickets.errors';
|
||||||
|
|
||||||
|
export const redemptionsAdminRouter = express.Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/redemptions:
|
||||||
|
* get:
|
||||||
|
* summary: List redemptions (admin)
|
||||||
|
* description: Filterable by event and status (ACTIVE/UNDONE).
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: query
|
||||||
|
* name: eventId
|
||||||
|
* schema:
|
||||||
|
* type: integer
|
||||||
|
* - in: query
|
||||||
|
* name: status
|
||||||
|
* schema:
|
||||||
|
* $ref: '#/components/schemas/RedemptionStatus'
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* $ref: '#/components/schemas/RedemptionSummary'
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
redemptionsAdminRouter.get('/', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const eventId = req.query.eventId !== undefined ? Number(req.query.eventId) : undefined;
|
||||||
|
const status = req.query.status as any;
|
||||||
|
res.status(200).send(await RedemptionsAdminService.listRedemptions({eventId, status}));
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/redemptions/{redemptionId}:
|
||||||
|
* get:
|
||||||
|
* summary: Get a single redemption (admin)
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: redemptionId
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: integer
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* 404:
|
||||||
|
* description: Unknown redemption
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
* patch:
|
||||||
|
* summary: Edit a redemption's contact info and/or guest list
|
||||||
|
* description: Only fields present in the body are changed. Growing the guest count is re-checked against the voucher's max guests and the event's remaining capacity. Logs to the audit trail with an optional admin-supplied reason.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: redemptionId
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: integer
|
||||||
|
* requestBody:
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* contactName:
|
||||||
|
* type: string
|
||||||
|
* contactEmail:
|
||||||
|
* type: string
|
||||||
|
* contactAddress:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* guestNames:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* type: string
|
||||||
|
* reason:
|
||||||
|
* type: string
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Edited
|
||||||
|
* 404:
|
||||||
|
* description: Unknown redemption
|
||||||
|
* 409:
|
||||||
|
* description: Not active, exceeds max guests, or exceeds remaining capacity
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
redemptionsAdminRouter.get('/:redemptionId', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const redemption = await RedemptionsAdminService.getRedemption(Number(req.params.redemptionId));
|
||||||
|
if (!redemption) {
|
||||||
|
res.status(404).send({status: 'NOT_FOUND'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(200).send(redemption);
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
redemptionsAdminRouter.patch('/:redemptionId', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const {contactName, contactEmail, contactAddress, guestNames, reason} = req.body || {};
|
||||||
|
const result = await RedemptionsAdminService.editRedemption(
|
||||||
|
Number(req.params.redemptionId),
|
||||||
|
{contactName, contactEmail, contactAddress, guestNames},
|
||||||
|
res.locals.admin.email,
|
||||||
|
reason || null
|
||||||
|
);
|
||||||
|
|
||||||
|
switch (result.status) {
|
||||||
|
case 'EDITED':
|
||||||
|
res.status(200).send({status: 'OK'});
|
||||||
|
return;
|
||||||
|
case 'NOT_FOUND':
|
||||||
|
res.status(404).send({status: 'NOT_FOUND'});
|
||||||
|
return;
|
||||||
|
case 'NOT_ACTIVE':
|
||||||
|
res.status(409).send({status: 'NOT_ACTIVE', message: 'This redemption is not active.'});
|
||||||
|
return;
|
||||||
|
case 'INVALID_EMAIL':
|
||||||
|
res.status(400).send({status: 'INVALID_EMAIL', message: 'Die E-Mail-Adresse sieht nicht gültig aus.'});
|
||||||
|
return;
|
||||||
|
case 'EXCEEDS_MAX_GUESTS':
|
||||||
|
res.status(409).send({status: 'EXCEEDS_MAX_GUESTS', maxGuests: result.maxGuests});
|
||||||
|
return;
|
||||||
|
case 'CAPACITY_EXCEEDED':
|
||||||
|
res.status(409).send({status: 'CAPACITY_EXCEEDED', spotsRemaining: result.spotsRemaining});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/redemptions/{redemptionId}/undo:
|
||||||
|
* post:
|
||||||
|
* summary: Undo a redemption
|
||||||
|
* description: Reopens the code (back to UNUSED) and marks the redemption UNDONE. Guest data is kept for the audit trail; a later re-redemption creates a new redemption record.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: redemptionId
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: integer
|
||||||
|
* requestBody:
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* reason:
|
||||||
|
* type: string
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Undone
|
||||||
|
* 404:
|
||||||
|
* description: Unknown redemption
|
||||||
|
* 409:
|
||||||
|
* description: Redemption is not active
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
redemptionsAdminRouter.post('/:redemptionId/undo', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const result = await RedemptionsAdminService.undoRedemption(Number(req.params.redemptionId), res.locals.admin.email, req.body?.reason || null);
|
||||||
|
if (result === 'NOT_FOUND') {
|
||||||
|
res.status(404).send({status: 'NOT_FOUND'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result === 'NOT_ACTIVE') {
|
||||||
|
res.status(409).send({status: 'NOT_ACTIVE', message: 'This redemption is not active.'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(200).send({status: 'OK'});
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/vouchers/{code}/history:
|
||||||
|
* get:
|
||||||
|
* summary: Get a voucher's admin-action audit trail
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: code
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: string
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* $ref: '#/components/schemas/AuditLogEntry'
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
export const voucherHistoryRouter = express.Router();
|
||||||
|
voucherHistoryRouter.get('/:code/history', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
res.status(200).send(await RedemptionsAdminService.getAuditHistory(req.params.code));
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import {NachklangTicketsDB} from '../Tickets.db';
|
||||||
|
import {getEventTicketState} from '../tickets.capacity';
|
||||||
|
import {AuditLogEntry, RedemptionSummary} from '../tickets.interface';
|
||||||
|
import {isValidEmail} from '../tickets.validation';
|
||||||
|
|
||||||
|
const mapRedemptionRow = (row: any, guests: string[]): RedemptionSummary => ({
|
||||||
|
redemptionId: row.redemption_id,
|
||||||
|
code: row.code,
|
||||||
|
eventId: row.event_id,
|
||||||
|
status: row.status,
|
||||||
|
contactName: row.contact_name,
|
||||||
|
contactEmail: row.contact_email,
|
||||||
|
contactAddress: row.contact_address,
|
||||||
|
guestCount: row.guest_count,
|
||||||
|
guests,
|
||||||
|
redeemedAt: row.redeemed_at
|
||||||
|
});
|
||||||
|
|
||||||
|
export interface ListRedemptionsFilter {
|
||||||
|
eventId?: number;
|
||||||
|
status?: 'ACTIVE' | 'UNDONE';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const listRedemptions = async (filter: ListRedemptionsFilter): Promise<RedemptionSummary[]> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
const where: string[] = [];
|
||||||
|
const params: any[] = [];
|
||||||
|
if (filter.eventId !== undefined) {
|
||||||
|
where.push('event_id = ?');
|
||||||
|
params.push(filter.eventId);
|
||||||
|
}
|
||||||
|
if (filter.status) {
|
||||||
|
where.push('status = ?');
|
||||||
|
params.push(filter.status);
|
||||||
|
}
|
||||||
|
let query = 'SELECT * FROM redemptions';
|
||||||
|
if (where.length > 0) query += ' WHERE ' + where.join(' AND ');
|
||||||
|
query += ' ORDER BY redeemed_at DESC';
|
||||||
|
|
||||||
|
const rows = await conn.query(query, params);
|
||||||
|
if (rows.length === 0) return [];
|
||||||
|
|
||||||
|
const redemptionIds = rows.map((r: any) => r.redemption_id);
|
||||||
|
const guestRows = await conn.query(
|
||||||
|
'SELECT redemption_id, name FROM redemption_guests WHERE redemption_id IN (?) ORDER BY redemption_id, position',
|
||||||
|
[redemptionIds]
|
||||||
|
);
|
||||||
|
const guestsByRedemption = new Map<number, string[]>();
|
||||||
|
for (const g of guestRows) {
|
||||||
|
const list = guestsByRedemption.get(g.redemption_id) || [];
|
||||||
|
list.push(g.name);
|
||||||
|
guestsByRedemption.set(g.redemption_id, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
return rows.map((row: any) => mapRedemptionRow(row, guestsByRedemption.get(row.redemption_id) || []));
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getRedemption = async (redemptionId: number): Promise<RedemptionSummary | null> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
const rows = await conn.query('SELECT * FROM redemptions WHERE redemption_id = ?', [redemptionId]);
|
||||||
|
if (rows.length === 0) return null;
|
||||||
|
const guestRows = await conn.query('SELECT name FROM redemption_guests WHERE redemption_id = ? ORDER BY position', [redemptionId]);
|
||||||
|
return mapRedemptionRow(rows[0], guestRows.map((g: any) => g.name));
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UndoRedemptionResult = 'UNDONE' | 'NOT_FOUND' | 'NOT_ACTIVE';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reopens the code (back to UNUSED) and marks the redemption UNDONE
|
||||||
|
* (soft-state, not deleted - guest names/contact info stay for the audit
|
||||||
|
* trail). A later re-redemption of the same code creates a new
|
||||||
|
* redemptions row rather than reviving this one.
|
||||||
|
*/
|
||||||
|
export const undoRedemption = async (redemptionId: number, adminEmail: string, reason: string | null): Promise<UndoRedemptionResult> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
const rows = await conn.query('SELECT * FROM redemptions WHERE redemption_id = ? FOR UPDATE', [redemptionId]);
|
||||||
|
if (rows.length === 0) {
|
||||||
|
await conn.rollback();
|
||||||
|
return 'NOT_FOUND';
|
||||||
|
}
|
||||||
|
const redemption = rows[0];
|
||||||
|
if (redemption.status !== 'ACTIVE') {
|
||||||
|
await conn.rollback();
|
||||||
|
return 'NOT_ACTIVE';
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.query('UPDATE redemptions SET status = ? WHERE redemption_id = ?', ['UNDONE', redemptionId]);
|
||||||
|
await conn.query('UPDATE voucher_codes SET status = ? WHERE code = ?', ['UNUSED', redemption.code]);
|
||||||
|
await conn.query(
|
||||||
|
'INSERT INTO voucher_audit_log (code, redemption_id, admin_email, action, reason) VALUES (?,?,?,?,?)',
|
||||||
|
[redemption.code, redemptionId, adminEmail, 'UNDO', reason]
|
||||||
|
);
|
||||||
|
|
||||||
|
await conn.commit();
|
||||||
|
return 'UNDONE';
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface EditRedemptionInput {
|
||||||
|
contactName?: string;
|
||||||
|
contactEmail?: string;
|
||||||
|
contactAddress?: string | null;
|
||||||
|
guestNames?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EditRedemptionResult =
|
||||||
|
| {status: 'EDITED'}
|
||||||
|
| {status: 'NOT_FOUND'}
|
||||||
|
| {status: 'NOT_ACTIVE'}
|
||||||
|
| {status: 'INVALID_EMAIL'}
|
||||||
|
| {status: 'EXCEEDS_MAX_GUESTS'; maxGuests: number}
|
||||||
|
| {status: 'CAPACITY_EXCEEDED'; spotsRemaining: number};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Direct admin correction of a redemption's contact info and/or guest
|
||||||
|
* list. Only the fields present in `input` are changed. Growing the guest
|
||||||
|
* count is re-checked against both the voucher's own max_guests and the
|
||||||
|
* event's remaining capacity (forUpdate=true, same race-safety approach as
|
||||||
|
* the public redeem path).
|
||||||
|
*/
|
||||||
|
export const editRedemption = async (redemptionId: number, input: EditRedemptionInput, adminEmail: string, reason: string | null): Promise<EditRedemptionResult> => {
|
||||||
|
if (input.contactEmail !== undefined && !isValidEmail(input.contactEmail)) {
|
||||||
|
return {status: 'INVALID_EMAIL'};
|
||||||
|
}
|
||||||
|
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
const rows = await conn.query('SELECT * FROM redemptions WHERE redemption_id = ? FOR UPDATE', [redemptionId]);
|
||||||
|
if (rows.length === 0) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'NOT_FOUND'};
|
||||||
|
}
|
||||||
|
const before = rows[0];
|
||||||
|
if (before.status !== 'ACTIVE') {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'NOT_ACTIVE'};
|
||||||
|
}
|
||||||
|
|
||||||
|
const changeSummary: Record<string, {before: any; after: any}> = {};
|
||||||
|
const fields: string[] = [];
|
||||||
|
const values: any[] = [];
|
||||||
|
|
||||||
|
if (input.contactName !== undefined && input.contactName !== before.contact_name) {
|
||||||
|
changeSummary.contactName = {before: before.contact_name, after: input.contactName};
|
||||||
|
fields.push('contact_name = ?');
|
||||||
|
values.push(input.contactName);
|
||||||
|
}
|
||||||
|
if (input.contactEmail !== undefined && input.contactEmail !== before.contact_email) {
|
||||||
|
changeSummary.contactEmail = {before: before.contact_email, after: input.contactEmail};
|
||||||
|
fields.push('contact_email = ?');
|
||||||
|
values.push(input.contactEmail);
|
||||||
|
}
|
||||||
|
if (input.contactAddress !== undefined && input.contactAddress !== before.contact_address) {
|
||||||
|
changeSummary.contactAddress = {before: before.contact_address, after: input.contactAddress};
|
||||||
|
fields.push('contact_address = ?');
|
||||||
|
values.push(input.contactAddress);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.guestNames !== undefined) {
|
||||||
|
const newCount = input.guestNames.length;
|
||||||
|
const delta = newCount - before.guest_count;
|
||||||
|
|
||||||
|
if (delta > 0) {
|
||||||
|
const voucherRows = await conn.query('SELECT max_guests FROM voucher_codes WHERE code = ?', [before.code]);
|
||||||
|
const maxGuests = voucherRows[0].max_guests;
|
||||||
|
if (newCount > maxGuests) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'EXCEEDS_MAX_GUESTS', maxGuests};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ticketState = await getEventTicketState(conn, before.event_id, true);
|
||||||
|
if (ticketState.spotsRemaining !== null && delta > ticketState.spotsRemaining) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'CAPACITY_EXCEEDED', spotsRemaining: ticketState.spotsRemaining};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldGuestRows = await conn.query('SELECT name FROM redemption_guests WHERE redemption_id = ? ORDER BY position', [redemptionId]);
|
||||||
|
changeSummary.guests = {before: oldGuestRows.map((g: any) => g.name), after: input.guestNames};
|
||||||
|
|
||||||
|
fields.push('guest_count = ?');
|
||||||
|
values.push(newCount);
|
||||||
|
|
||||||
|
await conn.query('DELETE FROM redemption_guests WHERE redemption_id = ?', [redemptionId]);
|
||||||
|
for (let i = 0; i < input.guestNames.length; i++) {
|
||||||
|
await conn.query('INSERT INTO redemption_guests (redemption_id, name, position) VALUES (?,?,?)', [redemptionId, input.guestNames[i], i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fields.length > 0) {
|
||||||
|
values.push(redemptionId);
|
||||||
|
await conn.query(`UPDATE redemptions SET ${fields.join(', ')} WHERE redemption_id = ?`, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(changeSummary).length > 0) {
|
||||||
|
await conn.query(
|
||||||
|
'INSERT INTO voucher_audit_log (code, redemption_id, admin_email, action, change_summary, reason) VALUES (?,?,?,?,?,?)',
|
||||||
|
[before.code, redemptionId, adminEmail, 'EDIT', JSON.stringify(changeSummary), reason]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.commit();
|
||||||
|
return {status: 'EDITED'};
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAuditHistory = async (code: string): Promise<AuditLogEntry[]> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
const rows = await conn.query('SELECT * FROM voucher_audit_log WHERE code = ? ORDER BY created_at DESC', [code]);
|
||||||
|
return rows.map((row: any) => ({
|
||||||
|
auditId: row.audit_id,
|
||||||
|
code: row.code,
|
||||||
|
redemptionId: row.redemption_id,
|
||||||
|
adminEmail: row.admin_email,
|
||||||
|
action: row.action,
|
||||||
|
// The mariadb driver already deserializes JSON-typed columns into
|
||||||
|
// objects - only parse if we somehow got a raw string back.
|
||||||
|
changeSummary: typeof row.change_summary === 'string' ? JSON.parse(row.change_summary) : (row.change_summary ?? null),
|
||||||
|
reason: row.reason,
|
||||||
|
createdAt: row.created_at
|
||||||
|
}));
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import express, {Request, Response} from 'express';
|
||||||
|
import * as VouchersAdminService from './vouchers.admin.service';
|
||||||
|
import {sendServerError} from '../tickets.errors';
|
||||||
|
|
||||||
|
export const vouchersAdminRouter = express.Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/vouchers:
|
||||||
|
* get:
|
||||||
|
* summary: List vouchers (admin)
|
||||||
|
* description: Filterable by event and status.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: query
|
||||||
|
* name: eventId
|
||||||
|
* schema:
|
||||||
|
* type: integer
|
||||||
|
* - in: query
|
||||||
|
* name: status
|
||||||
|
* schema:
|
||||||
|
* $ref: '#/components/schemas/VoucherStatus'
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* $ref: '#/components/schemas/VoucherCode'
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
vouchersAdminRouter.get('/', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const eventId = req.query.eventId !== undefined ? Number(req.query.eventId) : undefined;
|
||||||
|
const status = req.query.status as any;
|
||||||
|
res.status(200).send(await VouchersAdminService.listVouchers({eventId, status}));
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/vouchers/wildcard:
|
||||||
|
* post:
|
||||||
|
* summary: Batch-generate wildcard codes
|
||||||
|
* description: Generates `quantity` codes sharing the same eligible events and max-guest count, grouped under one batchId.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* requestBody:
|
||||||
|
* required: true
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* required: [eventIds, quantity]
|
||||||
|
* properties:
|
||||||
|
* eventIds:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* type: integer
|
||||||
|
* maxGuests:
|
||||||
|
* type: integer
|
||||||
|
* default: 2
|
||||||
|
* quantity:
|
||||||
|
* type: integer
|
||||||
|
* responses:
|
||||||
|
* 201:
|
||||||
|
* description: Created
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* codes:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* type: string
|
||||||
|
* 400:
|
||||||
|
* description: Invalid input
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
vouchersAdminRouter.post('/wildcard', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const {eventIds, maxGuests, quantity} = req.body || {};
|
||||||
|
if (!Array.isArray(eventIds) || eventIds.length === 0 || !quantity) {
|
||||||
|
res.status(400).send({status: 'BAD_REQUEST', message: 'eventIds and quantity are required'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const codes = await VouchersAdminService.generateWildcardBatch(
|
||||||
|
{eventIds, maxGuests: maxGuests || 2, quantity},
|
||||||
|
res.locals.admin.email
|
||||||
|
);
|
||||||
|
res.status(201).send({codes});
|
||||||
|
} catch (e: any) {
|
||||||
|
res.status(400).send({status: 'BAD_REQUEST', message: e.message});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/vouchers/personalized:
|
||||||
|
* post:
|
||||||
|
* summary: Bulk-create personalized codes
|
||||||
|
* description: One code per row (name, email, eligible events, max guests), grouped under one batchId.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* requestBody:
|
||||||
|
* required: true
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* required: [rows]
|
||||||
|
* properties:
|
||||||
|
* rows:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* type: object
|
||||||
|
* required: [name, email, eventIds]
|
||||||
|
* properties:
|
||||||
|
* name:
|
||||||
|
* type: string
|
||||||
|
* email:
|
||||||
|
* type: string
|
||||||
|
* eventIds:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* type: integer
|
||||||
|
* maxGuests:
|
||||||
|
* type: integer
|
||||||
|
* default: 2
|
||||||
|
* responses:
|
||||||
|
* 201:
|
||||||
|
* description: Created
|
||||||
|
* 400:
|
||||||
|
* description: Invalid input
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
vouchersAdminRouter.post('/personalized', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const rows = (req.body?.rows || []).map((r: any) => ({
|
||||||
|
name: r.name,
|
||||||
|
email: r.email,
|
||||||
|
eventIds: r.eventIds || [],
|
||||||
|
maxGuests: r.maxGuests || 2
|
||||||
|
}));
|
||||||
|
const codes = await VouchersAdminService.generatePersonalizedBatch(rows, res.locals.admin.email);
|
||||||
|
res.status(201).send({codes});
|
||||||
|
} catch (e: any) {
|
||||||
|
res.status(400).send({status: 'BAD_REQUEST', message: e.message});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/vouchers/{code}:
|
||||||
|
* get:
|
||||||
|
* summary: Get a single voucher (admin)
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: code
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: string
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* 404:
|
||||||
|
* description: Unknown code
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
vouchersAdminRouter.get('/:code', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const voucher = await VouchersAdminService.getVoucher(req.params.code);
|
||||||
|
if (!voucher) {
|
||||||
|
res.status(404).send({status: 'NOT_FOUND'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(200).send(voucher);
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/admin/vouchers/{code}/void:
|
||||||
|
* post:
|
||||||
|
* summary: Void an unredeemed code
|
||||||
|
* description: Only allowed while the code is UNUSED. Logs to the voucher's audit trail.
|
||||||
|
* tags: [tickets-admin]
|
||||||
|
* parameters:
|
||||||
|
* - $ref: '#/components/parameters/SessionIdHeader'
|
||||||
|
* - $ref: '#/components/parameters/SessionKeyHeader'
|
||||||
|
* - in: path
|
||||||
|
* name: code
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: string
|
||||||
|
* requestBody:
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* reason:
|
||||||
|
* type: string
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Voided
|
||||||
|
* 404:
|
||||||
|
* description: Unknown code
|
||||||
|
* 409:
|
||||||
|
* description: Code is not in UNUSED status
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized
|
||||||
|
*/
|
||||||
|
vouchersAdminRouter.post('/:code/void', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const result = await VouchersAdminService.voidCode(req.params.code, res.locals.admin.email, req.body?.reason || null);
|
||||||
|
if (result === 'NOT_FOUND') {
|
||||||
|
res.status(404).send({status: 'NOT_FOUND'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result === 'NOT_UNUSED') {
|
||||||
|
res.status(409).send({status: 'NOT_UNUSED', message: 'Only unused codes can be voided.'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(200).send({status: 'OK'});
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
import {Guid} from 'guid-typescript';
|
||||||
|
import {NachklangTicketsDB} from '../Tickets.db';
|
||||||
|
import {generateUniqueCode} from '../tickets.codes';
|
||||||
|
import {VoucherCode, VoucherStatus} from '../tickets.interface';
|
||||||
|
import {isValidEmail} from '../tickets.validation';
|
||||||
|
|
||||||
|
export interface WildcardGenerateInput {
|
||||||
|
eventIds: number[];
|
||||||
|
maxGuests: number;
|
||||||
|
quantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PersonalizedRowInput {
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
eventIds: number[];
|
||||||
|
maxGuests: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mapVoucherRow = (row: any): VoucherCode => ({
|
||||||
|
code: row.code,
|
||||||
|
status: row.status,
|
||||||
|
maxGuests: row.max_guests,
|
||||||
|
prefillName: row.prefill_name,
|
||||||
|
prefillEmail: row.prefill_email,
|
||||||
|
batchId: row.batch_id,
|
||||||
|
createdByEmail: row.created_by_email,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
eligibleEventIds: []
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Guards the event allow-list (event_ticket_settings) at the one place
|
||||||
|
* codes actually get minted - the admin event picker already filters to
|
||||||
|
* allow-listed events, but that's cosmetic unless generation enforces the
|
||||||
|
* same rule server-side. Without this, any event_id could be passed
|
||||||
|
* directly (bypassing the picker) and get a fully-uncapped, no-deadline
|
||||||
|
* redeemable code minted for a non-concert Calendar event.
|
||||||
|
*/
|
||||||
|
const assertEventsAllowListed = async (conn: any, eventIds: number[]): Promise<void> => {
|
||||||
|
const uniqueIds = [...new Set(eventIds)];
|
||||||
|
const rows = await conn.query('SELECT event_id FROM event_ticket_settings WHERE event_id IN (?)', [uniqueIds]);
|
||||||
|
const allowListed = new Set<number>(rows.map((r: any) => r.event_id));
|
||||||
|
const missing = uniqueIds.filter(id => !allowListed.has(id));
|
||||||
|
if (missing.length > 0) {
|
||||||
|
throw new Error(`event(s) not added to the ticket shop yet: ${missing.join(', ')}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attaches eligibleEventIds to a list of voucher rows in one extra query,
|
||||||
|
* rather than N+1 per code.
|
||||||
|
*/
|
||||||
|
const attachEligibleEvents = async (conn: any, vouchers: VoucherCode[]): Promise<VoucherCode[]> => {
|
||||||
|
if (vouchers.length === 0) return vouchers;
|
||||||
|
const codes = vouchers.map(v => v.code);
|
||||||
|
const rows = await conn.query('SELECT code, event_id FROM voucher_code_events WHERE code IN (?)', [codes]);
|
||||||
|
const byCode = new Map<string, number[]>();
|
||||||
|
for (const row of rows) {
|
||||||
|
const list = byCode.get(row.code) || [];
|
||||||
|
list.push(row.event_id);
|
||||||
|
byCode.set(row.code, list);
|
||||||
|
}
|
||||||
|
for (const voucher of vouchers) {
|
||||||
|
voucher.eligibleEventIds = byCode.get(voucher.code) || [];
|
||||||
|
}
|
||||||
|
return vouchers;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Batch-generates N wildcard codes sharing the same eligible events and
|
||||||
|
* max-guest count. All codes get the same batchId so the admin UI can group
|
||||||
|
* "codes generated together" (e.g. for printing a sheet for the conductor).
|
||||||
|
*/
|
||||||
|
export const generateWildcardBatch = async (input: WildcardGenerateInput, createdByEmail: string): Promise<string[]> => {
|
||||||
|
if (input.quantity < 1 || input.quantity > 500) {
|
||||||
|
throw new Error('quantity must be between 1 and 500');
|
||||||
|
}
|
||||||
|
if (input.eventIds.length === 0) {
|
||||||
|
throw new Error('at least one eligible event is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
await assertEventsAllowListed(conn, input.eventIds);
|
||||||
|
|
||||||
|
const existingRows = await conn.query('SELECT code FROM voucher_codes');
|
||||||
|
const existingCodes = new Set<string>(existingRows.map((r: any) => r.code));
|
||||||
|
|
||||||
|
const batchId = Guid.create().toString();
|
||||||
|
const codes: string[] = [];
|
||||||
|
for (let i = 0; i < input.quantity; i++) {
|
||||||
|
const code = generateUniqueCode(existingCodes);
|
||||||
|
codes.push(code);
|
||||||
|
await conn.query(
|
||||||
|
'INSERT INTO voucher_codes (code, status, max_guests, batch_id, created_by_email) VALUES (?,?,?,?,?)',
|
||||||
|
[code, 'UNUSED', input.maxGuests, batchId, createdByEmail]
|
||||||
|
);
|
||||||
|
for (const eventId of input.eventIds) {
|
||||||
|
await conn.query('INSERT INTO voucher_code_events (code, event_id) VALUES (?,?)', [code, eventId]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.commit();
|
||||||
|
return codes;
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bulk-creates personalized codes from a list of rows (repeating-row admin
|
||||||
|
* UI - see docs/plan-ticket-shop.md). One code per row, all sharing a
|
||||||
|
* batchId for the submission.
|
||||||
|
*/
|
||||||
|
export const generatePersonalizedBatch = async (rows: PersonalizedRowInput[], createdByEmail: string): Promise<string[]> => {
|
||||||
|
if (rows.length === 0) {
|
||||||
|
throw new Error('at least one row is required');
|
||||||
|
}
|
||||||
|
for (const row of rows) {
|
||||||
|
if (!row.name || !row.email || row.eventIds.length === 0) {
|
||||||
|
throw new Error('each row requires a name, email, and at least one eligible event');
|
||||||
|
}
|
||||||
|
if (!isValidEmail(row.email)) {
|
||||||
|
throw new Error(`"${row.email}" does not look like a valid email address`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
await assertEventsAllowListed(conn, rows.flatMap(r => r.eventIds));
|
||||||
|
|
||||||
|
const existingRows = await conn.query('SELECT code FROM voucher_codes');
|
||||||
|
const existingCodes = new Set<string>(existingRows.map((r: any) => r.code));
|
||||||
|
|
||||||
|
const batchId = Guid.create().toString();
|
||||||
|
const codes: string[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
const code = generateUniqueCode(existingCodes);
|
||||||
|
codes.push(code);
|
||||||
|
await conn.query(
|
||||||
|
'INSERT INTO voucher_codes (code, status, max_guests, prefill_name, prefill_email, batch_id, created_by_email) VALUES (?,?,?,?,?,?,?)',
|
||||||
|
[code, 'UNUSED', row.maxGuests, row.name, row.email, batchId, createdByEmail]
|
||||||
|
);
|
||||||
|
for (const eventId of row.eventIds) {
|
||||||
|
await conn.query('INSERT INTO voucher_code_events (code, event_id) VALUES (?,?)', [code, eventId]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.commit();
|
||||||
|
return codes;
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface ListVouchersFilter {
|
||||||
|
eventId?: number;
|
||||||
|
status?: VoucherStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const listVouchers = async (filter: ListVouchersFilter): Promise<VoucherCode[]> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
let query = 'SELECT vc.* FROM voucher_codes vc';
|
||||||
|
const params: any[] = [];
|
||||||
|
const where: string[] = [];
|
||||||
|
|
||||||
|
if (filter.eventId !== undefined) {
|
||||||
|
query += ' INNER JOIN voucher_code_events vce ON vce.code = vc.code';
|
||||||
|
where.push('vce.event_id = ?');
|
||||||
|
params.push(filter.eventId);
|
||||||
|
}
|
||||||
|
if (filter.status) {
|
||||||
|
where.push('vc.status = ?');
|
||||||
|
params.push(filter.status);
|
||||||
|
}
|
||||||
|
if (where.length > 0) {
|
||||||
|
query += ' WHERE ' + where.join(' AND ');
|
||||||
|
}
|
||||||
|
query += ' GROUP BY vc.code ORDER BY vc.created_at DESC';
|
||||||
|
|
||||||
|
const rows = await conn.query(query, params);
|
||||||
|
const vouchers = rows.map(mapVoucherRow);
|
||||||
|
return await attachEligibleEvents(conn, vouchers);
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getVoucher = async (code: string): Promise<VoucherCode | null> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
const rows = await conn.query('SELECT * FROM voucher_codes WHERE code = ?', [code]);
|
||||||
|
if (rows.length === 0) return null;
|
||||||
|
const [voucher] = await attachEligibleEvents(conn, [mapVoucherRow(rows[0])]);
|
||||||
|
return voucher;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export type VoidCodeResult = 'VOIDED' | 'NOT_FOUND' | 'NOT_UNUSED';
|
||||||
|
|
||||||
|
export const voidCode = async (code: string, adminEmail: string, reason: string | null): Promise<VoidCodeResult> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
const rows = await conn.query('SELECT status FROM voucher_codes WHERE code = ?', [code]);
|
||||||
|
if (rows.length === 0) {
|
||||||
|
await conn.rollback();
|
||||||
|
return 'NOT_FOUND';
|
||||||
|
}
|
||||||
|
if (rows[0].status !== 'UNUSED') {
|
||||||
|
await conn.rollback();
|
||||||
|
return 'NOT_UNUSED';
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.query('UPDATE voucher_codes SET status = ? WHERE code = ?', ['VOID', code]);
|
||||||
|
await conn.query(
|
||||||
|
'INSERT INTO voucher_audit_log (code, redemption_id, admin_email, action, reason) VALUES (?,NULL,?,?,?)',
|
||||||
|
[code, adminEmail, 'VOID', reason]
|
||||||
|
);
|
||||||
|
|
||||||
|
await conn.commit();
|
||||||
|
return 'VOIDED';
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import express, {Request, Response} from 'express';
|
||||||
|
import * as VoucherPublicService from './voucher.public.service';
|
||||||
|
import {sendServerError} from '../tickets.errors';
|
||||||
|
import {hashIp, redeemLimiter, validateLimiter} from '../tickets.ratelimit';
|
||||||
|
|
||||||
|
export const publicRouter = express.Router();
|
||||||
|
|
||||||
|
publicRouter.get('/', async (req: Request, res: Response) => {
|
||||||
|
res.status(200).send('Nachklang e.V. Tickets API Endpoint');
|
||||||
|
});
|
||||||
|
|
||||||
|
const rateLimitGuard = (req: Request, res: Response, limiter: typeof validateLimiter): string | null => {
|
||||||
|
const ipHash = hashIp(req.ip || '');
|
||||||
|
if (limiter.isRateLimited(ipHash)) {
|
||||||
|
res.status(429).send({status: 'RATE_LIMITED', message: 'Zu viele Anfragen. Bitte versuche es später erneut.'});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return ipHash;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/voucher/{code}:
|
||||||
|
* get:
|
||||||
|
* summary: Validate a voucher code
|
||||||
|
* description: Returns status, prefill data, and eligible events (with deadline/capacity state) for a code. Rate-limited per IP.
|
||||||
|
* tags: [tickets]
|
||||||
|
* parameters:
|
||||||
|
* - in: path
|
||||||
|
* name: code
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: string
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* $ref: '#/components/schemas/VoucherValidation'
|
||||||
|
* 404:
|
||||||
|
* description: Unknown code
|
||||||
|
* 429:
|
||||||
|
* description: Rate limited
|
||||||
|
*/
|
||||||
|
publicRouter.get('/voucher/:code', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const ipHash = rateLimitGuard(req, res, validateLimiter);
|
||||||
|
if (!ipHash) return;
|
||||||
|
validateLimiter.recordRequest(ipHash);
|
||||||
|
|
||||||
|
const voucher = await VoucherPublicService.validateVoucher(req.params.code.toUpperCase());
|
||||||
|
if (!voucher) {
|
||||||
|
res.status(404).send({status: 'NOT_FOUND'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(200).send(voucher);
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /tickets/voucher/{code}/redeem:
|
||||||
|
* post:
|
||||||
|
* summary: Redeem a voucher code
|
||||||
|
* description: Marks the code redeemed, records the redemption, and sends a confirmation email with an .ics attachment. Rate-limited per IP.
|
||||||
|
* tags: [tickets]
|
||||||
|
* parameters:
|
||||||
|
* - in: path
|
||||||
|
* name: code
|
||||||
|
* required: true
|
||||||
|
* schema:
|
||||||
|
* type: string
|
||||||
|
* requestBody:
|
||||||
|
* required: true
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* $ref: '#/components/schemas/RedeemRequest'
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Redeemed
|
||||||
|
* 400:
|
||||||
|
* description: Invalid request
|
||||||
|
* 404:
|
||||||
|
* description: Unknown code
|
||||||
|
* 409:
|
||||||
|
* description: Code already used, event no longer eligible, deadline passed, or capacity exceeded
|
||||||
|
* 429:
|
||||||
|
* description: Rate limited
|
||||||
|
*/
|
||||||
|
publicRouter.post('/voucher/:code/redeem', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const ipHash = rateLimitGuard(req, res, redeemLimiter);
|
||||||
|
if (!ipHash) return;
|
||||||
|
redeemLimiter.recordRequest(ipHash);
|
||||||
|
|
||||||
|
const code = req.params.code.toUpperCase();
|
||||||
|
const {eventId, contactName, contactEmail, contactAddress, guests} = req.body || {};
|
||||||
|
if (!eventId || !contactName || !contactEmail || !Array.isArray(guests)) {
|
||||||
|
res.status(400).send({status: 'BAD_REQUEST', message: 'eventId, contactName, contactEmail, and guests are required'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await VoucherPublicService.redeemVoucher(code, {eventId, contactName, contactEmail, contactAddress, guests});
|
||||||
|
|
||||||
|
switch (result.status) {
|
||||||
|
case 'OK':
|
||||||
|
res.status(200).send({status: 'OK', redemptionId: result.redemptionId});
|
||||||
|
return;
|
||||||
|
case 'NOT_FOUND':
|
||||||
|
res.status(404).send({status: 'NOT_FOUND'});
|
||||||
|
return;
|
||||||
|
case 'ALREADY_USED':
|
||||||
|
res.status(409).send({status: 'ALREADY_USED', message: 'Dieser Code wurde bereits eingelöst.'});
|
||||||
|
return;
|
||||||
|
case 'INVALID_EVENT':
|
||||||
|
res.status(409).send({status: 'INVALID_EVENT', message: 'Dieses Konzert ist für diesen Code nicht verfügbar.'});
|
||||||
|
return;
|
||||||
|
case 'DEADLINE_PASSED':
|
||||||
|
res.status(409).send({status: 'DEADLINE_PASSED', message: 'Die Anmeldefrist für dieses Konzert ist abgelaufen.'});
|
||||||
|
return;
|
||||||
|
case 'CAPACITY_EXCEEDED':
|
||||||
|
res.status(409).send({status: 'CAPACITY_EXCEEDED', message: 'Nicht genügend freie Plätze für dieses Konzert.', spotsRemaining: result.spotsRemaining});
|
||||||
|
return;
|
||||||
|
case 'ADDRESS_REQUIRED':
|
||||||
|
res.status(409).send({status: 'ADDRESS_REQUIRED', message: 'Für dieses Konzert ist eine Adresse erforderlich.'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
res.status(400).send({status: 'BAD_REQUEST', message: e.message});
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
import * as EventsService from '../../calendar/events/events.service';
|
||||||
|
import * as IcalService from '../../calendar/events/icalgenerator.service';
|
||||||
|
import {MailService} from '../../../common/common.mail.nodemailer';
|
||||||
|
import logger from '../../../middleware/logger';
|
||||||
|
import {NachklangTicketsDB} from '../Tickets.db';
|
||||||
|
import {getEventTicketState} from '../tickets.capacity';
|
||||||
|
import {EligibleEvent, RedeemRequest, VoucherValidation} from '../tickets.interface';
|
||||||
|
import {isValidEmail} from '../tickets.validation';
|
||||||
|
|
||||||
|
const formatGermanDateTime = (date: Date): string => {
|
||||||
|
return new Intl.DateTimeFormat('de-DE', {
|
||||||
|
dateStyle: 'full',
|
||||||
|
timeStyle: 'short',
|
||||||
|
timeZone: 'Europe/Berlin'
|
||||||
|
}).format(date);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the eligible-events list for a code: for each event it's linked
|
||||||
|
* to, merges live Calendar event details with the Tickets module's own
|
||||||
|
* capacity/deadline state. Events deleted from the calendar since the code
|
||||||
|
* was generated are silently skipped rather than erroring. DRAFT events are
|
||||||
|
* deliberately still eligible - vouchers are sometimes sent out before a
|
||||||
|
* concert is publicly announced (see docs/plan-ticket-shop.md), so only
|
||||||
|
* DELETED is excluded here, not draft/unpublished status.
|
||||||
|
*/
|
||||||
|
export const validateVoucher = async (code: string): Promise<VoucherValidation | null> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
const voucherRows = await conn.query('SELECT * FROM voucher_codes WHERE code = ?', [code]);
|
||||||
|
if (voucherRows.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const voucher = voucherRows[0];
|
||||||
|
|
||||||
|
const eventIdRows = await conn.query('SELECT event_id FROM voucher_code_events WHERE code = ?', [code]);
|
||||||
|
const eligibleEvents: EligibleEvent[] = [];
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
for (const row of eventIdRows) {
|
||||||
|
const eventId = row.event_id;
|
||||||
|
const event = await EventsService.getEventById(eventId);
|
||||||
|
if (!event || event.status === 'DELETED') continue;
|
||||||
|
|
||||||
|
const ticketState = await getEventTicketState(conn, eventId);
|
||||||
|
eligibleEvents.push({
|
||||||
|
eventId,
|
||||||
|
name: event.name,
|
||||||
|
startDateTime: event.startDateTime,
|
||||||
|
location: event.location,
|
||||||
|
deadlinePassed: ticketState.redemptionDeadline !== null && now > new Date(ticketState.redemptionDeadline),
|
||||||
|
isFull: ticketState.spotsRemaining !== null && ticketState.spotsRemaining <= 0,
|
||||||
|
spotsRemaining: ticketState.spotsRemaining,
|
||||||
|
collectAddress: ticketState.collectAddress,
|
||||||
|
requireAddress: ticketState.requireAddress
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
eligibleEvents.sort((a, b) => a.startDateTime.getTime() - b.startDateTime.getTime());
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: voucher.code,
|
||||||
|
status: voucher.status,
|
||||||
|
maxGuests: voucher.max_guests,
|
||||||
|
prefillName: voucher.prefill_name,
|
||||||
|
prefillEmail: voucher.prefill_email,
|
||||||
|
eligibleEvents
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RedeemResult =
|
||||||
|
| {status: 'OK'; redemptionId: number}
|
||||||
|
| {status: 'NOT_FOUND'}
|
||||||
|
| {status: 'ALREADY_USED'}
|
||||||
|
| {status: 'INVALID_EVENT'}
|
||||||
|
| {status: 'DEADLINE_PASSED'}
|
||||||
|
| {status: 'CAPACITY_EXCEEDED'; spotsRemaining: number}
|
||||||
|
| {status: 'ADDRESS_REQUIRED'};
|
||||||
|
|
||||||
|
export const redeemVoucher = async (code: string, request: RedeemRequest): Promise<RedeemResult> => {
|
||||||
|
if (!request.contactName || !request.contactEmail || !Array.isArray(request.guests) || request.guests.length === 0) {
|
||||||
|
throw new Error('contactName, contactEmail, and at least one guest are required');
|
||||||
|
}
|
||||||
|
if (!isValidEmail(request.contactEmail)) {
|
||||||
|
throw new Error('contactEmail does not look like a valid email address');
|
||||||
|
}
|
||||||
|
for (const guest of request.guests) {
|
||||||
|
if (!guest.name) {
|
||||||
|
throw new Error('every guest requires a name');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
let redemptionId: number;
|
||||||
|
let eventId: number;
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
// Locks the code row so two concurrent requests for the same code
|
||||||
|
// can't both pass the "still UNUSED" check.
|
||||||
|
const voucherRows = await conn.query('SELECT * FROM voucher_codes WHERE code = ? FOR UPDATE', [code]);
|
||||||
|
if (voucherRows.length === 0) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'NOT_FOUND'};
|
||||||
|
}
|
||||||
|
const voucher = voucherRows[0];
|
||||||
|
if (voucher.status !== 'UNUSED') {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'ALREADY_USED'};
|
||||||
|
}
|
||||||
|
|
||||||
|
const eligibleRows = await conn.query('SELECT 1 FROM voucher_code_events WHERE code = ? AND event_id = ?', [code, request.eventId]);
|
||||||
|
if (eligibleRows.length === 0) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'INVALID_EVENT'};
|
||||||
|
}
|
||||||
|
|
||||||
|
// A concert can be canceled/deleted from the calendar after codes were
|
||||||
|
// issued - without this, such a code would stay silently redeemable.
|
||||||
|
// DRAFT is deliberately still allowed (see validateVoucher's comment).
|
||||||
|
const event = await EventsService.getEventById(request.eventId);
|
||||||
|
if (!event || event.status === 'DELETED') {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'INVALID_EVENT'};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.guests.length > voucher.max_guests) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw new Error(`this code allows at most ${voucher.max_guests} guests`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// forUpdate=true serializes concurrent redemptions against this event
|
||||||
|
// so the capacity check below can't race past a hard cap.
|
||||||
|
const ticketState = await getEventTicketState(conn, request.eventId, true);
|
||||||
|
const now = new Date();
|
||||||
|
if (ticketState.redemptionDeadline !== null && now > new Date(ticketState.redemptionDeadline)) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'DEADLINE_PASSED'};
|
||||||
|
}
|
||||||
|
if (ticketState.spotsRemaining !== null && request.guests.length > ticketState.spotsRemaining) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'CAPACITY_EXCEEDED', spotsRemaining: ticketState.spotsRemaining};
|
||||||
|
}
|
||||||
|
if (ticketState.requireAddress && !request.contactAddress?.trim()) {
|
||||||
|
await conn.rollback();
|
||||||
|
return {status: 'ADDRESS_REQUIRED'};
|
||||||
|
}
|
||||||
|
|
||||||
|
const contactAddress = ticketState.collectAddress ? (request.contactAddress || null) : null;
|
||||||
|
|
||||||
|
const redemptionRes = await conn.query(
|
||||||
|
'INSERT INTO redemptions (code, event_id, contact_name, contact_email, contact_address, guest_count) VALUES (?,?,?,?,?,?) RETURNING redemption_id',
|
||||||
|
[code, request.eventId, request.contactName, request.contactEmail, contactAddress, request.guests.length]
|
||||||
|
);
|
||||||
|
redemptionId = redemptionRes[0].redemption_id;
|
||||||
|
eventId = request.eventId;
|
||||||
|
|
||||||
|
for (let i = 0; i < request.guests.length; i++) {
|
||||||
|
await conn.query('INSERT INTO redemption_guests (redemption_id, name, position) VALUES (?,?,?)', [redemptionId, request.guests[i].name, i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.query('UPDATE voucher_codes SET status = ? WHERE code = ?', ['REDEEMED', code]);
|
||||||
|
|
||||||
|
await conn.commit();
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sent after commit, mirroring the Calendar/Feedback convention: a mail
|
||||||
|
// delivery failure shouldn't roll back a successful redemption. Caught
|
||||||
|
// rather than left to propagate - the redemption already succeeded, so
|
||||||
|
// a mail-server hiccup must not turn into a false failure response to
|
||||||
|
// a guest who has, in fact, already secured their spot.
|
||||||
|
try {
|
||||||
|
await sendConfirmationEmail(eventId, request, redemptionId);
|
||||||
|
} catch (e: any) {
|
||||||
|
logger.error('Redemption ' + redemptionId + ' succeeded but confirmation email failed to send: ' + e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {status: 'OK', redemptionId};
|
||||||
|
};
|
||||||
|
|
||||||
|
const sendConfirmationEmail = async (eventId: number, request: RedeemRequest, redemptionId: number): Promise<void> => {
|
||||||
|
const event = await EventsService.getEventById(eventId);
|
||||||
|
if (!event) return;
|
||||||
|
|
||||||
|
const guestList = request.guests.map(g => `- ${g.name}`).join('\n');
|
||||||
|
const body = `Hallo ${request.contactName},\n\n` +
|
||||||
|
`vielen Dank für deine Anmeldung zu "${event.name}"!\n\n` +
|
||||||
|
`Termin: ${formatGermanDateTime(event.startDateTime)}\n` +
|
||||||
|
`Ort: ${event.location}\n\n` +
|
||||||
|
`Angemeldete Gäste:\n${guestList}\n\n` +
|
||||||
|
`Wir freuen uns auf dich!\n\nDein Nachklang-Team`;
|
||||||
|
|
||||||
|
let icsAttachment;
|
||||||
|
try {
|
||||||
|
const ics = await IcalService.convertToIcal([event]);
|
||||||
|
icsAttachment = [{filename: 'konzert.ics', content: ics, contentType: 'text/calendar'}];
|
||||||
|
} catch {
|
||||||
|
icsAttachment = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
await MailService.sendMail(
|
||||||
|
request.contactEmail,
|
||||||
|
`Bestätigung: ${event.name}`,
|
||||||
|
body,
|
||||||
|
{attachments: icsAttachment}
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import * as UserService from '../calendar/users/users.service';
|
||||||
|
import {sendServerError} from './tickets.errors';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors the Feedback module's feedback.auth.ts: this is the ONLY place in
|
||||||
|
* the tickets module that knows how admin authentication works. No route
|
||||||
|
* handler and no service outside this file may import users.service, read
|
||||||
|
* session headers, or touch bcrypt.
|
||||||
|
*
|
||||||
|
* Today: reuses the existing Calendar users/sessions mechanism. Any
|
||||||
|
* activated @nachklang.art account may administer vouchers - no roles, same
|
||||||
|
* policy as Feedback (see docs/plan-ticket-shop.md). A dedicated
|
||||||
|
* roles/permissions model is explicitly out of scope for v1.
|
||||||
|
*
|
||||||
|
* Explicitly forbidden: accepting sessionId/sessionKey from query
|
||||||
|
* parameters - headers only (see DEFERRED_SECURITY.md item 1).
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface AdminIdentity {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
displayName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AdminAuthenticator = (req: express.Request) => Promise<AdminIdentity | null>;
|
||||||
|
|
||||||
|
export const sessionHeaderAuthenticator: AdminAuthenticator = async (req) => {
|
||||||
|
const sessionId = req.header('X-Session-Id');
|
||||||
|
const sessionKey = req.header('X-Session-Key');
|
||||||
|
if (!sessionId || !sessionKey) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ip = req.ip || '';
|
||||||
|
const user = await UserService.checkSession(sessionId, sessionKey, ip);
|
||||||
|
|
||||||
|
if (!user || !user.isActive) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: String(user.userId),
|
||||||
|
email: user.email,
|
||||||
|
displayName: user.fullName
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const activeAuthenticator: AdminAuthenticator = sessionHeaderAuthenticator;
|
||||||
|
|
||||||
|
export const requireAdminAuth: express.RequestHandler = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const identity = await activeAuthenticator(req);
|
||||||
|
if (!identity) {
|
||||||
|
res.status(401).send({status: 'UNAUTHORIZED', message: 'Anmeldung erforderlich.'});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.locals.admin = identity;
|
||||||
|
next();
|
||||||
|
} catch (e: any) {
|
||||||
|
sendServerError(res, e);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
export interface EventTicketState {
|
||||||
|
eventId: number;
|
||||||
|
capacity: number | null;
|
||||||
|
redemptionDeadline: Date | null;
|
||||||
|
collectAddress: boolean;
|
||||||
|
requireAddress: boolean;
|
||||||
|
guestsUsed: number;
|
||||||
|
spotsRemaining: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads an event's voucher settings + live guest count within the caller's
|
||||||
|
* connection/transaction. Absence of a settings row means uncapped/no
|
||||||
|
* deadline/no address collection - the "absence over sentinels" convention
|
||||||
|
* also used by the Feedback module.
|
||||||
|
*
|
||||||
|
* Pass forUpdate=true from inside the redeem transaction to lock the
|
||||||
|
* settings row for the duration of that transaction, serializing concurrent
|
||||||
|
* redemptions against the same event so the guestsUsed sum computed here
|
||||||
|
* stays correct even under a last-spot race. Events with no settings row
|
||||||
|
* (uncapped) don't need this - there's no cap to race against.
|
||||||
|
*/
|
||||||
|
export const getEventTicketState = async (conn: any, eventId: number, forUpdate = false): Promise<EventTicketState> => {
|
||||||
|
const settingsQuery = `SELECT capacity, redemption_deadline, collect_address, require_address FROM event_ticket_settings WHERE event_id = ?${forUpdate ? ' FOR UPDATE' : ''}`;
|
||||||
|
const settingsRows = await conn.query(settingsQuery, [eventId]);
|
||||||
|
const capacity = settingsRows.length > 0 ? settingsRows[0].capacity : null;
|
||||||
|
const redemptionDeadline = settingsRows.length > 0 ? settingsRows[0].redemption_deadline : null;
|
||||||
|
const collectAddress = settingsRows.length > 0 ? !!settingsRows[0].collect_address : false;
|
||||||
|
// Only meaningful when collectAddress is also true - the field isn't
|
||||||
|
// shown/collected at all otherwise, so "required" is moot.
|
||||||
|
const requireAddress = collectAddress && settingsRows.length > 0 ? !!settingsRows[0].require_address : false;
|
||||||
|
|
||||||
|
const usedRows = await conn.query(
|
||||||
|
"SELECT COALESCE(SUM(guest_count), 0) as used FROM redemptions WHERE event_id = ? AND status = 'ACTIVE'",
|
||||||
|
[eventId]
|
||||||
|
);
|
||||||
|
const guestsUsed = Number(usedRows[0].used);
|
||||||
|
const spotsRemaining = capacity === null ? null : Math.max(0, capacity - guestsUsed);
|
||||||
|
|
||||||
|
return {eventId, capacity, redemptionDeadline, collectAddress, requireAddress, guestsUsed, spotsRemaining};
|
||||||
|
};
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import * as crypto from 'crypto';
|
||||||
|
|
||||||
|
// Excludes 0/O, 1/I/L to avoid look-alike confusion when a code is
|
||||||
|
// hand-written, read aloud, or typed from a printed fallback under a QR
|
||||||
|
// code. 31 symbols * 8 chars ≈ 39.6 bits of entropy - effectively
|
||||||
|
// unguessable combined with rate-limiting on the redeem endpoint.
|
||||||
|
const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
|
||||||
|
const CODE_LENGTH = 8;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a single random code. Uses crypto.randomInt (uniform, no
|
||||||
|
* modulo bias) rather than Math.random() since these gate a real-world
|
||||||
|
* concert invitation.
|
||||||
|
*/
|
||||||
|
export const generateCode = (): string => {
|
||||||
|
let code = '';
|
||||||
|
for (let i = 0; i < CODE_LENGTH; i++) {
|
||||||
|
code += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a code guaranteed not to collide with any row `existingCodes`
|
||||||
|
* already contains, tries up to `maxAttempts` times before giving up.
|
||||||
|
* Collisions are astronomically unlikely at this entropy - this exists as
|
||||||
|
* a correctness backstop, not because collisions are expected.
|
||||||
|
*/
|
||||||
|
export const generateUniqueCode = (existingCodes: Set<string>, maxAttempts = 20): string => {
|
||||||
|
for (let i = 0; i < maxAttempts; i++) {
|
||||||
|
const candidate = generateCode();
|
||||||
|
if (!existingCodes.has(candidate)) {
|
||||||
|
existingCodes.add(candidate);
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error('Could not generate a unique voucher code after ' + maxAttempts + ' attempts');
|
||||||
|
};
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import {Response} from 'express';
|
||||||
|
import {Guid} from 'guid-typescript';
|
||||||
|
import logger from '../../middleware/logger';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The tickets module's standard catch-block response: log with a reference
|
||||||
|
* guid, never leak the real error message to the client. Mirrors the
|
||||||
|
* Feedback module's feedback.errors.ts convention.
|
||||||
|
*/
|
||||||
|
export const sendServerError = (res: Response, e: any): void => {
|
||||||
|
const errorGuid = Guid.create().toString();
|
||||||
|
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
||||||
|
res.status(500).send({
|
||||||
|
status: 'PROCESSING_ERROR',
|
||||||
|
message: 'Internal Server Error. Try again later.',
|
||||||
|
reference: errorGuid
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* components:
|
||||||
|
* schemas:
|
||||||
|
* VoucherStatus:
|
||||||
|
* type: string
|
||||||
|
* enum: [UNUSED, REDEEMED, VOID]
|
||||||
|
* RedemptionStatus:
|
||||||
|
* type: string
|
||||||
|
* enum: [ACTIVE, UNDONE]
|
||||||
|
* EligibleEvent:
|
||||||
|
* type: object
|
||||||
|
* required: [eventId, name, startDateTime, location, deadlinePassed, isFull, collectAddress, requireAddress]
|
||||||
|
* properties:
|
||||||
|
* eventId:
|
||||||
|
* type: integer
|
||||||
|
* example: 42
|
||||||
|
* name:
|
||||||
|
* type: string
|
||||||
|
* example: "Adventskonzert 2026"
|
||||||
|
* startDateTime:
|
||||||
|
* type: string
|
||||||
|
* format: date-time
|
||||||
|
* location:
|
||||||
|
* type: string
|
||||||
|
* deadlinePassed:
|
||||||
|
* type: boolean
|
||||||
|
* isFull:
|
||||||
|
* type: boolean
|
||||||
|
* spotsRemaining:
|
||||||
|
* type: integer
|
||||||
|
* nullable: true
|
||||||
|
* description: null when the event has no capacity cap set (uncapped)
|
||||||
|
* collectAddress:
|
||||||
|
* type: boolean
|
||||||
|
* requireAddress:
|
||||||
|
* type: boolean
|
||||||
|
* VoucherValidation:
|
||||||
|
* type: object
|
||||||
|
* required: [code, status, maxGuests, eligibleEvents]
|
||||||
|
* properties:
|
||||||
|
* code:
|
||||||
|
* type: string
|
||||||
|
* example: "K7F3M9QX"
|
||||||
|
* status:
|
||||||
|
* $ref: '#/components/schemas/VoucherStatus'
|
||||||
|
* maxGuests:
|
||||||
|
* type: integer
|
||||||
|
* example: 2
|
||||||
|
* prefillName:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* prefillEmail:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* eligibleEvents:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* $ref: '#/components/schemas/EligibleEvent'
|
||||||
|
* RedeemGuest:
|
||||||
|
* type: object
|
||||||
|
* required: [name]
|
||||||
|
* properties:
|
||||||
|
* name:
|
||||||
|
* type: string
|
||||||
|
* example: "Erika Mustermann"
|
||||||
|
* RedeemRequest:
|
||||||
|
* type: object
|
||||||
|
* required: [eventId, contactName, contactEmail, guests]
|
||||||
|
* properties:
|
||||||
|
* eventId:
|
||||||
|
* type: integer
|
||||||
|
* contactName:
|
||||||
|
* type: string
|
||||||
|
* contactEmail:
|
||||||
|
* type: string
|
||||||
|
* contactAddress:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* guests:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* $ref: '#/components/schemas/RedeemGuest'
|
||||||
|
* RedemptionSummary:
|
||||||
|
* type: object
|
||||||
|
* required: [redemptionId, code, eventId, status, contactName, contactEmail, guestCount, guests, redeemedAt]
|
||||||
|
* properties:
|
||||||
|
* redemptionId:
|
||||||
|
* type: integer
|
||||||
|
* code:
|
||||||
|
* type: string
|
||||||
|
* eventId:
|
||||||
|
* type: integer
|
||||||
|
* status:
|
||||||
|
* $ref: '#/components/schemas/RedemptionStatus'
|
||||||
|
* contactName:
|
||||||
|
* type: string
|
||||||
|
* contactEmail:
|
||||||
|
* type: string
|
||||||
|
* contactAddress:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* guestCount:
|
||||||
|
* type: integer
|
||||||
|
* guests:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* type: string
|
||||||
|
* redeemedAt:
|
||||||
|
* type: string
|
||||||
|
* format: date-time
|
||||||
|
* VoucherCode:
|
||||||
|
* type: object
|
||||||
|
* required: [code, status, maxGuests, createdByEmail, createdAt, eligibleEventIds]
|
||||||
|
* properties:
|
||||||
|
* code:
|
||||||
|
* type: string
|
||||||
|
* status:
|
||||||
|
* $ref: '#/components/schemas/VoucherStatus'
|
||||||
|
* maxGuests:
|
||||||
|
* type: integer
|
||||||
|
* prefillName:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* prefillEmail:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* batchId:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* createdByEmail:
|
||||||
|
* type: string
|
||||||
|
* createdAt:
|
||||||
|
* type: string
|
||||||
|
* format: date-time
|
||||||
|
* eligibleEventIds:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* type: integer
|
||||||
|
* EventTicketSettings:
|
||||||
|
* type: object
|
||||||
|
* required: [eventId, collectAddress, requireAddress]
|
||||||
|
* properties:
|
||||||
|
* eventId:
|
||||||
|
* type: integer
|
||||||
|
* capacity:
|
||||||
|
* type: integer
|
||||||
|
* nullable: true
|
||||||
|
* redemptionDeadline:
|
||||||
|
* type: string
|
||||||
|
* format: date-time
|
||||||
|
* nullable: true
|
||||||
|
* collectAddress:
|
||||||
|
* type: boolean
|
||||||
|
* requireAddress:
|
||||||
|
* type: boolean
|
||||||
|
* description: Only meaningful when collectAddress is true.
|
||||||
|
* EventStats:
|
||||||
|
* type: object
|
||||||
|
* required: [eventId, collectAddress, requireAddress, guestsUsed, unusedCodes, redeemedCodes, voidCodes]
|
||||||
|
* properties:
|
||||||
|
* eventId:
|
||||||
|
* type: integer
|
||||||
|
* capacity:
|
||||||
|
* type: integer
|
||||||
|
* nullable: true
|
||||||
|
* redemptionDeadline:
|
||||||
|
* type: string
|
||||||
|
* format: date-time
|
||||||
|
* nullable: true
|
||||||
|
* collectAddress:
|
||||||
|
* type: boolean
|
||||||
|
* requireAddress:
|
||||||
|
* type: boolean
|
||||||
|
* guestsUsed:
|
||||||
|
* type: integer
|
||||||
|
* spotsRemaining:
|
||||||
|
* type: integer
|
||||||
|
* nullable: true
|
||||||
|
* unusedCodes:
|
||||||
|
* type: integer
|
||||||
|
* redeemedCodes:
|
||||||
|
* type: integer
|
||||||
|
* voidCodes:
|
||||||
|
* type: integer
|
||||||
|
* AuditLogEntry:
|
||||||
|
* type: object
|
||||||
|
* required: [auditId, code, adminEmail, action, createdAt]
|
||||||
|
* properties:
|
||||||
|
* auditId:
|
||||||
|
* type: integer
|
||||||
|
* code:
|
||||||
|
* type: string
|
||||||
|
* redemptionId:
|
||||||
|
* type: integer
|
||||||
|
* nullable: true
|
||||||
|
* adminEmail:
|
||||||
|
* type: string
|
||||||
|
* action:
|
||||||
|
* type: string
|
||||||
|
* enum: [EDIT, VOID, UNDO]
|
||||||
|
* changeSummary:
|
||||||
|
* type: object
|
||||||
|
* nullable: true
|
||||||
|
* reason:
|
||||||
|
* type: string
|
||||||
|
* nullable: true
|
||||||
|
* createdAt:
|
||||||
|
* type: string
|
||||||
|
* format: date-time
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type VoucherStatus = 'UNUSED' | 'REDEEMED' | 'VOID';
|
||||||
|
export type RedemptionStatus = 'ACTIVE' | 'UNDONE';
|
||||||
|
export type AuditAction = 'EDIT' | 'VOID' | 'UNDO';
|
||||||
|
|
||||||
|
export interface EligibleEvent {
|
||||||
|
eventId: number;
|
||||||
|
name: string;
|
||||||
|
startDateTime: Date;
|
||||||
|
location: string;
|
||||||
|
deadlinePassed: boolean;
|
||||||
|
isFull: boolean;
|
||||||
|
spotsRemaining: number | null;
|
||||||
|
collectAddress: boolean;
|
||||||
|
requireAddress: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VoucherValidation {
|
||||||
|
code: string;
|
||||||
|
status: VoucherStatus;
|
||||||
|
maxGuests: number;
|
||||||
|
prefillName: string | null;
|
||||||
|
prefillEmail: string | null;
|
||||||
|
eligibleEvents: EligibleEvent[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RedeemGuest {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RedeemRequest {
|
||||||
|
eventId: number;
|
||||||
|
contactName: string;
|
||||||
|
contactEmail: string;
|
||||||
|
contactAddress?: string | null;
|
||||||
|
guests: RedeemGuest[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RedemptionSummary {
|
||||||
|
redemptionId: number;
|
||||||
|
code: string;
|
||||||
|
eventId: number;
|
||||||
|
status: RedemptionStatus;
|
||||||
|
contactName: string;
|
||||||
|
contactEmail: string;
|
||||||
|
contactAddress: string | null;
|
||||||
|
guestCount: number;
|
||||||
|
guests: string[];
|
||||||
|
redeemedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VoucherCode {
|
||||||
|
code: string;
|
||||||
|
status: VoucherStatus;
|
||||||
|
maxGuests: number;
|
||||||
|
prefillName: string | null;
|
||||||
|
prefillEmail: string | null;
|
||||||
|
batchId: string | null;
|
||||||
|
createdByEmail: string;
|
||||||
|
createdAt: Date;
|
||||||
|
eligibleEventIds: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EventTicketSettings {
|
||||||
|
eventId: number;
|
||||||
|
capacity: number | null;
|
||||||
|
redemptionDeadline: Date | null;
|
||||||
|
collectAddress: boolean;
|
||||||
|
requireAddress: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EventStats extends EventTicketSettings {
|
||||||
|
guestsUsed: number;
|
||||||
|
spotsRemaining: number | null;
|
||||||
|
unusedCodes: number;
|
||||||
|
redeemedCodes: number;
|
||||||
|
voidCodes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuditLogEntry {
|
||||||
|
auditId: number;
|
||||||
|
code: string;
|
||||||
|
redemptionId: number | null;
|
||||||
|
adminEmail: string;
|
||||||
|
action: AuditAction;
|
||||||
|
changeSummary: Record<string, unknown> | null;
|
||||||
|
reason: string | null;
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import * as crypto from 'crypto';
|
||||||
|
import * as dotenv from 'dotenv';
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const RATE_LIMIT_WINDOW_MIN = parseInt(process.env.TICKETS_RATE_LIMIT_WINDOW_MIN || '10', 10);
|
||||||
|
const RATE_LIMIT_WINDOW_MS = RATE_LIMIT_WINDOW_MIN * 60 * 1000;
|
||||||
|
|
||||||
|
// Salted per-process (not persisted/configured) - these limiters are
|
||||||
|
// in-memory-only with no DB backstop, so the salt only needs to survive
|
||||||
|
// for the current process's lifetime, unlike Feedback's FEEDBACK_IP_SALT
|
||||||
|
// which also salts a persisted ip_hash column.
|
||||||
|
const IP_SALT = crypto.randomBytes(32).toString('hex');
|
||||||
|
|
||||||
|
export const hashIp = (ip: string): string => {
|
||||||
|
return crypto.createHash('sha256').update(IP_SALT + ip).digest('hex');
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Two independent budgets, not one shared counter: validating a code (GET)
|
||||||
|
* is a cheap, repeatable lookup a guest's own browser triggers on every
|
||||||
|
* page load/reload/back-navigation of their redemption link - a shared
|
||||||
|
* budget with redeem meant a guest could exhaust it just by reloading the
|
||||||
|
* page a few times before ever submitting. Redeeming (POST) is the
|
||||||
|
* sensitive, code-consuming action and stays tightly limited; validating
|
||||||
|
* is limited too (it's still the enumeration vector for guessing codes),
|
||||||
|
* just with a much larger allowance headroomed for normal page-reload
|
||||||
|
* behaviour.
|
||||||
|
*/
|
||||||
|
const createLimiter = (max: number) => {
|
||||||
|
const recentRequests = new Map<string, number[]>();
|
||||||
|
|
||||||
|
const pruneOld = (timestamps: number[], now: number): number[] => {
|
||||||
|
return timestamps.filter(t => now - t < RATE_LIMIT_WINDOW_MS);
|
||||||
|
};
|
||||||
|
|
||||||
|
const sweepInterval = setInterval(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [ipHash, timestamps] of recentRequests) {
|
||||||
|
if (pruneOld(timestamps, now).length === 0) {
|
||||||
|
recentRequests.delete(ipHash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, RATE_LIMIT_WINDOW_MS);
|
||||||
|
sweepInterval.unref();
|
||||||
|
|
||||||
|
return {
|
||||||
|
isRateLimited: (ipHash: string): boolean => {
|
||||||
|
const now = Date.now();
|
||||||
|
const timestamps = pruneOld(recentRequests.get(ipHash) || [], now);
|
||||||
|
if (timestamps.length > 0) {
|
||||||
|
recentRequests.set(ipHash, timestamps);
|
||||||
|
} else {
|
||||||
|
recentRequests.delete(ipHash);
|
||||||
|
}
|
||||||
|
return timestamps.length >= max;
|
||||||
|
},
|
||||||
|
recordRequest: (ipHash: string): void => {
|
||||||
|
const now = Date.now();
|
||||||
|
const timestamps = pruneOld(recentRequests.get(ipHash) || [], now);
|
||||||
|
timestamps.push(now);
|
||||||
|
recentRequests.set(ipHash, timestamps);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const validateLimiter = createLimiter(parseInt(process.env.TICKETS_VALIDATE_RATE_LIMIT_MAX || '30', 10));
|
||||||
|
export const redeemLimiter = createLimiter(parseInt(process.env.TICKETS_REDEEM_RATE_LIMIT_MAX || '10', 10));
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Intentionally permissive - "looks like an email" (something@something.tld),
|
||||||
|
// not full RFC 5322 validation. Good enough to catch typos without rejecting
|
||||||
|
// real addresses RFC 5322 edge cases would.
|
||||||
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
|
export const isValidEmail = (email: string): boolean => EMAIL_REGEX.test(email.trim());
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import {escapeCsvField, formatDatetime} from '../../src/models/feedback/admin/csv.service';
|
import {escapeCsvField} from '../../src/models/feedback/admin/csv.service';
|
||||||
|
import {formatDatetime} from '../../src/models/feedback/feedback.dates';
|
||||||
|
|
||||||
describe('escapeCsvField', () => {
|
describe('escapeCsvField', () => {
|
||||||
it('passes plain text through unchanged', () => {
|
it('passes plain text through unchanged', () => {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import {aggregateReport} from '../../src/models/feedback/admin/reports.admin.ser
|
|||||||
import {AnswerRow} from '../../src/models/feedback/admin/reports.admin.interface';
|
import {AnswerRow} from '../../src/models/feedback/admin/reports.admin.interface';
|
||||||
|
|
||||||
const eventMeta = {eventId: 1, name: 'Sommerkonzert', eventDate: '2026-08-01', feedbackDeadline: '2026-08-15T23:59:59'};
|
const eventMeta = {eventId: 1, name: 'Sommerkonzert', eventDate: '2026-08-01', feedbackDeadline: '2026-08-15T23:59:59'};
|
||||||
const emptyNewsletter = {total: 0, sent: 0, pending: 0, failed: 0};
|
const emptyNewsletter = {total: 0, sent: 0, pending: 0, failed: 0, skipped: 0};
|
||||||
|
|
||||||
const row = (overrides: Partial<AnswerRow>): AnswerRow => ({
|
const row = (overrides: Partial<AnswerRow>): AnswerRow => ({
|
||||||
submissionId: 1,
|
submissionId: 1,
|
||||||
@@ -90,13 +90,13 @@ describe('aggregateReport - top-level fields', () => {
|
|||||||
{totalSubmissions: 42, firstSubmissionAt: '2026-08-02T10:00:00.000Z', lastSubmissionAt: '2026-08-10T18:00:00.000Z'},
|
{totalSubmissions: 42, firstSubmissionAt: '2026-08-02T10:00:00.000Z', lastSubmissionAt: '2026-08-10T18:00:00.000Z'},
|
||||||
[],
|
[],
|
||||||
7,
|
7,
|
||||||
{total: 10, sent: 6, pending: 2, failed: 2}
|
{total: 10, sent: 6, pending: 2, failed: 1, skipped: 1}
|
||||||
);
|
);
|
||||||
expect(report.totalSubmissions).toBe(42);
|
expect(report.totalSubmissions).toBe(42);
|
||||||
expect(report.firstSubmissionAt).toBe('2026-08-02T10:00:00.000Z');
|
expect(report.firstSubmissionAt).toBe('2026-08-02T10:00:00.000Z');
|
||||||
expect(report.lastSubmissionAt).toBe('2026-08-10T18:00:00.000Z');
|
expect(report.lastSubmissionAt).toBe('2026-08-10T18:00:00.000Z');
|
||||||
expect(report.guestBookCount).toBe(7);
|
expect(report.guestBookCount).toBe(7);
|
||||||
expect(report.newsletter).toEqual({total: 10, sent: 6, pending: 2, failed: 2});
|
expect(report.newsletter).toEqual({total: 10, sent: 6, pending: 2, failed: 1, skipped: 1});
|
||||||
expect(report.event).toEqual(eventMeta);
|
expect(report.event).toEqual(eventMeta);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,198 @@
|
|||||||
|
// The module under test caches its OAuth token at module scope (see
|
||||||
|
// salesforce.service.ts's `cachedToken`), so every test resets the module
|
||||||
|
// registry for a clean cache. That also invalidates any jest.mock() factory
|
||||||
|
// instance captured before the reset, so every mocked dependency (axios,
|
||||||
|
// Feedback.db, the logger) is re-required fresh after each reset rather
|
||||||
|
// than referenced from a top-level import.
|
||||||
|
|
||||||
|
jest.mock('axios');
|
||||||
|
jest.mock('../../src/models/feedback/Feedback.db', () => ({
|
||||||
|
NachklangFeedbackDB: {getConnection: jest.fn()}
|
||||||
|
}));
|
||||||
|
jest.mock('../../src/middleware/logger', () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: {info: jest.fn(), error: jest.fn()}
|
||||||
|
}));
|
||||||
|
|
||||||
|
const SIGNUP_ROW = {
|
||||||
|
signup_id: 7,
|
||||||
|
first_name: 'Erika',
|
||||||
|
last_name: 'Mustermann',
|
||||||
|
email: 'erika@example.com',
|
||||||
|
event_name: 'Sommerkonzert 2026'
|
||||||
|
};
|
||||||
|
|
||||||
|
const makeConn = (rows: any[]) => ({
|
||||||
|
query: jest.fn().mockResolvedValue(rows),
|
||||||
|
end: jest.fn().mockResolvedValue(undefined)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Re-requires every mocked dependency fresh (see the note above) and
|
||||||
|
// returns the live references plus the service under test.
|
||||||
|
const freshImports = () => {
|
||||||
|
const axios = require('axios');
|
||||||
|
const {NachklangFeedbackDB} = require('../../src/models/feedback/Feedback.db');
|
||||||
|
const logger = require('../../src/middleware/logger').default;
|
||||||
|
const {syncNewsletterSignup} = require('../../src/models/feedback/integrations/salesforce.service');
|
||||||
|
return {axios, mockGetConnection: NachklangFeedbackDB.getConnection as jest.Mock, logger, syncNewsletterSignup};
|
||||||
|
};
|
||||||
|
|
||||||
|
const ORIGINAL_ENV = {...process.env};
|
||||||
|
|
||||||
|
describe('syncNewsletterSignup - disabled mode', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.resetModules();
|
||||||
|
process.env = {...ORIGINAL_ENV, SALESFORCE_ENABLED: 'false'};
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs the payload it would send and does not touch the network or write to the DB', async () => {
|
||||||
|
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
|
||||||
|
const conn = makeConn([SIGNUP_ROW]);
|
||||||
|
mockGetConnection.mockResolvedValue(conn);
|
||||||
|
|
||||||
|
await syncNewsletterSignup(7);
|
||||||
|
|
||||||
|
expect(logger.info).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('would have sent'),
|
||||||
|
expect.objectContaining({
|
||||||
|
signupId: 7,
|
||||||
|
payload: {firstName: 'Erika', lastName: 'Mustermann', email: 'erika@example.com', eventName: 'Sommerkonzert 2026'}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(axios.post).not.toHaveBeenCalled();
|
||||||
|
// One read connection only - no UPDATE issued, since the row's
|
||||||
|
// sync_status is already 'SKIPPED' from the insert.
|
||||||
|
expect(mockGetConnection).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs and returns without calling the network when the signup row does not exist', async () => {
|
||||||
|
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
|
||||||
|
mockGetConnection.mockResolvedValue(makeConn([]));
|
||||||
|
|
||||||
|
await syncNewsletterSignup(999);
|
||||||
|
|
||||||
|
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('not found'), {signupId: 999});
|
||||||
|
expect(axios.post).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('syncNewsletterSignup - enabled mode', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.resetModules();
|
||||||
|
process.env = {
|
||||||
|
...ORIGINAL_ENV,
|
||||||
|
SALESFORCE_ENABLED: 'true',
|
||||||
|
SALESFORCE_API_URL: 'https://example.my.salesforce.com',
|
||||||
|
SALESFORCE_CLIENT_ID: 'client-id',
|
||||||
|
SALESFORCE_CLIENT_SECRET: 'client-secret'
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches a token, posts the signup, and marks the row SENT with the returned record id', async () => {
|
||||||
|
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
|
||||||
|
const updateConn = makeConn([]);
|
||||||
|
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
||||||
|
axios.post.mockImplementation((url: string) => {
|
||||||
|
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
|
||||||
|
if (url.endsWith('/services/apexrest/newsletter/signup')) {
|
||||||
|
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q1234', created: true}});
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected url ${url}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
await syncNewsletterSignup(7);
|
||||||
|
|
||||||
|
expect(axios.post).toHaveBeenCalledWith(
|
||||||
|
'https://example.my.salesforce.com/services/oauth2/token',
|
||||||
|
expect.any(String),
|
||||||
|
expect.objectContaining({headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
|
||||||
|
);
|
||||||
|
expect(axios.post).toHaveBeenCalledWith(
|
||||||
|
'https://example.my.salesforce.com/services/apexrest/newsletter/signup',
|
||||||
|
{firstName: 'Erika', lastName: 'Mustermann', email: 'erika@example.com', eventName: 'Sommerkonzert 2026'},
|
||||||
|
expect.objectContaining({headers: {Authorization: 'Bearer tok-1'}})
|
||||||
|
);
|
||||||
|
expect(updateConn.query).toHaveBeenCalledWith(expect.stringContaining("sync_status = 'SENT'"), ['00Q1234', 7]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reuses the cached token across two calls instead of fetching twice', async () => {
|
||||||
|
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
|
||||||
|
mockGetConnection
|
||||||
|
.mockResolvedValueOnce(makeConn([SIGNUP_ROW]))
|
||||||
|
.mockResolvedValueOnce(makeConn([]))
|
||||||
|
.mockResolvedValueOnce(makeConn([SIGNUP_ROW]))
|
||||||
|
.mockResolvedValueOnce(makeConn([]));
|
||||||
|
axios.post.mockImplementation((url: string) => {
|
||||||
|
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
|
||||||
|
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q1234', created: true}});
|
||||||
|
});
|
||||||
|
|
||||||
|
await syncNewsletterSignup(7);
|
||||||
|
await syncNewsletterSignup(7);
|
||||||
|
|
||||||
|
const tokenCalls = axios.post.mock.calls.filter(([url]: [string]) => url.endsWith('/services/oauth2/token'));
|
||||||
|
expect(tokenCalls).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries once with a fresh token on a 401, then succeeds', async () => {
|
||||||
|
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
|
||||||
|
const updateConn = makeConn([]);
|
||||||
|
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
||||||
|
|
||||||
|
let tokenFetches = 0;
|
||||||
|
axios.post.mockImplementation((url: string) => {
|
||||||
|
if (url.endsWith('/services/oauth2/token')) {
|
||||||
|
tokenFetches += 1;
|
||||||
|
return Promise.resolve({data: {access_token: `tok-${tokenFetches}`}});
|
||||||
|
}
|
||||||
|
if (url.endsWith('/services/apexrest/newsletter/signup')) {
|
||||||
|
if (tokenFetches === 1) {
|
||||||
|
const err: any = new Error('Unauthorized');
|
||||||
|
err.response = {status: 401, data: {message: 'Session expired'}};
|
||||||
|
return Promise.reject(err);
|
||||||
|
}
|
||||||
|
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q9999', created: true}});
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected url ${url}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
await syncNewsletterSignup(7);
|
||||||
|
|
||||||
|
expect(tokenFetches).toBe(2);
|
||||||
|
expect(updateConn.query).toHaveBeenCalledWith(expect.stringContaining("sync_status = 'SENT'"), ['00Q9999', 7]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks the row FAILED with the error message on a non-401 error, without throwing', async () => {
|
||||||
|
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
|
||||||
|
const updateConn = makeConn([]);
|
||||||
|
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
||||||
|
axios.post.mockImplementation((url: string) => {
|
||||||
|
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
|
||||||
|
const err: any = new Error('Internal error');
|
||||||
|
err.response = {status: 500, data: {message: 'The newsletter signup could not be processed.'}};
|
||||||
|
return Promise.reject(err);
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(syncNewsletterSignup(7)).resolves.toBeUndefined();
|
||||||
|
|
||||||
|
expect(updateConn.query).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining("sync_status = 'FAILED'"),
|
||||||
|
['The newsletter signup could not be processed.', 7]
|
||||||
|
);
|
||||||
|
expect(logger.error).toHaveBeenCalledWith('syncNewsletterSignup failed', expect.objectContaining({signupId: 7}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks the row FAILED with a clear message when client credentials are not configured', async () => {
|
||||||
|
process.env.SALESFORCE_CLIENT_ID = '';
|
||||||
|
const {mockGetConnection, syncNewsletterSignup} = freshImports();
|
||||||
|
const updateConn = makeConn([]);
|
||||||
|
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
||||||
|
|
||||||
|
await syncNewsletterSignup(7);
|
||||||
|
|
||||||
|
expect(updateConn.query).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining("sync_status = 'FAILED'"),
|
||||||
|
[expect.stringContaining('SALESFORCE_CLIENT_ID'), 7]
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user