Add Feedback domain module: public submission flow, admin CRUD, reporting (#7)
Jenkins Production Deployment

Co-authored-by: Patrick Müller <mail@pmueller.me>
Reviewed-on: #7
Co-authored-by: Patrick Mueller <patrick@mueller-patrick.tech>
Co-committed-by: Patrick Mueller <patrick@mueller-patrick.tech>
This commit was merged in pull request #7.
This commit is contained in:
2026-08-23 09:39:02 +00:00
committed by Patrick Müller
parent e7621b8290
commit b05f6b9da0
38 changed files with 4115 additions and 2 deletions
+58
View File
@@ -0,0 +1,58 @@
import {escapeCsvField} from '../../src/models/feedback/admin/csv.service';
import {formatDatetime} from '../../src/models/feedback/feedback.dates';
describe('escapeCsvField', () => {
it('passes plain text through unchanged', () => {
expect(escapeCsvField('Abendlied')).toBe('Abendlied');
});
it('converts null/undefined to an empty string', () => {
expect(escapeCsvField(null)).toBe('');
expect(escapeCsvField(undefined)).toBe('');
});
it('converts numbers to strings', () => {
expect(escapeCsvField(5)).toBe('5');
});
it('quotes and doubles internal quotes (RFC 4180)', () => {
expect(escapeCsvField('Sie sagte "Danke"')).toBe('"Sie sagte ""Danke"""');
});
it('quotes a field containing the ; separator', () => {
expect(escapeCsvField('Rheinberger; Bach')).toBe('"Rheinberger; Bach"');
});
it('strips embedded newlines instead of breaking the row', () => {
expect(escapeCsvField('Zeile 1\r\nZeile 2')).toBe('Zeile 1 Zeile 2');
expect(escapeCsvField('Zeile 1\nZeile 2')).toBe('Zeile 1 Zeile 2');
});
it('prefixes formula-injection characters with an apostrophe', () => {
expect(escapeCsvField('=1+1')).toBe("'=1+1");
expect(escapeCsvField('+SUM(A1)')).toBe("'+SUM(A1)");
expect(escapeCsvField('-2')).toBe("'-2");
expect(escapeCsvField('@example')).toBe("'@example");
});
it('does not treat a mid-string = as formula injection', () => {
expect(escapeCsvField('x = y')).toBe('x = y');
});
});
describe('formatDatetime', () => {
it('formats a Date as YYYY-MM-DD HH:mm:ss, not the verbose Date.toString()', () => {
const d = new Date(2026, 7, 2, 21, 59, 21); // month is 0-indexed: August
expect(formatDatetime(d)).toBe('2026-08-02 21:59:21');
expect(formatDatetime(d)).not.toContain('GMT');
});
it('pads single-digit components', () => {
const d = new Date(2026, 0, 5, 3, 4, 5);
expect(formatDatetime(d)).toBe('2026-01-05 03:04:05');
});
it('returns an empty string for null', () => {
expect(formatDatetime(null)).toBe('');
});
});
@@ -0,0 +1,59 @@
import {computeDefaultDeadline, slugBase, slugifyName} from '../../src/models/feedback/admin/events.admin.service';
describe('slugifyName', () => {
it('lowercases and hyphenates', () => {
expect(slugifyName('Sommerkonzert 2026')).toBe('sommerkonzert-2026');
});
it('transliterates umlauts', () => {
expect(slugifyName('Frühlingskonzert')).toBe('fruehlingskonzert');
expect(slugifyName('Weihnachtsgrüße')).toBe('weihnachtsgruesse');
});
it('strips punctuation and collapses separators', () => {
expect(slugifyName('Konzert: "Klänge & Farben"!')).toBe('konzert-klaenge-farben');
});
it('trims leading and trailing hyphens', () => {
expect(slugifyName(' -- Herbstkonzert -- ')).toBe('herbstkonzert');
});
});
describe('slugBase', () => {
it('appends the concert year when the name does not already carry it', () => {
expect(slugBase('Sommerkonzert', '2026-08-01')).toBe('sommerkonzert-2026');
});
it('does not double up the year when the name already ends with it', () => {
expect(slugBase('Adventskonzert 2026', '2026-12-06')).toBe('adventskonzert-2026');
});
it('still appends the year when the name contains a different year', () => {
expect(slugBase('Jubiläum 2020', '2026-08-01')).toBe('jubilaeum-2020-2026');
});
});
describe('computeDefaultDeadline', () => {
it('is 14 days after the event date, at 23:59:59', () => {
const deadline = computeDefaultDeadline('2026-08-01');
expect(deadline.getFullYear()).toBe(2026);
expect(deadline.getMonth()).toBe(7); // August = index 7
expect(deadline.getDate()).toBe(15);
expect(deadline.getHours()).toBe(23);
expect(deadline.getMinutes()).toBe(59);
expect(deadline.getSeconds()).toBe(59);
});
it('rolls over the month correctly', () => {
const deadline = computeDefaultDeadline('2026-08-25');
expect(deadline.getMonth()).toBe(8); // September
expect(deadline.getDate()).toBe(8);
});
it('rolls over the year correctly', () => {
const deadline = computeDefaultDeadline('2026-12-25');
expect(deadline.getFullYear()).toBe(2027);
expect(deadline.getMonth()).toBe(0); // January
expect(deadline.getDate()).toBe(8);
});
});
+87
View File
@@ -0,0 +1,87 @@
import {Request, Response} from 'express';
jest.mock('../../src/models/calendar/users/users.service', () => ({
checkSession: jest.fn()
}));
import * as UserService from '../../src/models/calendar/users/users.service';
import {requireAdminAuth, sessionHeaderAuthenticator} from '../../src/models/feedback/feedback.auth';
const mockCheckSession = UserService.checkSession as jest.Mock;
const makeReq = (headers: Record<string, string>): Request => {
return {
header: (name: string) => headers[name],
ip: '203.0.113.42'
} as unknown as Request;
};
const makeRes = (): Response => {
const res: any = {};
res.status = jest.fn().mockReturnValue(res);
res.send = jest.fn().mockReturnValue(res);
res.locals = {};
return res as Response;
};
describe('sessionHeaderAuthenticator', () => {
beforeEach(() => mockCheckSession.mockReset());
it('returns null when headers are missing', async () => {
const identity = await sessionHeaderAuthenticator(makeReq({}));
expect(identity).toBeNull();
expect(mockCheckSession).not.toHaveBeenCalled();
});
it('returns null when checkSession finds no user', async () => {
mockCheckSession.mockResolvedValue(null);
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
expect(identity).toBeNull();
});
it('returns null for a valid session on an inactive account', async () => {
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'A', isActive: false});
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
expect(identity).toBeNull();
});
it('returns the identity for a valid session on an active account', async () => {
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'Anna Admin', isActive: true});
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
expect(identity).toEqual({id: '1', email: 'a@nachklang.art', displayName: 'Anna Admin'});
});
it('passes the session id and key from headers through to checkSession, never from query params', async () => {
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'A', isActive: true});
await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '42', 'X-Session-Key': 'sekret'}));
expect(mockCheckSession).toHaveBeenCalledWith('42', 'sekret', '203.0.113.42');
});
});
describe('requireAdminAuth', () => {
beforeEach(() => mockCheckSession.mockReset());
it('responds 401 and does not call next() when unauthenticated', async () => {
mockCheckSession.mockResolvedValue(null);
const req = makeReq({});
const res = makeRes();
const next = jest.fn();
await requireAdminAuth(req, res, next);
expect(res.status).toHaveBeenCalledWith(401);
expect(next).not.toHaveBeenCalled();
});
it('sets res.locals.admin and calls next() when authenticated', async () => {
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 res = makeRes();
const next = jest.fn();
await requireAdminAuth(req, res, next);
expect(next).toHaveBeenCalled();
expect(res.locals.admin).toEqual({id: '1', email: 'a@nachklang.art', displayName: 'Anna Admin'});
});
});
+16
View File
@@ -0,0 +1,16 @@
import {isHoneypotTriggered} from '../../src/models/feedback/public/public.router';
describe('isHoneypotTriggered', () => {
it('is false when the field is absent', () => {
expect(isHoneypotTriggered({})).toBe(false);
});
it('is false when the field is empty', () => {
expect(isHoneypotTriggered({website: ''})).toBe(false);
expect(isHoneypotTriggered({website: ' '})).toBe(false);
});
it('is true when a bot filled it in', () => {
expect(isHoneypotTriggered({website: 'https://spam.example'})).toBe(true);
});
});
@@ -0,0 +1,28 @@
// 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()
// call would silently repopulate from the repo's .env file.
jest.mock('dotenv', () => ({config: jest.fn()}));
jest.mock('../../src/models/feedback/Feedback.db', () => ({
NachklangFeedbackDB: {getConnection: jest.fn()}
}));
describe('FEEDBACK_IP_SALT enforcement', () => {
const originalSalt = process.env.FEEDBACK_IP_SALT;
afterEach(() => {
process.env.FEEDBACK_IP_SALT = originalSalt;
jest.resetModules();
});
it('throws at import time when FEEDBACK_IP_SALT is unset, rather than silently hashing unsalted', () => {
jest.resetModules();
delete process.env.FEEDBACK_IP_SALT;
expect(() => require('../../src/models/feedback/feedback.ratelimit')).toThrow(/FEEDBACK_IP_SALT/);
});
it('does not throw when FEEDBACK_IP_SALT is set', () => {
jest.resetModules();
process.env.FEEDBACK_IP_SALT = 'a-real-salt';
expect(() => require('../../src/models/feedback/feedback.ratelimit')).not.toThrow();
});
});
+20
View File
@@ -0,0 +1,20 @@
import {hashIp} from '../../src/models/feedback/feedback.ratelimit';
describe('hashIp', () => {
it('never returns the raw IP', () => {
const hash = hashIp('203.0.113.42');
expect(hash).not.toContain('203.0.113.42');
});
it('is deterministic for the same input', () => {
expect(hashIp('203.0.113.42')).toBe(hashIp('203.0.113.42'));
});
it('differs for different inputs', () => {
expect(hashIp('203.0.113.42')).not.toBe(hashIp('203.0.113.43'));
});
it('is a 64-char hex SHA-256 digest', () => {
expect(hashIp('203.0.113.42')).toMatch(/^[0-9a-f]{64}$/);
});
});
+109
View File
@@ -0,0 +1,109 @@
import {aggregateReport} from '../../src/models/feedback/admin/reports.admin.service';
import {AnswerRow} from '../../src/models/feedback/admin/reports.admin.interface';
const eventMeta = {eventId: 1, name: 'Sommerkonzert', eventDate: '2026-08-01', feedbackDeadline: '2026-08-15T23:59:59'};
const emptyNewsletter = {total: 0, sent: 0, pending: 0, failed: 0, skipped: 0};
const row = (overrides: Partial<AnswerRow>): AnswerRow => ({
submissionId: 1,
submittedAt: '2026-08-02T10:00:00.000Z',
questionId: 1,
questionLabel: 'Q',
questionType: 'FREE_TEXT',
songId: null,
songTitle: null,
rating: null,
textAnswer: null,
...overrides
});
describe('aggregateReport - song picks', () => {
it('counts votes per song and sorts by votes descending', () => {
const answers: AnswerRow[] = [
row({submissionId: 1, questionId: 5, questionLabel: 'Lieblingsstück?', questionType: 'SONG_PICK', songId: 10, songTitle: 'Abendlied'}),
row({submissionId: 2, questionId: 5, questionLabel: 'Lieblingsstück?', questionType: 'SONG_PICK', songId: 10, songTitle: 'Abendlied'}),
row({submissionId: 3, questionId: 5, questionLabel: 'Lieblingsstück?', questionType: 'SONG_PICK', songId: 11, songTitle: 'Morgenlied'})
];
const report = aggregateReport(eventMeta, {totalSubmissions: 3, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.songPicks).toHaveLength(1);
expect(report.songPicks[0].totalVotes).toBe(3);
expect(report.songPicks[0].results).toEqual([
{songId: 10, title: 'Abendlied', votes: 2},
{songId: 11, title: 'Morgenlied', votes: 1}
]);
});
it('keeps separate SONG_PICK questions in separate groups', () => {
const answers: AnswerRow[] = [
row({questionId: 5, questionLabel: 'Frage A', questionType: 'SONG_PICK', songId: 10, songTitle: 'Abendlied'}),
row({questionId: 6, questionLabel: 'Frage B', questionType: 'SONG_PICK', songId: 11, songTitle: 'Morgenlied'})
];
const report = aggregateReport(eventMeta, {totalSubmissions: 2, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.songPicks).toHaveLength(2);
});
});
describe('aggregateReport - song ratings', () => {
it('averages ratings per song, rounded to one decimal, sorted descending', () => {
const answers: AnswerRow[] = [
row({questionId: 7, questionLabel: 'Bewertung', questionType: 'SONG_RATING', songId: 10, songTitle: 'Abendlied', rating: 5}),
row({questionId: 7, questionLabel: 'Bewertung', questionType: 'SONG_RATING', songId: 10, songTitle: 'Abendlied', rating: 4}),
row({questionId: 7, questionLabel: 'Bewertung', questionType: 'SONG_RATING', songId: 11, songTitle: 'Morgenlied', rating: 3})
];
const report = aggregateReport(eventMeta, {totalSubmissions: 2, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.songRatings[0].results).toEqual([
{songId: 10, title: 'Abendlied', average: 4.5, count: 2},
{songId: 11, title: 'Morgenlied', average: 3, count: 1}
]);
});
});
describe('aggregateReport - free text', () => {
it('sorts newest first and caps at 500 with hasMore', () => {
const answers: AnswerRow[] = Array.from({length: 501}, (_, i) =>
row({
submissionId: i,
questionId: 9,
questionLabel: 'Sonstiges',
questionType: 'FREE_TEXT',
textAnswer: `Antwort ${i}`,
submittedAt: new Date(2026, 0, 1, 0, 0, i).toISOString()
})
);
const report = aggregateReport(eventMeta, {totalSubmissions: 501, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.freeText[0].responses).toHaveLength(500);
expect(report.freeText[0].hasMore).toBe(true);
expect(report.freeText[0].responses[0].text).toBe('Antwort 500');
});
it('does not set hasMore when at or under the cap', () => {
const answers: AnswerRow[] = [row({questionId: 9, questionLabel: 'Sonstiges', questionType: 'FREE_TEXT', textAnswer: 'Danke!'})];
const report = aggregateReport(eventMeta, {totalSubmissions: 1, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.freeText[0].hasMore).toBe(false);
});
});
describe('aggregateReport - top-level fields', () => {
it('passes through submission stats, guest book count, and newsletter counts unchanged', () => {
const report = aggregateReport(
eventMeta,
{totalSubmissions: 42, firstSubmissionAt: '2026-08-02T10:00:00.000Z', lastSubmissionAt: '2026-08-10T18:00:00.000Z'},
[],
7,
{total: 10, sent: 6, pending: 2, failed: 1, skipped: 1}
);
expect(report.totalSubmissions).toBe(42);
expect(report.firstSubmissionAt).toBe('2026-08-02T10:00:00.000Z');
expect(report.lastSubmissionAt).toBe('2026-08-10T18:00:00.000Z');
expect(report.guestBookCount).toBe(7);
expect(report.newsletter).toEqual({total: 10, sent: 6, pending: 2, failed: 1, skipped: 1});
expect(report.event).toEqual(eventMeta);
});
it('produces empty arrays for an event with no submissions', () => {
const report = aggregateReport(eventMeta, {totalSubmissions: 0, firstSubmissionAt: null, lastSubmissionAt: null}, [], 0, emptyNewsletter);
expect(report.songPicks).toEqual([]);
expect(report.songRatings).toEqual([]);
expect(report.freeText).toEqual([]);
});
});
+198
View File
@@ -0,0 +1,198 @@
// The module under test caches its OAuth token at module scope (see
// salesforce.service.ts's `cachedToken`), so every test resets the module
// registry for a clean cache. That also invalidates any jest.mock() factory
// instance captured before the reset, so every mocked dependency (axios,
// Feedback.db, the logger) is re-required fresh after each reset rather
// than referenced from a top-level import.
jest.mock('axios');
jest.mock('../../src/models/feedback/Feedback.db', () => ({
NachklangFeedbackDB: {getConnection: jest.fn()}
}));
jest.mock('../../src/middleware/logger', () => ({
__esModule: true,
default: {info: jest.fn(), error: jest.fn()}
}));
const SIGNUP_ROW = {
signup_id: 7,
first_name: 'Erika',
last_name: 'Mustermann',
email: 'erika@example.com',
event_name: 'Sommerkonzert 2026'
};
const makeConn = (rows: any[]) => ({
query: jest.fn().mockResolvedValue(rows),
end: jest.fn().mockResolvedValue(undefined)
});
// Re-requires every mocked dependency fresh (see the note above) and
// returns the live references plus the service under test.
const freshImports = () => {
const axios = require('axios');
const {NachklangFeedbackDB} = require('../../src/models/feedback/Feedback.db');
const logger = require('../../src/middleware/logger').default;
const {syncNewsletterSignup} = require('../../src/models/feedback/integrations/salesforce.service');
return {axios, mockGetConnection: NachklangFeedbackDB.getConnection as jest.Mock, logger, syncNewsletterSignup};
};
const ORIGINAL_ENV = {...process.env};
describe('syncNewsletterSignup - disabled mode', () => {
beforeEach(() => {
jest.resetModules();
process.env = {...ORIGINAL_ENV, SALESFORCE_ENABLED: 'false'};
});
it('logs the payload it would send and does not touch the network or write to the DB', async () => {
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
const conn = makeConn([SIGNUP_ROW]);
mockGetConnection.mockResolvedValue(conn);
await syncNewsletterSignup(7);
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining('would have sent'),
expect.objectContaining({
signupId: 7,
payload: {firstName: 'Erika', lastName: 'Mustermann', email: 'erika@example.com', eventName: 'Sommerkonzert 2026'}
})
);
expect(axios.post).not.toHaveBeenCalled();
// One read connection only - no UPDATE issued, since the row's
// sync_status is already 'SKIPPED' from the insert.
expect(mockGetConnection).toHaveBeenCalledTimes(1);
});
it('logs and returns without calling the network when the signup row does not exist', async () => {
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
mockGetConnection.mockResolvedValue(makeConn([]));
await syncNewsletterSignup(999);
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('not found'), {signupId: 999});
expect(axios.post).not.toHaveBeenCalled();
});
});
describe('syncNewsletterSignup - enabled mode', () => {
beforeEach(() => {
jest.resetModules();
process.env = {
...ORIGINAL_ENV,
SALESFORCE_ENABLED: 'true',
SALESFORCE_API_URL: 'https://example.my.salesforce.com',
SALESFORCE_CLIENT_ID: 'client-id',
SALESFORCE_CLIENT_SECRET: 'client-secret'
};
});
it('fetches a token, posts the signup, and marks the row SENT with the returned record id', async () => {
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
const updateConn = makeConn([]);
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
if (url.endsWith('/services/apexrest/newsletter/signup')) {
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q1234', created: true}});
}
throw new Error(`unexpected url ${url}`);
});
await syncNewsletterSignup(7);
expect(axios.post).toHaveBeenCalledWith(
'https://example.my.salesforce.com/services/oauth2/token',
expect.any(String),
expect.objectContaining({headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
);
expect(axios.post).toHaveBeenCalledWith(
'https://example.my.salesforce.com/services/apexrest/newsletter/signup',
{firstName: 'Erika', lastName: 'Mustermann', email: 'erika@example.com', eventName: 'Sommerkonzert 2026'},
expect.objectContaining({headers: {Authorization: 'Bearer tok-1'}})
);
expect(updateConn.query).toHaveBeenCalledWith(expect.stringContaining("sync_status = 'SENT'"), ['00Q1234', 7]);
});
it('reuses the cached token across two calls instead of fetching twice', async () => {
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
mockGetConnection
.mockResolvedValueOnce(makeConn([SIGNUP_ROW]))
.mockResolvedValueOnce(makeConn([]))
.mockResolvedValueOnce(makeConn([SIGNUP_ROW]))
.mockResolvedValueOnce(makeConn([]));
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q1234', created: true}});
});
await syncNewsletterSignup(7);
await syncNewsletterSignup(7);
const tokenCalls = axios.post.mock.calls.filter(([url]: [string]) => url.endsWith('/services/oauth2/token'));
expect(tokenCalls).toHaveLength(1);
});
it('retries once with a fresh token on a 401, then succeeds', async () => {
const {axios, mockGetConnection, syncNewsletterSignup} = freshImports();
const updateConn = makeConn([]);
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
let tokenFetches = 0;
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) {
tokenFetches += 1;
return Promise.resolve({data: {access_token: `tok-${tokenFetches}`}});
}
if (url.endsWith('/services/apexrest/newsletter/signup')) {
if (tokenFetches === 1) {
const err: any = new Error('Unauthorized');
err.response = {status: 401, data: {message: 'Session expired'}};
return Promise.reject(err);
}
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q9999', created: true}});
}
throw new Error(`unexpected url ${url}`);
});
await syncNewsletterSignup(7);
expect(tokenFetches).toBe(2);
expect(updateConn.query).toHaveBeenCalledWith(expect.stringContaining("sync_status = 'SENT'"), ['00Q9999', 7]);
});
it('marks the row FAILED with the error message on a non-401 error, without throwing', async () => {
const {axios, mockGetConnection, logger, syncNewsletterSignup} = freshImports();
const updateConn = makeConn([]);
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
const err: any = new Error('Internal error');
err.response = {status: 500, data: {message: 'The newsletter signup could not be processed.'}};
return Promise.reject(err);
});
await expect(syncNewsletterSignup(7)).resolves.toBeUndefined();
expect(updateConn.query).toHaveBeenCalledWith(
expect.stringContaining("sync_status = 'FAILED'"),
['The newsletter signup could not be processed.', 7]
);
expect(logger.error).toHaveBeenCalledWith('syncNewsletterSignup failed', expect.objectContaining({signupId: 7}));
});
it('marks the row FAILED with a clear message when client credentials are not configured', async () => {
process.env.SALESFORCE_CLIENT_ID = '';
const {mockGetConnection, syncNewsletterSignup} = freshImports();
const updateConn = makeConn([]);
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
await syncNewsletterSignup(7);
expect(updateConn.query).toHaveBeenCalledWith(
expect.stringContaining("sync_status = 'FAILED'"),
[expect.stringContaining('SALESFORCE_CLIENT_ID'), 7]
);
});
});
+151
View File
@@ -0,0 +1,151 @@
import {MAX_ANSWER_ROWS, validateAnswers, validateGuestBook, validateNewsletter} from '../../src/models/feedback/public/submissions.service';
type QuestionLookup = Map<number, {eventQuestionId: number; questionId: number; type: 'SONG_PICK' | 'SONG_RATING' | 'FREE_TEXT'; label: string; position: number}>;
const songTitleById = new Map<number, string>([
[1, 'Abendlied'],
[2, 'Morgenlied']
]);
describe('validateAnswers', () => {
const questionsById: QuestionLookup = new Map([
[10, {eventQuestionId: 10, questionId: 100, type: 'SONG_PICK', label: 'Lieblingsstück?', position: 0}],
[11, {eventQuestionId: 11, questionId: 101, type: 'SONG_RATING', label: 'Bewertung', position: 1}],
[12, {eventQuestionId: 12, questionId: 102, type: 'FREE_TEXT', label: 'Sonstiges', position: 2}]
]);
it('produces a row for a valid SONG_PICK answer', () => {
const rows = validateAnswers([{eventQuestionId: 10, songId: 1}], questionsById, songTitleById);
expect(rows).toEqual([
{eventQuestionId: 10, questionId: 100, label: 'Lieblingsstück?', type: 'SONG_PICK', position: 0, songId: 1, songTitle: 'Abendlied', rating: null, text: null}
]);
});
it('ignores a SONG_PICK answer with an unknown songId', () => {
const rows = validateAnswers([{eventQuestionId: 10, songId: 999}], questionsById, songTitleById);
expect(rows).toHaveLength(0);
});
it('ignores an answer for an unknown eventQuestionId', () => {
const rows = validateAnswers([{eventQuestionId: 999, songId: 1}], questionsById, songTitleById);
expect(rows).toHaveLength(0);
});
it('produces one row per rated song for SONG_RATING, ignoring unknown songs', () => {
const rows = validateAnswers([
{eventQuestionId: 11, ratings: [{songId: 1, rating: 5}, {songId: 2, rating: 3}, {songId: 999, rating: 4}]}
], questionsById, songTitleById);
expect(rows).toHaveLength(2);
expect(rows.map(r => r.songId)).toEqual([1, 2]);
});
it('clamps ratings to the 1..5 range', () => {
const rows = validateAnswers([
{eventQuestionId: 11, ratings: [{songId: 1, rating: 9}, {songId: 2, rating: -3}]}
], questionsById, songTitleById);
expect(rows.find(r => r.songId === 1)?.rating).toBe(5);
expect(rows.find(r => r.songId === 2)?.rating).toBe(1);
});
it('an unrated song in a SONG_RATING block produces no row', () => {
const rows = validateAnswers([{eventQuestionId: 11, ratings: []}], questionsById, songTitleById);
expect(rows).toHaveLength(0);
});
it('trims FREE_TEXT and drops it if empty after trimming', () => {
const withText = validateAnswers([{eventQuestionId: 12, text: ' Danke für den Abend! '}], questionsById, songTitleById);
expect(withText[0].text).toBe('Danke für den Abend!');
const blank = validateAnswers([{eventQuestionId: 12, text: ' '}], questionsById, songTitleById);
expect(blank).toHaveLength(0);
});
it('caps FREE_TEXT at 5000 characters', () => {
const long = 'a'.repeat(6000);
const rows = validateAnswers([{eventQuestionId: 12, text: long}], questionsById, songTitleById);
expect(rows[0].text).toHaveLength(5000);
});
it('a fully empty answer set produces no rows (skipped questions produce no rows)', () => {
const rows = validateAnswers([], questionsById, songTitleById);
expect(rows).toHaveLength(0);
});
it('de-duplicates repeated ratings for the same song, keeping the last value', () => {
const rows = validateAnswers([
{eventQuestionId: 11, ratings: [{songId: 1, rating: 2}, {songId: 1, rating: 5}, {songId: 1, rating: 3}]}
], questionsById, songTitleById);
expect(rows).toHaveLength(1);
expect(rows[0].rating).toBe(3);
});
it('caps total generated rows at MAX_ANSWER_ROWS regardless of how many ratings are submitted', () => {
const massRatings = Array.from({length: MAX_ANSWER_ROWS + 500}, (_, i) => ({
songId: 1,
rating: (i % 5) + 1
}));
// Force distinct songIds so de-duplication alone can't be the thing capping the count.
const distinctSongTitleById = new Map<number, string>(
Array.from({length: MAX_ANSWER_ROWS + 500}, (_, i) => [i, `Song ${i}`])
);
const distinctRatings = massRatings.map((r, i) => ({songId: i, rating: r.rating}));
const rows = validateAnswers(
[{eventQuestionId: 11, ratings: distinctRatings}],
questionsById,
distinctSongTitleById
);
expect(rows.length).toBe(MAX_ANSWER_ROWS);
});
it('stops adding rows across multiple answers once the cap is reached', () => {
const distinctSongTitleById = new Map<number, string>(
Array.from({length: MAX_ANSWER_ROWS + 10}, (_, i) => [i, `Song ${i}`])
);
const answers = Array.from({length: MAX_ANSWER_ROWS + 10}, (_, i) => ({
eventQuestionId: 10,
songId: i
}));
// SONG_PICK only ever produces 0 or 1 row per answer entry, so this
// exercises the cap across many separate answers, not one big array.
const rows = validateAnswers(answers, questionsById, distinctSongTitleById);
expect(rows.length).toBe(MAX_ANSWER_ROWS);
});
});
describe('validateGuestBook', () => {
it('returns null when nothing was filled in', () => {
expect(validateGuestBook(undefined)).toBeNull();
expect(validateGuestBook({displayName: ' ', message: ' '})).toBeNull();
});
it('keeps a valid entry with only a display name', () => {
expect(validateGuestBook({displayName: 'Familie Müller'})).toEqual({displayName: 'Familie Müller', message: null});
});
it('caps the message at 2000 characters', () => {
const long = 'x'.repeat(3000);
const result = validateGuestBook({message: long});
expect(result?.message).toHaveLength(2000);
});
});
describe('validateNewsletter', () => {
it('returns null when the object is missing', () => {
expect(validateNewsletter(undefined)).toBeNull();
});
it('drops the signup silently when the email is invalid', () => {
expect(validateNewsletter({firstName: 'Anna', lastName: 'Beispiel', email: 'not-an-email'})).toBeNull();
});
it('drops the signup when first or last name is missing', () => {
expect(validateNewsletter({firstName: '', lastName: 'Beispiel', email: 'a@b.de'})).toBeNull();
expect(validateNewsletter({firstName: 'Anna', lastName: '', email: 'a@b.de'})).toBeNull();
});
it('accepts a fully valid signup', () => {
expect(validateNewsletter({firstName: 'Anna', lastName: 'Beispiel', email: 'anna@beispiel.de'})).toEqual({
firstName: 'Anna', lastName: 'Beispiel', email: 'anna@beispiel.de'
});
});
});