Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
1de0cc6940
|
|||
|
b6499eb7b3
|
@@ -1,5 +1,3 @@
|
|||||||
# Values containing #, ", \ or surrounding spaces must be single-quoted
|
|
||||||
# (dotenv 16 treats an unquoted # as a comment): DB_PASSWORD='abc#def'
|
|
||||||
PORT=3000
|
PORT=3000
|
||||||
|
|
||||||
DB_HOST=
|
DB_HOST=
|
||||||
|
|||||||
@@ -8,13 +8,12 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
npm run build # Compile TypeScript → dist/
|
npm run build # Compile TypeScript → dist/
|
||||||
npm run start # Build and start (tsc && node ./dist/app.js)
|
npm run start # Build and start (tsc && node ./dist/app.js)
|
||||||
npm run debug # Start with DEBUG=* environment variable
|
npm run debug # Start with DEBUG=* environment variable
|
||||||
npm run test # Run the vitest suite once with coverage (lcov + testResults/sonar-report.xml)
|
npm run test # Run Jest tests with coverage (outputs sonar-report.xml)
|
||||||
npm run test:watch # vitest in watch mode
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Run a single test file:
|
Run a single test file:
|
||||||
```bash
|
```bash
|
||||||
npx vitest run test/some.test.ts
|
npx jest test/some.test.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
@@ -47,11 +46,6 @@ Express.js REST API in TypeScript with a service-oriented layering. Domains: `Ca
|
|||||||
|
|
||||||
## Environment
|
## Environment
|
||||||
|
|
||||||
dotenv 16 parses `.env` stricter than the old dotenv 8: an unquoted `#` starts a comment and
|
|
||||||
backslash escapes inside double quotes are expanded. Wrap any value containing `#`, `"`, `\` or
|
|
||||||
surrounding spaces in single quotes (`DB_PASSWORD='abc#def'`), which are taken literally.
|
|
||||||
A truncated password shows up as MariaDB "Access denied ... (using password: YES)".
|
|
||||||
|
|
||||||
Copy `.env.example` (or create `.env`) with:
|
Copy `.env.example` (or create `.env`) with:
|
||||||
```
|
```
|
||||||
PORT=
|
PORT=
|
||||||
@@ -75,10 +69,6 @@ CHOIR_CREDENTIAL=
|
|||||||
MANAGEMENT_CREDENTIAL=
|
MANAGEMENT_CREDENTIAL=
|
||||||
```
|
```
|
||||||
|
|
||||||
## TypeScript / module system
|
## TypeScript config
|
||||||
|
|
||||||
The API runs on Node 26 (`engines` in package.json, `.nvmrc`; Plesk runs 26 too) and is native ESM (`"type": "module"`, `module: nodenext`, target ES2024, strict mode, compiled output in `./dist`, inline source maps). Consequences:
|
Strict mode enabled, target ES2016, compiled output in `./dist`, inline source maps. Tests run through `ts-jest` directly against `.ts` sources.
|
||||||
|
|
||||||
- Relative imports carry the `.js` suffix (`import {x} from "./x.js"`) even though the source file is `.ts`.
|
|
||||||
- CommonJS dependencies are consumed via default imports (`import mariadb from "mariadb"`, `import cors from "cors"`, `import winston from "winston"`), never `require()`.
|
|
||||||
- Tests run with vitest directly against `.ts` sources; import `describe`/`it`/`expect`/`vi` from `vitest` explicitly (no globals). Module mocks use `vi.mock(...)` with the same `.js`-suffixed paths as the imports.
|
|
||||||
|
|||||||
@@ -3,15 +3,16 @@ import * as http from 'http';
|
|||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import swaggerUi from 'swagger-ui-express';
|
import swaggerUi from 'swagger-ui-express';
|
||||||
import swaggerJSDoc from 'swagger-jsdoc';
|
import swaggerJSDoc from 'swagger-jsdoc';
|
||||||
import cors from 'cors';
|
import logger from './src/middleware/logger';
|
||||||
import logger from './src/middleware/logger.js';
|
|
||||||
|
|
||||||
// Router imports
|
// Router imports
|
||||||
import {calendarRouter} from './src/models/calendar/Calendar.router.js';
|
import {calendarRouter} from './src/models/calendar/Calendar.router';
|
||||||
import {feedbackRouter} from './src/models/feedback/Feedback.router.js';
|
import {feedbackRouter} from './src/models/feedback/Feedback.router';
|
||||||
import {ticketsRouter} from './src/models/tickets/Tickets.router.js';
|
import {ticketsRouter} from './src/models/tickets/Tickets.router';
|
||||||
|
|
||||||
|
|
||||||
|
let cors = require('cors');
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
if (!process.env.PORT) {
|
if (!process.env.PORT) {
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
|
||||||
|
module.exports = {
|
||||||
|
preset: 'ts-jest',
|
||||||
|
testEnvironment: 'node',
|
||||||
|
roots: [
|
||||||
|
'test'
|
||||||
|
]
|
||||||
|
};
|
||||||
Generated
+5904
-2166
File diff suppressed because it is too large
Load Diff
+18
-14
@@ -3,30 +3,26 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=26"
|
|
||||||
},
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "tsc && node ./dist/app.js",
|
"start": "tsc && node ./dist/app.js",
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"debug": "export DEBUG=* && npm run start",
|
"debug": "export DEBUG=* && npm run start",
|
||||||
"test": "vitest run --coverage",
|
"test": "jest --coverage --testResultsProcessor ./node_modules/jest-sonar-reporter/index.js"
|
||||||
"test:watch": "vitest"
|
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"app-root-path": "^3.0.0",
|
"app-root-path": "^3.0.0",
|
||||||
"axios": "^1.20.0",
|
"axios": "^0.24.0",
|
||||||
"bcrypt": "^5.0.1",
|
"bcrypt": "^5.0.1",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"debug": "^4.3.1",
|
"debug": "^4.3.1",
|
||||||
"dotenv": "^16.6.1",
|
"dotenv": "^8.2.0",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
"guid-typescript": "^1.0.9",
|
"guid-typescript": "^1.0.9",
|
||||||
"mariadb": "^3.0.2",
|
"mariadb": "^3.0.2",
|
||||||
|
"nodemailer": "^6.9.8",
|
||||||
"random-words": "^1.1.1",
|
"random-words": "^1.1.1",
|
||||||
"swagger-jsdoc": "^6.1.0",
|
"swagger-jsdoc": "^6.1.0",
|
||||||
"swagger-ui-express": "^4.3.0",
|
"swagger-ui-express": "^4.3.0",
|
||||||
@@ -35,19 +31,27 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/app-root-path": "^1.2.4",
|
"@types/app-root-path": "^1.2.4",
|
||||||
"@types/bcrypt": "^3.0.1",
|
"@types/bcrypt": "^3.0.1",
|
||||||
"@types/cors": "^2.8.19",
|
|
||||||
"@types/debug": "^4.1.5",
|
"@types/debug": "^4.1.5",
|
||||||
"@types/express": "^4.17.15",
|
"@types/express": "^4.17.15",
|
||||||
"@types/node": "^26.4.1",
|
"@types/jest": "^28.1.3",
|
||||||
|
"@types/node": "^18.11.17",
|
||||||
|
"@types/nodemailer": "^6.4.14",
|
||||||
"@types/random-words": "^1.1.2",
|
"@types/random-words": "^1.1.2",
|
||||||
"@types/swagger-jsdoc": "^6.0.1",
|
"@types/swagger-jsdoc": "^6.0.1",
|
||||||
"@types/swagger-ui-express": "^4.1.3",
|
"@types/swagger-ui-express": "^4.1.3",
|
||||||
"@types/winston": "^2.4.4",
|
"@types/winston": "^2.4.4",
|
||||||
"@vitest/coverage-v8": "^5.0.0",
|
|
||||||
"is-number": "^7.0.0",
|
"is-number": "^7.0.0",
|
||||||
|
"jest": "^28.1.1",
|
||||||
|
"jest-sonar-reporter": "^2.0.0",
|
||||||
"source-map-support": "^0.5.19",
|
"source-map-support": "^0.5.19",
|
||||||
"typescript": "^5.9.3",
|
"ts-jest": "^28.0.5",
|
||||||
"vitest": "^5.0.0",
|
"tslint": "^6.1.3",
|
||||||
"vitest-sonar-reporter": "^3.0.0"
|
"typescript": "^4.9.4"
|
||||||
|
},
|
||||||
|
"jestSonar": {
|
||||||
|
"sonar56x": true,
|
||||||
|
"reportPath": "testResults",
|
||||||
|
"reportFile": "sonar-report.xml",
|
||||||
|
"indent": 4
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
-- Nachklang e.V. Tickets module — records the outcome of the redemption
|
|
||||||
-- confirmation email on the redemption itself, so the admin UI can flag a
|
|
||||||
-- failed send and offer a resend. NULL until the post-commit send resolves.
|
|
||||||
-- Apply manually against TICKETS_DB, after 002_add_require_address.sql:
|
|
||||||
-- mysql -h <DB_HOST> -u <DB_USER> -p <TICKETS_DB> < 003_add_confirmation_email_status.sql
|
|
||||||
ALTER TABLE redemptions
|
|
||||||
ADD COLUMN confirmation_email_status ENUM('SENT','FAILED') NULL DEFAULT NULL AFTER redeemed_at;
|
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import * as nodemailer from 'nodemailer';
|
||||||
|
|
||||||
|
export namespace MailService {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host: process.env.EMAIL_HOST,
|
||||||
|
pool: true,
|
||||||
|
port: 465,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: process.env.EMAIL_USERNAME,
|
||||||
|
pass: process.env.EMAIL_PASSWORD
|
||||||
|
},
|
||||||
|
tls: {rejectUnauthorized: false}
|
||||||
|
});
|
||||||
|
|
||||||
|
export interface MailAttachment {
|
||||||
|
filename: string;
|
||||||
|
content: string | Buffer;
|
||||||
|
contentType?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
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',
|
||||||
|
to: recipientAddress,
|
||||||
|
subject: subject,
|
||||||
|
text: body,
|
||||||
|
html: options?.html,
|
||||||
|
attachments: options?.attachments
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
import logger from '../middleware/logger.js';
|
|
||||||
import {salesforceApexRestPost, salesforceEnabled} from './salesforce.client.js';
|
|
||||||
|
|
||||||
// Transactional email for the ticketing/calendar flows (voucher redemption
|
|
||||||
// confirmations, account activation links, password-reset tokens) is relayed
|
|
||||||
// through the Nachklang Salesforce org rather than sent over our own SMTP host:
|
|
||||||
// that host's IP reputation gets it blocked by allowlist-based receivers
|
|
||||||
// (notably t-online.de). Salesforce's MTA plus the org's DKIM signature for
|
|
||||||
// nachklang.art get the mail delivered. The org endpoint is EmailSendResource
|
|
||||||
// (POST /services/apexrest/email/send); the From address is fixed server-side
|
|
||||||
// there and is never sent from here.
|
|
||||||
//
|
|
||||||
// sendMail never throws on a delivery problem. Every caller has already
|
|
||||||
// committed its own work (a registration, a password-reset token, a
|
|
||||||
// redemption) by the time mail goes out, so a mail failure must not surface as
|
|
||||||
// a user-facing error. It returns whether the mail was accepted so the one
|
|
||||||
// caller that shows failures to staff (the voucher confirmation) can record it.
|
|
||||||
|
|
||||||
export namespace MailService {
|
|
||||||
export interface MailAttachment {
|
|
||||||
filename: string;
|
|
||||||
content: string | Buffer;
|
|
||||||
contentType?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SendMailOptions {
|
|
||||||
html?: string;
|
|
||||||
attachments?: MailAttachment[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface EmailSendResponse {
|
|
||||||
status: 'SENT';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Practical ceiling, well under Apex REST's 6 MB request-body limit once
|
|
||||||
// base64 inflation (~33%) is accounted for. The only attachment today is a
|
|
||||||
// ~1 KB .ics file.
|
|
||||||
const MAX_ATTACHMENT_BYTES = 3 * 1024 * 1024;
|
|
||||||
|
|
||||||
const isRetriable = (err: any): boolean => {
|
|
||||||
const status = err?.response?.status;
|
|
||||||
if (status !== undefined) {
|
|
||||||
return status >= 500;
|
|
||||||
}
|
|
||||||
// No response at all - network error or timeout.
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Relays one email through the Salesforce org. Retries once on a transient
|
|
||||||
* failure (5xx / network / timeout), then logs and returns false rather
|
|
||||||
* than throwing. Returns false immediately (without a callout) when the
|
|
||||||
* Salesforce integration is disabled.
|
|
||||||
*/
|
|
||||||
export const sendMail = async (
|
|
||||||
recipientAddress: string,
|
|
||||||
subject: string,
|
|
||||||
body: string,
|
|
||||||
options?: SendMailOptions
|
|
||||||
): Promise<boolean> => {
|
|
||||||
if (!salesforceEnabled()) {
|
|
||||||
logger.info('MailService: SALESFORCE_ENABLED is false, would have sent', {recipientAddress, subject});
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let attachments: {filename: string; contentType?: string; contentBase64: string}[];
|
|
||||||
try {
|
|
||||||
attachments = (options?.attachments ?? []).map(attachment => {
|
|
||||||
const buffer = Buffer.isBuffer(attachment.content)
|
|
||||||
? attachment.content
|
|
||||||
: Buffer.from(attachment.content, 'utf-8');
|
|
||||||
if (buffer.byteLength > MAX_ATTACHMENT_BYTES) {
|
|
||||||
throw new Error(`attachment ${attachment.filename} is ${buffer.byteLength} bytes, over the ${MAX_ATTACHMENT_BYTES} limit`);
|
|
||||||
}
|
|
||||||
return {filename: attachment.filename, contentType: attachment.contentType, contentBase64: buffer.toString('base64')};
|
|
||||||
});
|
|
||||||
} catch (err: any) {
|
|
||||||
logger.error('MailService: could not prepare attachments', {recipientAddress, subject, detail: err?.message});
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
to: recipientAddress,
|
|
||||||
subject,
|
|
||||||
textBody: body,
|
|
||||||
htmlBody: options?.html ?? null,
|
|
||||||
attachments
|
|
||||||
};
|
|
||||||
|
|
||||||
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
||||||
try {
|
|
||||||
await salesforceApexRestPost<EmailSendResponse>('/services/apexrest/email/send', payload);
|
|
||||||
return true;
|
|
||||||
} catch (err: any) {
|
|
||||||
const status = err?.response?.status;
|
|
||||||
const detail = err?.response?.data?.errorCode || err?.response?.data?.message || err?.message || 'unknown error';
|
|
||||||
if (attempt === 1 && isRetriable(err)) {
|
|
||||||
logger.warn('MailService: send failed, retrying once', {recipientAddress, subject, status, detail});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
logger.error('MailService: send failed', {recipientAddress, subject, status, detail});
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import axios from 'axios';
|
|
||||||
|
|
||||||
// Shared server-to-server access to the one Nachklang Salesforce org. Both the
|
|
||||||
// newsletter-signup sync (feedback module) and the transactional-email relay
|
|
||||||
// (common.mail) authenticate the same way - OAuth 2.0 client credentials
|
|
||||||
// against the nk_Nachklang_API_Integration external client app - so the token
|
|
||||||
// cache and the retry-once-on-401 live here rather than being duplicated.
|
|
||||||
//
|
|
||||||
// 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 salesforceApexRestPost).
|
|
||||||
|
|
||||||
const TOKEN_CACHE_MS = 15 * 60 * 1000;
|
|
||||||
let cachedToken: {accessToken: string; fetchedAt: number} | null = null;
|
|
||||||
|
|
||||||
export const salesforceEnabled = (): boolean => process.env.SALESFORCE_ENABLED === 'true';
|
|
||||||
|
|
||||||
const readConfig = (): {instanceUrl: string; clientId: string; clientSecret: string} => {
|
|
||||||
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.');
|
|
||||||
}
|
|
||||||
return {instanceUrl, clientId, clientSecret};
|
|
||||||
};
|
|
||||||
|
|
||||||
const getAccessToken = async (forceRefresh: boolean): Promise<string> => {
|
|
||||||
if (!forceRefresh && cachedToken && Date.now() - cachedToken.fetchedAt < TOKEN_CACHE_MS) {
|
|
||||||
return cachedToken.accessToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
const {instanceUrl, clientId, clientSecret} = readConfig();
|
|
||||||
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;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* POSTs a JSON body to an Apex REST path (e.g. '/services/apexrest/newsletter/signup')
|
|
||||||
* and returns the parsed response body. Retries once with a forced token
|
|
||||||
* refresh on a 401 - the server-side token may have expired even though our
|
|
||||||
* conservative local TTL has not. All other errors propagate to the caller.
|
|
||||||
*/
|
|
||||||
export const salesforceApexRestPost = async <T>(path: string, body: unknown): Promise<T> => {
|
|
||||||
const {instanceUrl} = readConfig();
|
|
||||||
const url = `${instanceUrl}${path}`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const token = await getAccessToken(false);
|
|
||||||
const res = await axios.post<T>(url, body, {headers: {Authorization: `Bearer ${token}`}, timeout: 10000});
|
|
||||||
return res.data;
|
|
||||||
} catch (err: any) {
|
|
||||||
if (err?.response?.status === 401) {
|
|
||||||
const token = await getAccessToken(true);
|
|
||||||
const res = await axios.post<T>(url, body, {headers: {Authorization: `Bearer ${token}`}, timeout: 10000});
|
|
||||||
return res.data;
|
|
||||||
}
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import appRoot from 'app-root-path';
|
import * as appRoot from 'app-root-path';
|
||||||
import winston from 'winston';
|
import * as winston from 'winston';
|
||||||
|
|
||||||
const options = {
|
const options = {
|
||||||
file_info: {
|
file_info: {
|
||||||
level: 'info',
|
level: 'info',
|
||||||
filename: `${appRoot.path}/logs/app.log`,
|
filename: `${appRoot}/logs/app.log`,
|
||||||
handleExceptions: true,
|
handleExceptions: true,
|
||||||
json: true,
|
json: true,
|
||||||
maxsize: 5242880, // 5MB
|
maxsize: 5242880, // 5MB
|
||||||
@@ -13,7 +13,7 @@ const options = {
|
|||||||
},
|
},
|
||||||
file_error: {
|
file_error: {
|
||||||
level: 'error',
|
level: 'error',
|
||||||
filename: `${appRoot.path}/logs/error.log`,
|
filename: `${appRoot}/logs/error.log`,
|
||||||
handleExceptions: true,
|
handleExceptions: true,
|
||||||
json: true,
|
json: true,
|
||||||
maxsize: 5242880, // 5MB
|
maxsize: 5242880, // 5MB
|
||||||
@@ -22,7 +22,7 @@ const options = {
|
|||||||
},
|
},
|
||||||
file_debug: {
|
file_debug: {
|
||||||
level: 'debug',
|
level: 'debug',
|
||||||
filename: `${appRoot.path}/logs/debug.log`,
|
filename: `${appRoot}/logs/debug.log`,
|
||||||
handleExceptions: true,
|
handleExceptions: true,
|
||||||
json: true,
|
json: true,
|
||||||
maxsize: 5242880, // 5MB
|
maxsize: 5242880, // 5MB
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import mariadb from 'mariadb';
|
|
||||||
|
const mariadb = require('mariadb');
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
@@ -9,7 +10,8 @@ export namespace NachklangCalendarDB {
|
|||||||
user: process.env.DB_USER,
|
user: process.env.DB_USER,
|
||||||
password: process.env.DB_PASSWORD,
|
password: process.env.DB_PASSWORD,
|
||||||
database: process.env.CALENDAR_DB,
|
database: process.env.CALENDAR_DB,
|
||||||
connectionLimit: 5
|
connectionLimit: 5,
|
||||||
|
autoCommit: false
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getConnection = async () => {
|
export const getConnection = async () => {
|
||||||
|
|||||||
@@ -3,9 +3,9 @@
|
|||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import logger from '../../middleware/logger.js';
|
import logger from '../../middleware/logger';
|
||||||
import {eventsRouter} from './events/events.router.js';
|
import {eventsRouter} from './events/events.router';
|
||||||
import {usersRouter} from './users/users.router.js';
|
import {usersRouter} from './users/users.router';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import * as UserService from '../users/users.service.js';
|
import * as UserService from '../users/users.service';
|
||||||
|
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {Event} from './event.interface.js';
|
import {Event} from './event.interface';
|
||||||
import * as EventService from './events.service.js';
|
import * as EventService from './events.service';
|
||||||
import * as iCalService from './icalgenerator.service.js';
|
import * as iCalService from './icalgenerator.service';
|
||||||
import * as CredentialService from './credentials.service.js';
|
import * as CredentialService from './credentials.service';
|
||||||
import * as UserService from '../users/users.service.js';
|
import * as UserService from '../users/users.service';
|
||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import logger from '../../../middleware/logger.js';
|
import logger from '../../../middleware/logger';
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import {Event} from './event.interface.js';
|
import {Event} from './event.interface';
|
||||||
import {NachklangCalendarDB} from '../Calendar.db.js';
|
import {NachklangCalendarDB} from '../Calendar.db';
|
||||||
|
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {Event} from './event.interface.js';
|
import {Event} from './event.interface';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interface to external classes - Turns the given events into an ical string
|
* Interface to external classes - Turns the given events into an ical string
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import * as UserService from './users.service.js';
|
import * as UserService from './users.service';
|
||||||
import {Session} from './session.interface.js';
|
import {Session} from './session.interface';
|
||||||
import {User} from './user.interface.js';
|
import {User} from './user.interface';
|
||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import logger from '../../../middleware/logger.js';
|
import logger from '../../../middleware/logger';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import bcrypt from 'bcrypt';
|
import * as bcrypt from 'bcrypt';
|
||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import {User} from './user.interface.js';
|
import {User} from './user.interface';
|
||||||
import {Session} from './session.interface.js';
|
import {Session} from './session.interface';
|
||||||
import {NachklangCalendarDB} from '../Calendar.db.js';
|
import {NachklangCalendarDB} from '../Calendar.db';
|
||||||
import {MailService} from '../../../common/common.mail.js';
|
import {MailService} from "../../../common/common.mail.nodemailer";
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
@@ -54,10 +54,7 @@ export const createUser = async (email: string, password: string, fullName: stri
|
|||||||
sessionId = row.session_id;
|
sessionId = row.session_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send email with activation link (after commit so we don't block on email
|
// Send email with activation link (after commit so we don't block on email delivery)
|
||||||
// delivery). sendMail never throws on a delivery failure - it logs and
|
|
||||||
// returns false - so a mail-server problem here can't roll back the
|
|
||||||
// already-committed user and leave registration reporting a false error.
|
|
||||||
await MailService.sendMail(email, 'Activate your Nachklang account', `Hi ${fullName},\n\nPlease click on the following link to activate your account:\n\nhttps://api.nachklang.art/calendar/users/activate?id=${userId}&token=${activationToken}`);
|
await MailService.sendMail(email, 'Activate your Nachklang account', `Hi ${fullName},\n\nPlease click on the following link to activate your account:\n\nhttps://api.nachklang.art/calendar/users/activate?id=${userId}&token=${activationToken}`);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import mariadb from 'mariadb';
|
|
||||||
|
const mariadb = require('mariadb');
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
@@ -9,7 +10,8 @@ export namespace NachklangFeedbackDB {
|
|||||||
user: process.env.DB_USER,
|
user: process.env.DB_USER,
|
||||||
password: process.env.DB_PASSWORD,
|
password: process.env.DB_PASSWORD,
|
||||||
database: process.env.FEEDBACK_DB,
|
database: process.env.FEEDBACK_DB,
|
||||||
connectionLimit: 5
|
connectionLimit: 5,
|
||||||
|
autoCommit: false
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getConnection = async () => {
|
export const getConnection = async () => {
|
||||||
|
|||||||
@@ -2,9 +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 {publicRouter} from './public/public.router.js';
|
import {publicRouter} from './public/public.router';
|
||||||
import {adminRouter} from './admin/admin.router.js';
|
import {adminRouter} from './admin/admin.router';
|
||||||
import {sendServerError} from './feedback.errors.js';
|
import {sendServerError} from './feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -81,7 +81,7 @@
|
|||||||
* type: boolean
|
* type: boolean
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {QuestionType, Song} from '../feedback.interface.js';
|
import {QuestionType, Song} from '../feedback.interface';
|
||||||
|
|
||||||
export interface EventAdminSummary {
|
export interface EventAdminSummary {
|
||||||
eventId: number;
|
eventId: number;
|
||||||
|
|||||||
@@ -2,13 +2,13 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {requireAdminAuth} from '../feedback.auth.js';
|
import {requireAdminAuth} from '../feedback.auth';
|
||||||
import {sendServerError} from '../feedback.errors.js';
|
import {sendServerError} from '../feedback.errors';
|
||||||
import {eventsAdminRouter} from './events.admin.router.js';
|
import {eventsAdminRouter} from './events.admin.router';
|
||||||
import {songsAdminRouter} from './songs.admin.router.js';
|
import {songsAdminRouter} from './songs.admin.router';
|
||||||
import {questionsAdminRouter} from './questions.admin.router.js';
|
import {questionsAdminRouter} from './questions.admin.router';
|
||||||
import {reportsAdminRouter} from './reports.admin.router.js';
|
import {reportsAdminRouter} from './reports.admin.router';
|
||||||
import * as ReportsAdminService from './reports.admin.service.js';
|
import * as ReportsAdminService from './reports.admin.service';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db.js';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
import {formatDatetime} from '../feedback.dates.js';
|
import {formatDatetime} from '../feedback.dates';
|
||||||
|
|
||||||
const CSV_SEPARATOR = ';';
|
const CSV_SEPARATOR = ';';
|
||||||
const UTF8_BOM = '';
|
const UTF8_BOM = '';
|
||||||
|
|||||||
@@ -2,9 +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 * as EventsAdminService from './events.admin.service.js';
|
import * as EventsAdminService from './events.admin.service';
|
||||||
import * as SongsAdminService from './songs.admin.service.js';
|
import * as SongsAdminService from './songs.admin.service';
|
||||||
import {sendServerError} from '../feedback.errors.js';
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db.js';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
import {Song} from '../feedback.interface.js';
|
import {Song} from '../feedback.interface';
|
||||||
import {CreateEventInput, EventAdminDetail, EventAdminQuestionAssignment, EventAdminSummary, UpdateEventInput} from './admin.interface.js';
|
import {CreateEventInput, EventAdminDetail, EventAdminQuestionAssignment, EventAdminSummary, UpdateEventInput} from './admin.interface';
|
||||||
import {formatDatetime} from '../feedback.dates.js';
|
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',
|
||||||
|
|||||||
@@ -2,8 +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 * as QuestionsAdminService from './questions.admin.service.js';
|
import * as QuestionsAdminService from './questions.admin.service';
|
||||||
import {sendServerError} from '../feedback.errors.js';
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db.js';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
import {QuestionType} from '../feedback.interface.js';
|
import {QuestionType} from '../feedback.interface';
|
||||||
import {AdminQuestion} from './admin.interface.js';
|
import {AdminQuestion} from './admin.interface';
|
||||||
|
|
||||||
const mapRow = (row: any): AdminQuestion => ({
|
const mapRow = (row: any): AdminQuestion => ({
|
||||||
questionId: row.question_id,
|
questionId: row.question_id,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {QuestionType} from '../feedback.interface.js';
|
import {QuestionType} from '../feedback.interface';
|
||||||
|
|
||||||
export interface SongPickResult {
|
export interface SongPickResult {
|
||||||
songId: number;
|
songId: number;
|
||||||
|
|||||||
@@ -2,10 +2,10 @@
|
|||||||
* Required External Modules and Interfaces
|
* Required External Modules and Interfaces
|
||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import * as ReportsAdminService from './reports.admin.service.js';
|
import * as ReportsAdminService from './reports.admin.service';
|
||||||
import * as CsvService from './csv.service.js';
|
import * as CsvService from './csv.service';
|
||||||
import * as EventsAdminService from './events.admin.service.js';
|
import * as EventsAdminService from './events.admin.service';
|
||||||
import {sendServerError} from '../feedback.errors.js';
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db.js';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
import {
|
import {
|
||||||
AnswerRow, EventReport, FreeTextReport, SongPickReport, SongRatingReport
|
AnswerRow, EventReport, FreeTextReport, SongPickReport, SongRatingReport
|
||||||
} from './reports.admin.interface.js';
|
} from './reports.admin.interface';
|
||||||
|
|
||||||
const FREE_TEXT_CAP = 500;
|
const FREE_TEXT_CAP = 500;
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +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 * as SongsAdminService from './songs.admin.service.js';
|
import * as SongsAdminService from './songs.admin.service';
|
||||||
import {sendServerError} from '../feedback.errors.js';
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db.js';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
|
|
||||||
export const addSong = async (eventId: number, title: string, composer: string | null): Promise<number> => {
|
export const addSong = async (eventId: number, title: string, composer: string | null): Promise<number> => {
|
||||||
let conn = await NachklangFeedbackDB.getConnection();
|
let conn = await NachklangFeedbackDB.getConnection();
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
import * as UserService from '../calendar/users/users.service.js';
|
import * as UserService from '../calendar/users/users.service';
|
||||||
import {sendServerError} from './feedback.errors.js';
|
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
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {Response} from 'express';
|
import {Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import logger from '../../middleware/logger.js';
|
import logger from '../../middleware/logger';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The feedback module's standard catch-block response: log with a
|
* The feedback module's standard catch-block response: log with a
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as crypto from 'crypto';
|
import * as crypto from 'crypto';
|
||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import {NachklangFeedbackDB} from './Feedback.db.js';
|
import {NachklangFeedbackDB} from './Feedback.db';
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db.js';
|
import axios from 'axios';
|
||||||
import logger from '../../../middleware/logger.js';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
import {salesforceApexRestPost} from '../../../common/salesforce.client.js';
|
import logger from '../../../middleware/logger';
|
||||||
|
|
||||||
// Newsletter opt-ins sync to Salesforce, which already runs a full
|
// Newsletter opt-ins sync to Salesforce, which already runs a full
|
||||||
// double-opt-in subscription flow (Person Account for existing constituents,
|
// double-opt-in subscription flow (Person Account for existing constituents,
|
||||||
@@ -9,8 +9,7 @@ import {salesforceApexRestPost} from '../../../common/salesforce.client.js';
|
|||||||
// This is the one file that knows that contract exists; submissions.service.ts
|
// This is the one file that knows that contract exists; submissions.service.ts
|
||||||
// only ever calls syncNewsletterSignup(signupId) after its own transaction
|
// only ever calls syncNewsletterSignup(signupId) after its own transaction
|
||||||
// commits, fire-and-forget, so a Salesforce outage can never delay or fail a
|
// commits, fire-and-forget, so a Salesforce outage can never delay or fail a
|
||||||
// visitor's feedback submission. The OAuth token cache and retry-once-on-401
|
// visitor's feedback submission.
|
||||||
// live in common/salesforce.client.ts, shared with the transactional-email relay.
|
|
||||||
|
|
||||||
interface SalesforceSuccessResponse {
|
interface SalesforceSuccessResponse {
|
||||||
status: 'PENDING_CONFIRMATION' | 'ALREADY_SUBSCRIBED';
|
status: 'PENDING_CONFIRMATION' | 'ALREADY_SUBSCRIBED';
|
||||||
@@ -27,8 +26,54 @@ interface NewsletterSignupRow {
|
|||||||
event_name: string;
|
event_name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const postSignup = (payload: {firstName: string; lastName: string; email: string; eventName: string}): Promise<SalesforceSuccessResponse> =>
|
// Salesforce's client-credentials token response does not reliably include
|
||||||
salesforceApexRestPost<SalesforceSuccessResponse>('/services/apexrest/newsletter/signup', payload);
|
// 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> => {
|
const markSynced = async (signupId: number, externalId: string): Promise<void> => {
|
||||||
let conn = await NachklangFeedbackDB.getConnection();
|
let conn = await NachklangFeedbackDB.getConnection();
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db.js';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
import {EventConfig, EventSummary, Question, Song} from '../feedback.interface.js';
|
import {EventConfig, EventSummary, Question, Song} from '../feedback.interface';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns all events currently eligible to receive feedback:
|
* Returns all events currently eligible to receive feedback:
|
||||||
|
|||||||
@@ -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 logger from '../../../middleware/logger.js';
|
import logger from '../../../middleware/logger';
|
||||||
import {getEligibleEvents, getEventConfigBySlug} from './events.public.service.js';
|
import {getEligibleEvents, getEventConfigBySlug} from './events.public.service';
|
||||||
import {submitFeedback} from './submissions.service.js';
|
import {submitFeedback} from './submissions.service';
|
||||||
import {hashIp, isRateLimited, recordSubmission} from '../feedback.ratelimit.js';
|
import {hashIp, isRateLimited, recordSubmission} from '../feedback.ratelimit';
|
||||||
import {sendServerError} from '../feedback.errors.js';
|
import {sendServerError} from '../feedback.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import {NachklangFeedbackDB} from '../Feedback.db.js';
|
import {NachklangFeedbackDB} from '../Feedback.db';
|
||||||
import {QuestionType} from '../feedback.interface.js';
|
import {QuestionType} from '../feedback.interface';
|
||||||
import {getEventConfigBySlug} from './events.public.service.js';
|
import {getEventConfigBySlug} from './events.public.service';
|
||||||
import {AnswerInput, GuestBookInput, NewsletterInput, SubmissionRequestBody} from './submission.interface.js';
|
import {AnswerInput, GuestBookInput, NewsletterInput, SubmissionRequestBody} from './submission.interface';
|
||||||
import {syncNewsletterSignup} from '../integrations/salesforce.service.js';
|
import {syncNewsletterSignup} from '../integrations/salesforce.service';
|
||||||
import logger from '../../../middleware/logger.js';
|
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.
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import mariadb from 'mariadb';
|
|
||||||
|
const mariadb = require('mariadb');
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
@@ -9,7 +10,8 @@ export namespace NachklangTicketsDB {
|
|||||||
user: process.env.DB_USER,
|
user: process.env.DB_USER,
|
||||||
password: process.env.DB_PASSWORD,
|
password: process.env.DB_PASSWORD,
|
||||||
database: process.env.TICKETS_DB,
|
database: process.env.TICKETS_DB,
|
||||||
connectionLimit: 5
|
connectionLimit: 5,
|
||||||
|
autoCommit: false
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getConnection = async () => {
|
export const getConnection = async () => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
import {adminRouter} from './admin/admin.router.js';
|
import {adminRouter} from './admin/admin.router';
|
||||||
import {publicRouter} from './public/public.router.js';
|
import {publicRouter} from './public/public.router';
|
||||||
|
|
||||||
export const ticketsRouter = express.Router();
|
export const ticketsRouter = express.Router();
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {requireAdminAuth} from '../tickets.auth.js';
|
import {requireAdminAuth} from '../tickets.auth';
|
||||||
import {vouchersAdminRouter} from './vouchers.admin.router.js';
|
import {vouchersAdminRouter} from './vouchers.admin.router';
|
||||||
import {redemptionsAdminRouter, voucherHistoryRouter} from './redemptions.admin.router.js';
|
import {redemptionsAdminRouter, voucherHistoryRouter} from './redemptions.admin.router';
|
||||||
import {eventsAdminRouter} from './events.admin.router.js';
|
import {eventsAdminRouter} from './events.admin.router';
|
||||||
|
|
||||||
export const adminRouter = express.Router();
|
export const adminRouter = express.Router();
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import * as EventsAdminService from './events.admin.service.js';
|
import * as EventsAdminService from './events.admin.service';
|
||||||
import {sendServerError} from '../tickets.errors.js';
|
import {sendServerError} from '../tickets.errors';
|
||||||
|
|
||||||
export const eventsAdminRouter = express.Router();
|
export const eventsAdminRouter = express.Router();
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import * as CalendarEventsService from '../../calendar/events/events.service.js';
|
import * as CalendarEventsService from '../../calendar/events/events.service';
|
||||||
import {NachklangTicketsDB} from '../Tickets.db.js';
|
import {NachklangTicketsDB} from '../Tickets.db';
|
||||||
import {getEventTicketState} from '../tickets.capacity.js';
|
import {getEventTicketState} from '../tickets.capacity';
|
||||||
import {EventStats, EventTicketSettings} from '../tickets.interface.js';
|
import {EventStats, EventTicketSettings} from '../tickets.interface';
|
||||||
|
|
||||||
// Concerts are managed on the public calendar (calendarId 1) - see
|
// Concerts are managed on the public calendar (calendarId 1) - see
|
||||||
// docs/plan-ticket-shop.md. getAllEventsAdmin includes DRAFT events so
|
// docs/plan-ticket-shop.md. getAllEventsAdmin includes DRAFT events so
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import * as RedemptionsAdminService from './redemptions.admin.service.js';
|
import * as RedemptionsAdminService from './redemptions.admin.service';
|
||||||
import {sendServerError} from '../tickets.errors.js';
|
import {sendServerError} from '../tickets.errors';
|
||||||
|
|
||||||
export const redemptionsAdminRouter = express.Router();
|
export const redemptionsAdminRouter = express.Router();
|
||||||
|
|
||||||
@@ -204,55 +204,6 @@ redemptionsAdminRouter.post('/:redemptionId/undo', async (req: Request, res: Res
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* /tickets/admin/redemptions/{redemptionId}/resend-confirmation:
|
|
||||||
* post:
|
|
||||||
* summary: Resend the redemption confirmation email
|
|
||||||
* description: Rebuilds the confirmation email from the stored redemption data and sends it again, then records the outcome on the redemption. Intended for redemptions whose original confirmation email failed.
|
|
||||||
* tags: [tickets-admin]
|
|
||||||
* parameters:
|
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
|
||||||
* name: redemptionId
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: integer
|
|
||||||
* responses:
|
|
||||||
* 200:
|
|
||||||
* description: The email was accepted for delivery
|
|
||||||
* 404:
|
|
||||||
* description: Unknown redemption
|
|
||||||
* 409:
|
|
||||||
* description: Redemption is not active
|
|
||||||
* 502:
|
|
||||||
* description: The email relay rejected the send
|
|
||||||
* 401:
|
|
||||||
* description: Unauthorized
|
|
||||||
*/
|
|
||||||
redemptionsAdminRouter.post('/:redemptionId/resend-confirmation', async (req: Request, res: Response) => {
|
|
||||||
try {
|
|
||||||
const result = await RedemptionsAdminService.resendRedemptionConfirmation(Number(req.params.redemptionId));
|
|
||||||
switch (result) {
|
|
||||||
case 'SENT':
|
|
||||||
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 'FAILED':
|
|
||||||
res.status(502).send({status: 'SEND_FAILED', message: 'Die E-Mail konnte nicht versendet werden. Bitte später erneut versuchen.'});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
sendServerError(res, e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @swagger
|
* @swagger
|
||||||
* /tickets/admin/vouchers/{code}/history:
|
* /tickets/admin/vouchers/{code}/history:
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import {NachklangTicketsDB} from '../Tickets.db.js';
|
import {NachklangTicketsDB} from '../Tickets.db';
|
||||||
import {getEventTicketState} from '../tickets.capacity.js';
|
import {getEventTicketState} from '../tickets.capacity';
|
||||||
import {recordConfirmationEmailResult, sendRedemptionConfirmation} from '../tickets.confirmation-email.js';
|
import {AuditLogEntry, RedemptionSummary} from '../tickets.interface';
|
||||||
import {AuditLogEntry, RedemptionSummary} from '../tickets.interface.js';
|
import {isValidEmail} from '../tickets.validation';
|
||||||
import {isValidEmail} from '../tickets.validation.js';
|
|
||||||
|
|
||||||
const mapRedemptionRow = (row: any, guests: string[]): RedemptionSummary => ({
|
const mapRedemptionRow = (row: any, guests: string[]): RedemptionSummary => ({
|
||||||
redemptionId: row.redemption_id,
|
redemptionId: row.redemption_id,
|
||||||
@@ -14,8 +13,7 @@ const mapRedemptionRow = (row: any, guests: string[]): RedemptionSummary => ({
|
|||||||
contactAddress: row.contact_address,
|
contactAddress: row.contact_address,
|
||||||
guestCount: row.guest_count,
|
guestCount: row.guest_count,
|
||||||
guests,
|
guests,
|
||||||
redeemedAt: row.redeemed_at,
|
redeemedAt: row.redeemed_at
|
||||||
confirmationEmailStatus: row.confirmation_email_status ?? null
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export interface ListRedemptionsFilter {
|
export interface ListRedemptionsFilter {
|
||||||
@@ -229,29 +227,6 @@ export const editRedemption = async (redemptionId: number, input: EditRedemption
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ResendConfirmationResult = 'SENT' | 'FAILED' | 'NOT_FOUND' | 'NOT_ACTIVE';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Rebuilds and re-sends the redemption confirmation email from the stored
|
|
||||||
* redemption data, then records the new outcome on the row. Used by the admin
|
|
||||||
* UI's "resend" action on a redemption whose confirmation email failed. Only
|
|
||||||
* active redemptions can be resent.
|
|
||||||
*/
|
|
||||||
export const resendRedemptionConfirmation = async (redemptionId: number): Promise<ResendConfirmationResult> => {
|
|
||||||
const redemption = await getRedemption(redemptionId);
|
|
||||||
if (!redemption) return 'NOT_FOUND';
|
|
||||||
if (redemption.status !== 'ACTIVE') return 'NOT_ACTIVE';
|
|
||||||
|
|
||||||
const sent = await sendRedemptionConfirmation({
|
|
||||||
eventId: redemption.eventId,
|
|
||||||
contactName: redemption.contactName,
|
|
||||||
contactEmail: redemption.contactEmail,
|
|
||||||
guestNames: redemption.guests
|
|
||||||
});
|
|
||||||
await recordConfirmationEmailResult(redemptionId, sent);
|
|
||||||
return sent ? 'SENT' : 'FAILED';
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getAuditHistory = async (code: string): Promise<AuditLogEntry[]> => {
|
export const getAuditHistory = async (code: string): Promise<AuditLogEntry[]> => {
|
||||||
let conn = await NachklangTicketsDB.getConnection();
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import * as VouchersAdminService from './vouchers.admin.service.js';
|
import * as VouchersAdminService from './vouchers.admin.service';
|
||||||
import {sendServerError} from '../tickets.errors.js';
|
import {sendServerError} from '../tickets.errors';
|
||||||
|
|
||||||
export const vouchersAdminRouter = express.Router();
|
export const vouchersAdminRouter = express.Router();
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import {NachklangTicketsDB} from '../Tickets.db.js';
|
import {NachklangTicketsDB} from '../Tickets.db';
|
||||||
import {generateUniqueCode} from '../tickets.codes.js';
|
import {generateUniqueCode} from '../tickets.codes';
|
||||||
import {VoucherCode, VoucherStatus} from '../tickets.interface.js';
|
import {VoucherCode, VoucherStatus} from '../tickets.interface';
|
||||||
import {isValidEmail} from '../tickets.validation.js';
|
import {isValidEmail} from '../tickets.validation';
|
||||||
|
|
||||||
export interface WildcardGenerateInput {
|
export interface WildcardGenerateInput {
|
||||||
eventIds: number[];
|
eventIds: number[];
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import * as VoucherPublicService from './voucher.public.service.js';
|
import * as VoucherPublicService from './voucher.public.service';
|
||||||
import {sendServerError} from '../tickets.errors.js';
|
import {sendServerError} from '../tickets.errors';
|
||||||
import {hashIp, redeemLimiter, validateLimiter} from '../tickets.ratelimit.js';
|
import {hashIp, redeemLimiter, validateLimiter} from '../tickets.ratelimit';
|
||||||
|
|
||||||
export const publicRouter = express.Router();
|
export const publicRouter = express.Router();
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,19 @@
|
|||||||
import * as EventsService from '../../calendar/events/events.service.js';
|
import * as EventsService from '../../calendar/events/events.service';
|
||||||
import logger from '../../../middleware/logger.js';
|
import * as IcalService from '../../calendar/events/icalgenerator.service';
|
||||||
import {NachklangTicketsDB} from '../Tickets.db.js';
|
import {MailService} from '../../../common/common.mail.nodemailer';
|
||||||
import {getEventTicketState} from '../tickets.capacity.js';
|
import logger from '../../../middleware/logger';
|
||||||
import {recordConfirmationEmailResult, sendRedemptionConfirmation} from '../tickets.confirmation-email.js';
|
import {NachklangTicketsDB} from '../Tickets.db';
|
||||||
import {EligibleEvent, RedeemRequest, VoucherValidation} from '../tickets.interface.js';
|
import {getEventTicketState} from '../tickets.capacity';
|
||||||
import {isValidEmail} from '../tickets.validation.js';
|
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
|
* Builds the eligible-events list for a code: for each event it's linked
|
||||||
@@ -164,21 +173,43 @@ export const redeemVoucher = async (code: string, request: RedeemRequest): Promi
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sent after commit, mirroring the Calendar/Feedback convention: a mail
|
// Sent after commit, mirroring the Calendar/Feedback convention: a mail
|
||||||
// delivery failure shouldn't roll back a successful redemption, and the
|
// delivery failure shouldn't roll back a successful redemption. Caught
|
||||||
// guest has in fact already secured their spot. The send itself no longer
|
// rather than left to propagate - the redemption already succeeded, so
|
||||||
// throws on a delivery problem; its result is recorded on the redemption
|
// a mail-server hiccup must not turn into a false failure response to
|
||||||
// so staff can spot and resend a failed confirmation from the admin UI.
|
// a guest who has, in fact, already secured their spot.
|
||||||
try {
|
try {
|
||||||
const sent = await sendRedemptionConfirmation({
|
await sendConfirmationEmail(eventId, request, redemptionId);
|
||||||
eventId,
|
|
||||||
contactName: request.contactName,
|
|
||||||
contactEmail: request.contactEmail,
|
|
||||||
guestNames: request.guests.map(g => g.name)
|
|
||||||
});
|
|
||||||
await recordConfirmationEmailResult(redemptionId, sent);
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
logger.error('Redemption ' + redemptionId + ' committed but the confirmation email step failed: ' + e.message);
|
logger.error('Redemption ' + redemptionId + ' succeeded but confirmation email failed to send: ' + e.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {status: 'OK', redemptionId};
|
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}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
import * as UserService from '../calendar/users/users.service.js';
|
import * as UserService from '../calendar/users/users.service';
|
||||||
import {sendServerError} from './tickets.errors.js';
|
import {sendServerError} from './tickets.errors';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mirrors the Feedback module's feedback.auth.ts: this is the ONLY place in
|
* Mirrors the Feedback module's feedback.auth.ts: this is the ONLY place in
|
||||||
|
|||||||
@@ -1,76 +0,0 @@
|
|||||||
import * as EventsService from '../calendar/events/events.service.js';
|
|
||||||
import * as IcalService from '../calendar/events/icalgenerator.service.js';
|
|
||||||
import {MailService} from '../../common/common.mail.js';
|
|
||||||
import logger from '../../middleware/logger.js';
|
|
||||||
import {NachklangTicketsDB} from './Tickets.db.js';
|
|
||||||
|
|
||||||
export type ConfirmationEmailStatus = 'SENT' | 'FAILED';
|
|
||||||
|
|
||||||
// The redemption confirmation email is built and sent from here so the public
|
|
||||||
// redeem path and the admin "resend" action share one copy of the German text
|
|
||||||
// and the .ics attachment logic.
|
|
||||||
|
|
||||||
const formatGermanDateTime = (date: Date): string =>
|
|
||||||
new Intl.DateTimeFormat('de-DE', {
|
|
||||||
dateStyle: 'full',
|
|
||||||
timeStyle: 'short',
|
|
||||||
timeZone: 'Europe/Berlin'
|
|
||||||
}).format(date);
|
|
||||||
|
|
||||||
export interface ConfirmationRecipient {
|
|
||||||
eventId: number;
|
|
||||||
contactName: string;
|
|
||||||
contactEmail: string;
|
|
||||||
guestNames: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sends the redemption confirmation email for one redemption. Returns whether
|
|
||||||
* the mail was accepted by the relay. Never throws: a missing event is treated
|
|
||||||
* as "not sent", and MailService.sendMail already swallows delivery failures.
|
|
||||||
*/
|
|
||||||
export const sendRedemptionConfirmation = async (recipient: ConfirmationRecipient): Promise<boolean> => {
|
|
||||||
const event = await EventsService.getEventById(recipient.eventId);
|
|
||||||
if (!event) {
|
|
||||||
logger.error('Confirmation email skipped: event ' + recipient.eventId + ' no longer exists');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const guestList = recipient.guestNames.map(name => `- ${name}`).join('\n');
|
|
||||||
const body =
|
|
||||||
`Hallo ${recipient.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 (e: any) {
|
|
||||||
// Non-fatal: the confirmation still goes out, just without the calendar file.
|
|
||||||
logger.warn('Confirmation email for event ' + recipient.eventId + ' sent without .ics attachment: ' + e?.message);
|
|
||||||
icsAttachment = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
return MailService.sendMail(recipient.contactEmail, `Bestätigung: ${event.name}`, body, {attachments: icsAttachment});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records the outcome of a confirmation-email send on the redemption row so the
|
|
||||||
* admin UI can flag failures. Best-effort: a failure to write the flag is
|
|
||||||
* logged, never thrown - the redemption itself already succeeded.
|
|
||||||
*/
|
|
||||||
export const recordConfirmationEmailResult = async (redemptionId: number, sent: boolean): Promise<void> => {
|
|
||||||
const status: ConfirmationEmailStatus = sent ? 'SENT' : 'FAILED';
|
|
||||||
let conn = await NachklangTicketsDB.getConnection();
|
|
||||||
try {
|
|
||||||
await conn.query('UPDATE redemptions SET confirmation_email_status = ? WHERE redemption_id = ?', [status, redemptionId]);
|
|
||||||
} catch (err: any) {
|
|
||||||
logger.error('Could not record confirmation email status for redemption ' + redemptionId + ': ' + err?.message);
|
|
||||||
} finally {
|
|
||||||
await conn.end();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import {Response} from 'express';
|
import {Response} from 'express';
|
||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import logger from '../../middleware/logger.js';
|
import logger from '../../middleware/logger';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The tickets module's standard catch-block response: log with a reference
|
* The tickets module's standard catch-block response: log with a reference
|
||||||
|
|||||||
@@ -109,11 +109,6 @@
|
|||||||
* redeemedAt:
|
* redeemedAt:
|
||||||
* type: string
|
* type: string
|
||||||
* format: date-time
|
* format: date-time
|
||||||
* confirmationEmailStatus:
|
|
||||||
* type: string
|
|
||||||
* enum: [SENT, FAILED]
|
|
||||||
* nullable: true
|
|
||||||
* description: Outcome of the redemption confirmation email. null until the send resolves.
|
|
||||||
* VoucherCode:
|
* VoucherCode:
|
||||||
* type: object
|
* type: object
|
||||||
* required: [code, status, maxGuests, createdByEmail, createdAt, eligibleEventIds]
|
* required: [code, status, maxGuests, createdByEmail, createdAt, eligibleEventIds]
|
||||||
@@ -263,8 +258,6 @@ export interface RedemptionSummary {
|
|||||||
guestCount: number;
|
guestCount: number;
|
||||||
guests: string[];
|
guests: string[];
|
||||||
redeemedAt: Date;
|
redeemedAt: Date;
|
||||||
// null until the post-redemption confirmation email send resolves.
|
|
||||||
confirmationEmailStatus: 'SENT' | 'FAILED' | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VoucherCode {
|
export interface VoucherCode {
|
||||||
|
|||||||
@@ -1,116 +0,0 @@
|
|||||||
// common.mail relays one email through the Salesforce org (see
|
|
||||||
// src/common/common.mail.ts). These tests mock the shared Salesforce client so
|
|
||||||
// no network is touched, and check: the payload shape, base64 attachment
|
|
||||||
// encoding, the attachment size cap, the retry-once-on-transient-failure
|
|
||||||
// behaviour, and that a delivery failure is swallowed (returns false, never
|
|
||||||
// throws).
|
|
||||||
|
|
||||||
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
|
||||||
vi.mock('../../src/common/salesforce.client.js');
|
|
||||||
vi.mock('../../src/middleware/logger.js', () => ({
|
|
||||||
__esModule: true,
|
|
||||||
default: {info: vi.fn(), warn: vi.fn(), error: vi.fn()}
|
|
||||||
}));
|
|
||||||
|
|
||||||
import {MailService} from '../../src/common/common.mail.js';
|
|
||||||
import {salesforceApexRestPost, salesforceEnabled} from '../../src/common/salesforce.client.js';
|
|
||||||
|
|
||||||
const mockPost = salesforceApexRestPost as Mock;
|
|
||||||
const mockEnabled = salesforceEnabled as Mock;
|
|
||||||
|
|
||||||
const httpError = (status: number, body?: any): any => {
|
|
||||||
const err: any = new Error('request failed with ' + status);
|
|
||||||
err.response = {status, data: body};
|
|
||||||
return err;
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockEnabled.mockReturnValue(true);
|
|
||||||
mockPost.mockResolvedValue({status: 'SENT'});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('MailService.sendMail', () => {
|
|
||||||
it('returns false without a callout when Salesforce is disabled', async () => {
|
|
||||||
mockEnabled.mockReturnValue(false);
|
|
||||||
|
|
||||||
const result = await MailService.sendMail('guest@example.com', 'Hi', 'Hallo');
|
|
||||||
|
|
||||||
expect(result).toBe(false);
|
|
||||||
expect(mockPost).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('posts the email to the Apex REST endpoint and returns true on success', async () => {
|
|
||||||
const result = await MailService.sendMail('guest@example.com', 'Bestätigung', 'Hallo', {html: '<p>Hallo</p>'});
|
|
||||||
|
|
||||||
expect(result).toBe(true);
|
|
||||||
expect(mockPost).toHaveBeenCalledWith('/services/apexrest/email/send', {
|
|
||||||
to: 'guest@example.com',
|
|
||||||
subject: 'Bestätigung',
|
|
||||||
textBody: 'Hallo',
|
|
||||||
htmlBody: '<p>Hallo</p>',
|
|
||||||
attachments: []
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('sends htmlBody as null when no HTML is given', async () => {
|
|
||||||
await MailService.sendMail('guest@example.com', 'Hi', 'Hallo');
|
|
||||||
|
|
||||||
expect(mockPost).toHaveBeenCalledWith('/services/apexrest/email/send', expect.objectContaining({htmlBody: null}));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('base64-encodes attachments', async () => {
|
|
||||||
await MailService.sendMail('guest@example.com', 'Hi', 'Hallo', {
|
|
||||||
attachments: [{filename: 'konzert.ics', content: 'BEGIN:VCALENDAR', contentType: 'text/calendar'}]
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(mockPost).toHaveBeenCalledWith(
|
|
||||||
'/services/apexrest/email/send',
|
|
||||||
expect.objectContaining({
|
|
||||||
attachments: [{
|
|
||||||
filename: 'konzert.ics',
|
|
||||||
contentType: 'text/calendar',
|
|
||||||
contentBase64: Buffer.from('BEGIN:VCALENDAR', 'utf-8').toString('base64')
|
|
||||||
}]
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects an attachment over the size cap without sending', async () => {
|
|
||||||
const huge = Buffer.alloc(3 * 1024 * 1024 + 1);
|
|
||||||
|
|
||||||
const result = await MailService.sendMail('guest@example.com', 'Hi', 'Hallo', {
|
|
||||||
attachments: [{filename: 'big.pdf', content: huge}]
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result).toBe(false);
|
|
||||||
expect(mockPost).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('retries once on a 5xx and returns false when the retry also fails', async () => {
|
|
||||||
mockPost.mockRejectedValue(httpError(503));
|
|
||||||
|
|
||||||
const result = await MailService.sendMail('guest@example.com', 'Hi', 'Hallo');
|
|
||||||
|
|
||||||
expect(result).toBe(false);
|
|
||||||
expect(mockPost).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('retries once on a network error (no response) then succeeds', async () => {
|
|
||||||
mockPost.mockRejectedValueOnce(new Error('socket hang up')).mockResolvedValueOnce({status: 'SENT'});
|
|
||||||
|
|
||||||
const result = await MailService.sendMail('guest@example.com', 'Hi', 'Hallo');
|
|
||||||
|
|
||||||
expect(result).toBe(true);
|
|
||||||
expect(mockPost).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not retry on a 4xx (e.g. the 429 limit response) and returns false', async () => {
|
|
||||||
mockPost.mockRejectedValue(httpError(429, {errorCode: 'LIMIT_REACHED'}));
|
|
||||||
|
|
||||||
const result = await MailService.sendMail('guest@example.com', 'Hi', 'Hallo');
|
|
||||||
|
|
||||||
expect(result).toBe(false);
|
|
||||||
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
// salesforce.client caches the OAuth token at module scope, so every test
|
|
||||||
// resets the module registry for a clean cache and re-imports axios + the
|
|
||||||
// module under test after the reset (same approach as
|
|
||||||
// test/feedback/salesforce.service.test.ts). Mocked modules survive
|
|
||||||
// vi.resetModules(), so mock state is reset explicitly in beforeEach.
|
|
||||||
|
|
||||||
import {vi, describe, it, expect, beforeEach, afterAll} from 'vitest';
|
|
||||||
vi.mock('axios');
|
|
||||||
|
|
||||||
const freshImports = async () => {
|
|
||||||
const axios: any = (await import('axios')).default;
|
|
||||||
const {salesforceApexRestPost, salesforceEnabled} = await import('../../src/common/salesforce.client.js');
|
|
||||||
return {axios, salesforceApexRestPost, salesforceEnabled};
|
|
||||||
};
|
|
||||||
|
|
||||||
const ORIGINAL_ENV = {...process.env};
|
|
||||||
const ENABLED_ENV = {
|
|
||||||
...ORIGINAL_ENV,
|
|
||||||
SALESFORCE_ENABLED: 'true',
|
|
||||||
SALESFORCE_API_URL: 'https://example.my.salesforce.com',
|
|
||||||
SALESFORCE_CLIENT_ID: 'client-id',
|
|
||||||
SALESFORCE_CLIENT_SECRET: 'client-secret'
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.resetModules();
|
|
||||||
vi.resetAllMocks();
|
|
||||||
process.env = {...ENABLED_ENV};
|
|
||||||
});
|
|
||||||
|
|
||||||
afterAll(() => {
|
|
||||||
process.env = {...ORIGINAL_ENV};
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('salesforceEnabled', () => {
|
|
||||||
it('is true only when SALESFORCE_ENABLED === "true"', async () => {
|
|
||||||
process.env.SALESFORCE_ENABLED = 'true';
|
|
||||||
expect((await freshImports()).salesforceEnabled()).toBe(true);
|
|
||||||
|
|
||||||
vi.resetModules();
|
|
||||||
process.env.SALESFORCE_ENABLED = 'false';
|
|
||||||
expect((await freshImports()).salesforceEnabled()).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('salesforceApexRestPost', () => {
|
|
||||||
it('fetches a token, posts to the given Apex REST path, and returns the response body', async () => {
|
|
||||||
const {axios, salesforceApexRestPost} = await freshImports();
|
|
||||||
axios.post.mockImplementation((url: string) => {
|
|
||||||
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
|
|
||||||
return Promise.resolve({data: {ok: true}});
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await salesforceApexRestPost('/services/apexrest/email/send', {to: 'x@example.com'});
|
|
||||||
|
|
||||||
expect(result).toEqual({ok: true});
|
|
||||||
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/email/send',
|
|
||||||
{to: 'x@example.com'},
|
|
||||||
expect.objectContaining({headers: {Authorization: 'Bearer tok-1'}})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reuses the cached token across calls instead of fetching twice', async () => {
|
|
||||||
const {axios, salesforceApexRestPost} = await freshImports();
|
|
||||||
axios.post.mockImplementation((url: string) => {
|
|
||||||
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
|
|
||||||
return Promise.resolve({data: {}});
|
|
||||||
});
|
|
||||||
|
|
||||||
await salesforceApexRestPost('/services/apexrest/email/send', {});
|
|
||||||
await salesforceApexRestPost('/services/apexrest/email/send', {});
|
|
||||||
|
|
||||||
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, salesforceApexRestPost} = await freshImports();
|
|
||||||
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 (tokenFetches === 1) {
|
|
||||||
const err: any = new Error('Unauthorized');
|
|
||||||
err.response = {status: 401};
|
|
||||||
return Promise.reject(err);
|
|
||||||
}
|
|
||||||
return Promise.resolve({data: {ok: true}});
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await salesforceApexRestPost('/services/apexrest/email/send', {});
|
|
||||||
|
|
||||||
expect(result).toEqual({ok: true});
|
|
||||||
expect(tokenFetches).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not retry on a non-401 error and rethrows it', async () => {
|
|
||||||
const {axios, salesforceApexRestPost} = await freshImports();
|
|
||||||
axios.post.mockImplementation((url: string) => {
|
|
||||||
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
|
|
||||||
const err: any = new Error('Server error');
|
|
||||||
err.response = {status: 500};
|
|
||||||
return Promise.reject(err);
|
|
||||||
});
|
|
||||||
|
|
||||||
await expect(salesforceApexRestPost('/services/apexrest/email/send', {})).rejects.toThrow('Server error');
|
|
||||||
const endpointCalls = axios.post.mock.calls.filter(([url]: [string]) => url.endsWith('/email/send'));
|
|
||||||
expect(endpointCalls).toHaveLength(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws a clear error when client credentials are not configured', async () => {
|
|
||||||
process.env.SALESFORCE_CLIENT_ID = '';
|
|
||||||
const {salesforceApexRestPost} = await freshImports();
|
|
||||||
|
|
||||||
await expect(salesforceApexRestPost('/services/apexrest/email/send', {})).rejects.toThrow('SALESFORCE_CLIENT_ID');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import {describe, it, expect} from 'vitest';
|
import {escapeCsvField} from '../../src/models/feedback/admin/csv.service';
|
||||||
import {escapeCsvField} from '../../src/models/feedback/admin/csv.service.js';
|
import {formatDatetime} from '../../src/models/feedback/feedback.dates';
|
||||||
import {formatDatetime} from '../../src/models/feedback/feedback.dates.js';
|
|
||||||
|
|
||||||
describe('escapeCsvField', () => {
|
describe('escapeCsvField', () => {
|
||||||
it('passes plain text through unchanged', () => {
|
it('passes plain text through unchanged', () => {
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import {describe, it, expect} from 'vitest';
|
import {computeDefaultDeadline, slugBase, slugifyName} from '../../src/models/feedback/admin/events.admin.service';
|
||||||
import {computeDefaultDeadline, slugBase, slugifyName} from '../../src/models/feedback/admin/events.admin.service.js';
|
|
||||||
|
|
||||||
describe('slugifyName', () => {
|
describe('slugifyName', () => {
|
||||||
it('lowercases and hyphenates', () => {
|
it('lowercases and hyphenates', () => {
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
|
||||||
import {Request, Response} from 'express';
|
import {Request, Response} from 'express';
|
||||||
|
|
||||||
vi.mock('../../src/models/calendar/users/users.service.js', () => ({
|
jest.mock('../../src/models/calendar/users/users.service', () => ({
|
||||||
checkSession: vi.fn()
|
checkSession: jest.fn()
|
||||||
}));
|
}));
|
||||||
|
|
||||||
import * as UserService from '../../src/models/calendar/users/users.service.js';
|
import * as UserService from '../../src/models/calendar/users/users.service';
|
||||||
import {requireAdminAuth, sessionHeaderAuthenticator} from '../../src/models/feedback/feedback.auth.js';
|
import {requireAdminAuth, sessionHeaderAuthenticator} from '../../src/models/feedback/feedback.auth';
|
||||||
|
|
||||||
const mockCheckSession = UserService.checkSession as Mock;
|
const mockCheckSession = UserService.checkSession as jest.Mock;
|
||||||
|
|
||||||
const makeReq = (headers: Record<string, string>): Request => {
|
const makeReq = (headers: Record<string, string>): Request => {
|
||||||
return {
|
return {
|
||||||
@@ -19,8 +18,8 @@ const makeReq = (headers: Record<string, string>): Request => {
|
|||||||
|
|
||||||
const makeRes = (): Response => {
|
const makeRes = (): Response => {
|
||||||
const res: any = {};
|
const res: any = {};
|
||||||
res.status = vi.fn().mockReturnValue(res);
|
res.status = jest.fn().mockReturnValue(res);
|
||||||
res.send = vi.fn().mockReturnValue(res);
|
res.send = jest.fn().mockReturnValue(res);
|
||||||
res.locals = {};
|
res.locals = {};
|
||||||
return res as Response;
|
return res as Response;
|
||||||
};
|
};
|
||||||
@@ -66,7 +65,7 @@ describe('requireAdminAuth', () => {
|
|||||||
mockCheckSession.mockResolvedValue(null);
|
mockCheckSession.mockResolvedValue(null);
|
||||||
const req = makeReq({});
|
const req = makeReq({});
|
||||||
const res = makeRes();
|
const res = makeRes();
|
||||||
const next = vi.fn();
|
const next = jest.fn();
|
||||||
|
|
||||||
await requireAdminAuth(req, res, next);
|
await requireAdminAuth(req, res, next);
|
||||||
|
|
||||||
@@ -78,7 +77,7 @@ describe('requireAdminAuth', () => {
|
|||||||
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'Anna Admin', isActive: true});
|
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'Anna Admin', isActive: true});
|
||||||
const req = makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'});
|
const req = makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'});
|
||||||
const res = makeRes();
|
const res = makeRes();
|
||||||
const next = vi.fn();
|
const next = jest.fn();
|
||||||
|
|
||||||
await requireAdminAuth(req, res, next);
|
await requireAdminAuth(req, res, next);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import {describe, it, expect} from 'vitest';
|
import {isHoneypotTriggered} from '../../src/models/feedback/public/public.router';
|
||||||
import {isHoneypotTriggered} from '../../src/models/feedback/public/public.router.js';
|
|
||||||
|
|
||||||
describe('isHoneypotTriggered', () => {
|
describe('isHoneypotTriggered', () => {
|
||||||
it('is false when the field is absent', () => {
|
it('is false when the field is absent', () => {
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
// Isolated from ratelimit.test.ts because it needs to control whether
|
// Isolated from ratelimit.test.ts because it needs to control whether
|
||||||
// FEEDBACK_IP_SALT is present at module-load time, which a real dotenv.config()
|
// FEEDBACK_IP_SALT is present at module-load time, which a real dotenv.config()
|
||||||
// call would silently repopulate from the repo's .env file.
|
// call would silently repopulate from the repo's .env file.
|
||||||
import {vi, describe, it, expect, afterEach} from 'vitest';
|
jest.mock('dotenv', () => ({config: jest.fn()}));
|
||||||
vi.mock('dotenv', () => ({config: vi.fn()}));
|
jest.mock('../../src/models/feedback/Feedback.db', () => ({
|
||||||
vi.mock('../../src/models/feedback/Feedback.db.js', () => ({
|
NachklangFeedbackDB: {getConnection: jest.fn()}
|
||||||
NachklangFeedbackDB: {getConnection: vi.fn()}
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
describe('FEEDBACK_IP_SALT enforcement', () => {
|
describe('FEEDBACK_IP_SALT enforcement', () => {
|
||||||
@@ -12,18 +11,18 @@ describe('FEEDBACK_IP_SALT enforcement', () => {
|
|||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
process.env.FEEDBACK_IP_SALT = originalSalt;
|
process.env.FEEDBACK_IP_SALT = originalSalt;
|
||||||
vi.resetModules();
|
jest.resetModules();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws at import time when FEEDBACK_IP_SALT is unset, rather than silently hashing unsalted', async () => {
|
it('throws at import time when FEEDBACK_IP_SALT is unset, rather than silently hashing unsalted', () => {
|
||||||
vi.resetModules();
|
jest.resetModules();
|
||||||
delete process.env.FEEDBACK_IP_SALT;
|
delete process.env.FEEDBACK_IP_SALT;
|
||||||
await expect(import('../../src/models/feedback/feedback.ratelimit.js')).rejects.toThrow(/FEEDBACK_IP_SALT/);
|
expect(() => require('../../src/models/feedback/feedback.ratelimit')).toThrow(/FEEDBACK_IP_SALT/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not throw when FEEDBACK_IP_SALT is set', async () => {
|
it('does not throw when FEEDBACK_IP_SALT is set', () => {
|
||||||
vi.resetModules();
|
jest.resetModules();
|
||||||
process.env.FEEDBACK_IP_SALT = 'a-real-salt';
|
process.env.FEEDBACK_IP_SALT = 'a-real-salt';
|
||||||
await expect(import('../../src/models/feedback/feedback.ratelimit.js')).resolves.toBeDefined();
|
expect(() => require('../../src/models/feedback/feedback.ratelimit')).not.toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import {describe, it, expect} from 'vitest';
|
import {hashIp} from '../../src/models/feedback/feedback.ratelimit';
|
||||||
import {hashIp} from '../../src/models/feedback/feedback.ratelimit.js';
|
|
||||||
|
|
||||||
describe('hashIp', () => {
|
describe('hashIp', () => {
|
||||||
it('never returns the raw IP', () => {
|
it('never returns the raw IP', () => {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import {describe, it, expect} from 'vitest';
|
import {aggregateReport} from '../../src/models/feedback/admin/reports.admin.service';
|
||||||
import {aggregateReport} from '../../src/models/feedback/admin/reports.admin.service.js';
|
import {AnswerRow} from '../../src/models/feedback/admin/reports.admin.interface';
|
||||||
import {AnswerRow} from '../../src/models/feedback/admin/reports.admin.interface.js';
|
|
||||||
|
|
||||||
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, skipped: 0};
|
const emptyNewsletter = {total: 0, sent: 0, pending: 0, failed: 0, skipped: 0};
|
||||||
|
|||||||
@@ -1,19 +1,17 @@
|
|||||||
// The module under test caches its OAuth token at module scope (see
|
// The module under test caches its OAuth token at module scope (see
|
||||||
// salesforce.service.ts's `cachedToken`), so every test resets the module
|
// salesforce.service.ts's `cachedToken`), so every test resets the module
|
||||||
// registry for a clean cache. Every mocked dependency (axios, Feedback.db,
|
// registry for a clean cache. That also invalidates any jest.mock() factory
|
||||||
// the logger) is re-imported after the reset rather than referenced from a
|
// instance captured before the reset, so every mocked dependency (axios,
|
||||||
// top-level import, so the test always holds the same instance the service
|
// Feedback.db, the logger) is re-required fresh after each reset rather
|
||||||
// under test resolves. Mocked modules survive vi.resetModules(), so their
|
// than referenced from a top-level import.
|
||||||
// mock state is reset explicitly in beforeEach.
|
|
||||||
|
|
||||||
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
jest.mock('axios');
|
||||||
vi.mock('axios');
|
jest.mock('../../src/models/feedback/Feedback.db', () => ({
|
||||||
vi.mock('../../src/models/feedback/Feedback.db.js', () => ({
|
NachklangFeedbackDB: {getConnection: jest.fn()}
|
||||||
NachklangFeedbackDB: {getConnection: vi.fn()}
|
|
||||||
}));
|
}));
|
||||||
vi.mock('../../src/middleware/logger.js', () => ({
|
jest.mock('../../src/middleware/logger', () => ({
|
||||||
__esModule: true,
|
__esModule: true,
|
||||||
default: {info: vi.fn(), error: vi.fn()}
|
default: {info: jest.fn(), error: jest.fn()}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const SIGNUP_ROW = {
|
const SIGNUP_ROW = {
|
||||||
@@ -25,31 +23,30 @@ const SIGNUP_ROW = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const makeConn = (rows: any[]) => ({
|
const makeConn = (rows: any[]) => ({
|
||||||
query: vi.fn().mockResolvedValue(rows),
|
query: jest.fn().mockResolvedValue(rows),
|
||||||
end: vi.fn().mockResolvedValue(undefined)
|
end: jest.fn().mockResolvedValue(undefined)
|
||||||
});
|
});
|
||||||
|
|
||||||
// Re-imports every mocked dependency (see the note above) and returns the
|
// Re-requires every mocked dependency fresh (see the note above) and
|
||||||
// live references plus the service under test.
|
// returns the live references plus the service under test.
|
||||||
const freshImports = async () => {
|
const freshImports = () => {
|
||||||
const axios: any = (await import('axios')).default;
|
const axios = require('axios');
|
||||||
const {NachklangFeedbackDB} = await import('../../src/models/feedback/Feedback.db.js');
|
const {NachklangFeedbackDB} = require('../../src/models/feedback/Feedback.db');
|
||||||
const logger = (await import('../../src/middleware/logger.js')).default;
|
const logger = require('../../src/middleware/logger').default;
|
||||||
const {syncNewsletterSignup} = await import('../../src/models/feedback/integrations/salesforce.service.js');
|
const {syncNewsletterSignup} = require('../../src/models/feedback/integrations/salesforce.service');
|
||||||
return {axios, mockGetConnection: NachklangFeedbackDB.getConnection as Mock, logger, syncNewsletterSignup};
|
return {axios, mockGetConnection: NachklangFeedbackDB.getConnection as jest.Mock, logger, syncNewsletterSignup};
|
||||||
};
|
};
|
||||||
|
|
||||||
const ORIGINAL_ENV = {...process.env};
|
const ORIGINAL_ENV = {...process.env};
|
||||||
|
|
||||||
describe('syncNewsletterSignup - disabled mode', () => {
|
describe('syncNewsletterSignup - disabled mode', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.resetModules();
|
jest.resetModules();
|
||||||
vi.resetAllMocks();
|
|
||||||
process.env = {...ORIGINAL_ENV, SALESFORCE_ENABLED: 'false'};
|
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 () => {
|
it('logs the payload it would send and does not touch the network or write to the DB', async () => {
|
||||||
const {axios, mockGetConnection, logger, syncNewsletterSignup} = await freshImports();
|
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
|
||||||
const conn = makeConn([SIGNUP_ROW]);
|
const conn = makeConn([SIGNUP_ROW]);
|
||||||
mockGetConnection.mockResolvedValue(conn);
|
mockGetConnection.mockResolvedValue(conn);
|
||||||
|
|
||||||
@@ -69,7 +66,7 @@ describe('syncNewsletterSignup - disabled mode', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('logs and returns without calling the network when the signup row does not exist', async () => {
|
it('logs and returns without calling the network when the signup row does not exist', async () => {
|
||||||
const {axios, mockGetConnection, logger, syncNewsletterSignup} = await freshImports();
|
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
|
||||||
mockGetConnection.mockResolvedValue(makeConn([]));
|
mockGetConnection.mockResolvedValue(makeConn([]));
|
||||||
|
|
||||||
await syncNewsletterSignup(999);
|
await syncNewsletterSignup(999);
|
||||||
@@ -81,8 +78,7 @@ describe('syncNewsletterSignup - disabled mode', () => {
|
|||||||
|
|
||||||
describe('syncNewsletterSignup - enabled mode', () => {
|
describe('syncNewsletterSignup - enabled mode', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.resetModules();
|
jest.resetModules();
|
||||||
vi.resetAllMocks();
|
|
||||||
process.env = {
|
process.env = {
|
||||||
...ORIGINAL_ENV,
|
...ORIGINAL_ENV,
|
||||||
SALESFORCE_ENABLED: 'true',
|
SALESFORCE_ENABLED: 'true',
|
||||||
@@ -93,7 +89,7 @@ describe('syncNewsletterSignup - enabled mode', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('fetches a token, posts the signup, and marks the row SENT with the returned record id', async () => {
|
it('fetches a token, posts the signup, and marks the row SENT with the returned record id', async () => {
|
||||||
const {axios, mockGetConnection, syncNewsletterSignup} = await freshImports();
|
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
|
||||||
const updateConn = makeConn([]);
|
const updateConn = makeConn([]);
|
||||||
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
||||||
axios.post.mockImplementation((url: string) => {
|
axios.post.mockImplementation((url: string) => {
|
||||||
@@ -120,7 +116,7 @@ describe('syncNewsletterSignup - enabled mode', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('reuses the cached token across two calls instead of fetching twice', async () => {
|
it('reuses the cached token across two calls instead of fetching twice', async () => {
|
||||||
const {axios, mockGetConnection, syncNewsletterSignup} = await freshImports();
|
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
|
||||||
mockGetConnection
|
mockGetConnection
|
||||||
.mockResolvedValueOnce(makeConn([SIGNUP_ROW]))
|
.mockResolvedValueOnce(makeConn([SIGNUP_ROW]))
|
||||||
.mockResolvedValueOnce(makeConn([]))
|
.mockResolvedValueOnce(makeConn([]))
|
||||||
@@ -139,7 +135,7 @@ describe('syncNewsletterSignup - enabled mode', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('retries once with a fresh token on a 401, then succeeds', async () => {
|
it('retries once with a fresh token on a 401, then succeeds', async () => {
|
||||||
const {axios, mockGetConnection, syncNewsletterSignup} = await freshImports();
|
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
|
||||||
const updateConn = makeConn([]);
|
const updateConn = makeConn([]);
|
||||||
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
||||||
|
|
||||||
@@ -167,7 +163,7 @@ describe('syncNewsletterSignup - enabled mode', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('marks the row FAILED with the error message on a non-401 error, without throwing', async () => {
|
it('marks the row FAILED with the error message on a non-401 error, without throwing', async () => {
|
||||||
const {axios, mockGetConnection, logger, syncNewsletterSignup} = await freshImports();
|
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
|
||||||
const updateConn = makeConn([]);
|
const updateConn = makeConn([]);
|
||||||
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
||||||
axios.post.mockImplementation((url: string) => {
|
axios.post.mockImplementation((url: string) => {
|
||||||
@@ -188,7 +184,7 @@ describe('syncNewsletterSignup - enabled mode', () => {
|
|||||||
|
|
||||||
it('marks the row FAILED with a clear message when client credentials are not configured', async () => {
|
it('marks the row FAILED with a clear message when client credentials are not configured', async () => {
|
||||||
process.env.SALESFORCE_CLIENT_ID = '';
|
process.env.SALESFORCE_CLIENT_ID = '';
|
||||||
const {mockGetConnection, syncNewsletterSignup} = await freshImports();
|
const {mockGetConnection, syncNewsletterSignup} = freshImports();
|
||||||
const updateConn = makeConn([]);
|
const updateConn = makeConn([]);
|
||||||
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import {describe, it, expect} from 'vitest';
|
import {MAX_ANSWER_ROWS, validateAnswers, validateGuestBook, validateNewsletter} from '../../src/models/feedback/public/submissions.service';
|
||||||
import {MAX_ANSWER_ROWS, validateAnswers, validateGuestBook, validateNewsletter} from '../../src/models/feedback/public/submissions.service.js';
|
|
||||||
|
|
||||||
type QuestionLookup = Map<number, {eventQuestionId: number; questionId: number; type: 'SONG_PICK' | 'SONG_RATING' | 'FREE_TEXT'; label: string; position: number}>;
|
type QuestionLookup = Map<number, {eventQuestionId: number; questionId: number; type: 'SONG_PICK' | 'SONG_RATING' | 'FREE_TEXT'; label: string; position: number}>;
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import {test, expect} from 'vitest';
|
|
||||||
test('Test template', async () => {
|
test('Test template', async () => {
|
||||||
expect(true).toBe(true);
|
expect(true).toBe(true);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,132 +0,0 @@
|
|||||||
// tickets.confirmation-email builds and sends the redemption confirmation
|
|
||||||
// email, shared by the public redeem path and the admin resend action.
|
|
||||||
|
|
||||||
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
|
||||||
vi.mock('../../src/models/calendar/events/events.service.js', () => ({
|
|
||||||
getEventById: vi.fn()
|
|
||||||
}));
|
|
||||||
vi.mock('../../src/models/calendar/events/icalgenerator.service.js', () => ({
|
|
||||||
convertToIcal: vi.fn()
|
|
||||||
}));
|
|
||||||
vi.mock('../../src/common/common.mail.js', () => ({
|
|
||||||
MailService: {sendMail: vi.fn()}
|
|
||||||
}));
|
|
||||||
vi.mock('../../src/models/tickets/Tickets.db.js', () => ({
|
|
||||||
NachklangTicketsDB: {getConnection: vi.fn()}
|
|
||||||
}));
|
|
||||||
vi.mock('../../src/middleware/logger.js', () => ({
|
|
||||||
__esModule: true,
|
|
||||||
default: {info: vi.fn(), warn: vi.fn(), error: vi.fn()}
|
|
||||||
}));
|
|
||||||
|
|
||||||
import * as EventsService from '../../src/models/calendar/events/events.service.js';
|
|
||||||
import * as IcalService from '../../src/models/calendar/events/icalgenerator.service.js';
|
|
||||||
import {MailService} from '../../src/common/common.mail.js';
|
|
||||||
import logger from '../../src/middleware/logger.js';
|
|
||||||
import {NachklangTicketsDB} from '../../src/models/tickets/Tickets.db.js';
|
|
||||||
import {recordConfirmationEmailResult, sendRedemptionConfirmation} from '../../src/models/tickets/tickets.confirmation-email.js';
|
|
||||||
|
|
||||||
const mockGetEvent = EventsService.getEventById as Mock;
|
|
||||||
const mockToIcal = IcalService.convertToIcal as Mock;
|
|
||||||
const mockSendMail = MailService.sendMail as Mock;
|
|
||||||
const mockLogger = logger as unknown as {info: Mock; warn: Mock; error: Mock};
|
|
||||||
const mockGetConnection = NachklangTicketsDB.getConnection as Mock;
|
|
||||||
|
|
||||||
const EVENT = {
|
|
||||||
eventId: 42,
|
|
||||||
name: 'Sommerkonzert 2026',
|
|
||||||
startDateTime: new Date('2026-07-01T19:00:00Z'),
|
|
||||||
location: 'Christuskirche',
|
|
||||||
status: 'PUBLISHED'
|
|
||||||
};
|
|
||||||
|
|
||||||
const RECIPIENT = {
|
|
||||||
eventId: 42,
|
|
||||||
contactName: 'Erika Mustermann',
|
|
||||||
contactEmail: 'erika@example.com',
|
|
||||||
guestNames: ['Erika Mustermann', 'Hans Mustermann']
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockGetEvent.mockResolvedValue(EVENT);
|
|
||||||
mockToIcal.mockResolvedValue('BEGIN:VCALENDAR\nEND:VCALENDAR');
|
|
||||||
mockSendMail.mockResolvedValue(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('sendRedemptionConfirmation', () => {
|
|
||||||
it('sends the German confirmation with the event details, guest list and .ics attachment', async () => {
|
|
||||||
const result = await sendRedemptionConfirmation(RECIPIENT);
|
|
||||||
|
|
||||||
expect(result).toBe(true);
|
|
||||||
expect(mockSendMail).toHaveBeenCalledTimes(1);
|
|
||||||
const [to, subject, body, options] = mockSendMail.mock.calls[0];
|
|
||||||
expect(to).toBe('erika@example.com');
|
|
||||||
expect(subject).toBe('Bestätigung: Sommerkonzert 2026');
|
|
||||||
expect(body).toContain('Hallo Erika Mustermann,');
|
|
||||||
expect(body).toContain('"Sommerkonzert 2026"');
|
|
||||||
expect(body).toContain('- Hans Mustermann');
|
|
||||||
expect(options.attachments).toEqual([
|
|
||||||
{filename: 'konzert.ics', content: 'BEGIN:VCALENDAR\nEND:VCALENDAR', contentType: 'text/calendar'}
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('still sends (without an attachment) and warns when the .ics build fails', async () => {
|
|
||||||
mockToIcal.mockRejectedValue(new Error('ical boom'));
|
|
||||||
|
|
||||||
await sendRedemptionConfirmation(RECIPIENT);
|
|
||||||
|
|
||||||
const options = mockSendMail.mock.calls[0][3];
|
|
||||||
expect(options.attachments).toBeUndefined();
|
|
||||||
expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('without .ics attachment'));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns false and does not send when the event no longer exists', async () => {
|
|
||||||
mockGetEvent.mockResolvedValue(null);
|
|
||||||
|
|
||||||
const result = await sendRedemptionConfirmation(RECIPIENT);
|
|
||||||
|
|
||||||
expect(result).toBe(false);
|
|
||||||
expect(mockSendMail).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('propagates the relay result', async () => {
|
|
||||||
mockSendMail.mockResolvedValue(false);
|
|
||||||
|
|
||||||
expect(await sendRedemptionConfirmation(RECIPIENT)).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('recordConfirmationEmailResult', () => {
|
|
||||||
const makeConn = () => ({query: vi.fn().mockResolvedValue(undefined), end: vi.fn().mockResolvedValue(undefined)});
|
|
||||||
|
|
||||||
it('writes SENT when the mail was accepted', async () => {
|
|
||||||
const conn = makeConn();
|
|
||||||
mockGetConnection.mockResolvedValue(conn);
|
|
||||||
|
|
||||||
await recordConfirmationEmailResult(7, true);
|
|
||||||
|
|
||||||
expect(conn.query).toHaveBeenCalledWith(
|
|
||||||
'UPDATE redemptions SET confirmation_email_status = ? WHERE redemption_id = ?',
|
|
||||||
['SENT', 7]
|
|
||||||
);
|
|
||||||
expect(conn.end).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('writes FAILED when the mail was not accepted', async () => {
|
|
||||||
const conn = makeConn();
|
|
||||||
mockGetConnection.mockResolvedValue(conn);
|
|
||||||
|
|
||||||
await recordConfirmationEmailResult(7, false);
|
|
||||||
|
|
||||||
expect(conn.query).toHaveBeenCalledWith(expect.any(String), ['FAILED', 7]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('swallows a DB error rather than throwing', async () => {
|
|
||||||
const conn = {query: vi.fn().mockRejectedValue(new Error('db down')), end: vi.fn().mockResolvedValue(undefined)};
|
|
||||||
mockGetConnection.mockResolvedValue(conn);
|
|
||||||
|
|
||||||
await expect(recordConfirmationEmailResult(7, true)).resolves.toBeUndefined();
|
|
||||||
expect(conn.end).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
// resendRedemptionConfirmation rebuilds the confirmation email from stored
|
|
||||||
// redemption data and records the new outcome. Only the resend path is
|
|
||||||
// exercised here; the shared send/record logic is covered by
|
|
||||||
// confirmation-email.test.ts.
|
|
||||||
|
|
||||||
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
|
||||||
vi.mock('../../src/models/tickets/Tickets.db.js', () => ({
|
|
||||||
NachklangTicketsDB: {getConnection: vi.fn()}
|
|
||||||
}));
|
|
||||||
vi.mock('../../src/models/tickets/tickets.confirmation-email.js', () => ({
|
|
||||||
sendRedemptionConfirmation: vi.fn(),
|
|
||||||
recordConfirmationEmailResult: vi.fn()
|
|
||||||
}));
|
|
||||||
|
|
||||||
import {NachklangTicketsDB} from '../../src/models/tickets/Tickets.db.js';
|
|
||||||
import {recordConfirmationEmailResult, sendRedemptionConfirmation} from '../../src/models/tickets/tickets.confirmation-email.js';
|
|
||||||
import {resendRedemptionConfirmation} from '../../src/models/tickets/admin/redemptions.admin.service.js';
|
|
||||||
|
|
||||||
const mockGetConnection = NachklangTicketsDB.getConnection as Mock;
|
|
||||||
const mockSend = sendRedemptionConfirmation as Mock;
|
|
||||||
const mockRecord = recordConfirmationEmailResult as Mock;
|
|
||||||
|
|
||||||
const ACTIVE_ROW = {
|
|
||||||
redemption_id: 5,
|
|
||||||
code: 'ABC123',
|
|
||||||
event_id: 42,
|
|
||||||
status: 'ACTIVE',
|
|
||||||
contact_name: 'Erika Mustermann',
|
|
||||||
contact_email: 'erika@example.com',
|
|
||||||
contact_address: null,
|
|
||||||
guest_count: 2,
|
|
||||||
redeemed_at: new Date('2026-06-01T10:00:00Z'),
|
|
||||||
confirmation_email_status: 'FAILED'
|
|
||||||
};
|
|
||||||
|
|
||||||
// getRedemption issues: 1) SELECT redemptions, 2) SELECT redemption_guests
|
|
||||||
const connFor = (redemptionRows: any[], guestRows: any[] = []) => ({
|
|
||||||
query: vi
|
|
||||||
.fn()
|
|
||||||
.mockResolvedValueOnce(redemptionRows)
|
|
||||||
.mockResolvedValueOnce(guestRows),
|
|
||||||
end: vi.fn().mockResolvedValue(undefined)
|
|
||||||
});
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockSend.mockResolvedValue(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('resendRedemptionConfirmation', () => {
|
|
||||||
it('returns NOT_FOUND when the redemption does not exist', async () => {
|
|
||||||
mockGetConnection.mockResolvedValue(connFor([]));
|
|
||||||
|
|
||||||
expect(await resendRedemptionConfirmation(5)).toBe('NOT_FOUND');
|
|
||||||
expect(mockSend).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns NOT_ACTIVE for an undone redemption', async () => {
|
|
||||||
mockGetConnection.mockResolvedValue(connFor([{...ACTIVE_ROW, status: 'UNDONE'}]));
|
|
||||||
|
|
||||||
expect(await resendRedemptionConfirmation(5)).toBe('NOT_ACTIVE');
|
|
||||||
expect(mockSend).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('resends from the stored data and records SENT on success', async () => {
|
|
||||||
mockGetConnection.mockResolvedValue(connFor([ACTIVE_ROW], [{name: 'Erika Mustermann'}, {name: 'Hans Mustermann'}]));
|
|
||||||
|
|
||||||
const result = await resendRedemptionConfirmation(5);
|
|
||||||
|
|
||||||
expect(result).toBe('SENT');
|
|
||||||
expect(mockSend).toHaveBeenCalledWith({
|
|
||||||
eventId: 42,
|
|
||||||
contactName: 'Erika Mustermann',
|
|
||||||
contactEmail: 'erika@example.com',
|
|
||||||
guestNames: ['Erika Mustermann', 'Hans Mustermann']
|
|
||||||
});
|
|
||||||
expect(mockRecord).toHaveBeenCalledWith(5, true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('records FAILED and returns FAILED when the relay rejects the send', async () => {
|
|
||||||
mockGetConnection.mockResolvedValue(connFor([ACTIVE_ROW], [{name: 'Erika Mustermann'}]));
|
|
||||||
mockSend.mockResolvedValue(false);
|
|
||||||
|
|
||||||
const result = await resendRedemptionConfirmation(5);
|
|
||||||
|
|
||||||
expect(result).toBe('FAILED');
|
|
||||||
expect(mockRecord).toHaveBeenCalledWith(5, false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+98
-15
@@ -1,20 +1,103 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
/* The API is native ESM ("type": "module" in package.json). nodenext makes
|
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||||
tsc emit ESM, requires the ".js" suffix on relative imports, and treats
|
|
||||||
CommonJS dependencies (express, mariadb, winston, ...) via default imports. */
|
|
||||||
"module": "nodenext",
|
|
||||||
"target": "es2024",
|
|
||||||
"lib": ["es2024"],
|
|
||||||
"types": ["node"],
|
|
||||||
|
|
||||||
"outDir": "./dist",
|
/* Projects */
|
||||||
"inlineSourceMap": true,
|
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||||
|
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||||
|
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||||
|
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||||
|
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||||
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||||
|
|
||||||
"esModuleInterop": true,
|
/* Language and Environment */
|
||||||
"forceConsistentCasingInFileNames": true,
|
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||||
"strict": true,
|
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
"skipLibCheck": true
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
},
|
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||||
"include": ["app.ts", "src/**/*.ts", "test/**/*.ts", "vitest.config.ts"]
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
|
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||||
|
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||||
|
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||||
|
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||||
|
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||||
|
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||||
|
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||||
|
|
||||||
|
/* Modules */
|
||||||
|
"module": "commonjs", /* Specify what module code is generated. */
|
||||||
|
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||||
|
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||||
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||||
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
|
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||||
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||||
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||||
|
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||||
|
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
|
||||||
|
/* JavaScript Support */
|
||||||
|
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||||
|
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||||
|
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||||
|
|
||||||
|
/* Emit */
|
||||||
|
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||||
|
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
||||||
|
// "removeComments": true, /* Disable emitting comments. */
|
||||||
|
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||||
|
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||||
|
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||||
|
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||||
|
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||||
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
|
"inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||||
|
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||||
|
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||||
|
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||||
|
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||||
|
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||||
|
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||||
|
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||||
|
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||||
|
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||||
|
|
||||||
|
/* Interop Constraints */
|
||||||
|
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||||
|
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||||
|
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||||
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
|
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||||
|
|
||||||
|
/* Type Checking */
|
||||||
|
"strict": true, /* Enable all strict type-checking options. */
|
||||||
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||||
|
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||||
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||||
|
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||||
|
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||||
|
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||||
|
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||||
|
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||||
|
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||||
|
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||||
|
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||||
|
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||||
|
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||||
|
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||||
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||||
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||||
|
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||||
|
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||||
|
|
||||||
|
/* Completeness */
|
||||||
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
import {defineConfig} from 'vitest/config';
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
test: {
|
|
||||||
include: ['test/**/*.test.ts'],
|
|
||||||
environment: 'node',
|
|
||||||
// feedback.ratelimit throws at import time without a salt (see
|
|
||||||
// test/feedback/ratelimit.salt-guard.test.ts). Set one here so the suite
|
|
||||||
// passes on a clean checkout without a local .env; the salt-guard test
|
|
||||||
// deletes it explicitly before exercising the missing-salt path.
|
|
||||||
env: {
|
|
||||||
FEEDBACK_IP_SALT: 'vitest-salt'
|
|
||||||
},
|
|
||||||
reporters: [
|
|
||||||
'default',
|
|
||||||
['vitest-sonar-reporter', {outputFile: 'testResults/sonar-report.xml'}]
|
|
||||||
],
|
|
||||||
coverage: {
|
|
||||||
provider: 'v8',
|
|
||||||
reporter: ['text-summary', 'lcov'],
|
|
||||||
reportsDirectory: 'coverage',
|
|
||||||
include: ['app.ts', 'src/**/*.ts']
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Reference in New Issue
Block a user