feat(donations): public dropoff announcement form — backend (route + schema + emails + tests)

First half of the Proposed-T1 donation drop-off form. The donate page
currently has a bank-transfer block + a static address box; a donor
who wants to bring devices has no structured way to announce intent
other than a mailto: link tucked under the address. This route gives
them a real path.

Shape mirrors /api/inquiry exactly — rate-limited, Zod-validated, two
fire-and-forget emails (notification to CONTACT.email + confirmation
to the donor). No DB persist on the public side: a drop-off
announcement is an *intent*, not a recorded donation. Staff records
the actual donation in /admin/donations once devices physically
arrive, so we avoid forcing dedup of every visitor-typed device list.

- DonationDropoffSchema accepts name + email + devices (required) +
  phone + preferredDate (YYYY-MM-DD) + notes (optional). Trimmed,
  bounded lengths, no defaults beyond optional fields.
- donationDropoffNotification / donationDropoffConfirmation templates
  follow the inquiry template pattern — every user-supplied field
  escaped before HTML interpolation.
- 8 route tests lock auth (none — public), validation (4 cases),
  rate-limit, the recipient routing (admin vs donor), and the
  fire-and-forget guarantee (rejected sendCustomEmail still returns 200).
- 8 schema tests lock the optional fields and the validation bounds.

Frontend form + page integration follow in the next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-05-31 03:07:28 +02:00
1 parent 3e937caf92
commit 2eed49637c
6 files changed
+412

No files matched your search

@@ -0,0 +1,146 @@
/**
* @jest-environment node
*
* Tests for POST /api/donations/dropoff
*
* Behaviors locked:
* - 200 on valid dropoff announcement, both emails sent
* - 400 on invalid input (missing required fields)
* - 429 when rate limit is exceeded
* - confirmation goes to the donor, notification to CONTACT.email
* - emails are fire-and-forget — a rejected sendCustomEmail still returns 200
*/
const mockCheckRateLimit = jest.fn()
const mockGetClientIp = jest.fn().mockReturnValue('127.0.0.1')
jest.mock('@/lib/auth/rate-limiter', () => ({
checkRateLimit: (...args: unknown[]) => mockCheckRateLimit.apply(null, args),
getClientIp: (...args: unknown[]) => mockGetClientIp.apply(null, args),
}))
const mockSendCustomEmail = jest.fn().mockResolvedValue(undefined)
jest.mock('@/lib/email', () => ({
sendCustomEmail: (...args: unknown[]) => mockSendCustomEmail.apply(null, args),
}))
jest.mock('@/lib/email/templates/donation-dropoff', () => ({
donationDropoffNotification: jest.fn().mockReturnValue({ subject: 'Notification', html: '', text: '' }),
donationDropoffConfirmation: jest.fn().mockReturnValue({ subject: 'Confirmation', html: '', text: '' }),
}))
jest.mock('@/config/org', () => ({
CONTACT: { email: 'kontakt@revamp-it.ch' },
}))
jest.mock('@/lib/logger', () => ({
logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
}))
jest.mock('@/lib/api/helpers', () => {
const { NextResponse } = jest.requireActual('next/server')
return {
apiSuccess: (data: unknown) => NextResponse.json({ success: true, data }),
apiBadRequest: (msg: string, details?: unknown) =>
NextResponse.json({ success: false, error: msg, details }, { status: 400 }),
apiError: (_err: unknown, msg: string, status = 500) =>
NextResponse.json({ success: false, error: msg }, { status }),
apiRateLimited: (msg: string) => NextResponse.json({ success: false, error: msg }, { status: 429 }),
}
})
jest.mock('@/config/error-messages', () => ({
ERROR_MESSAGES: {
RATE_LIMITED: 'Zu viele Anfragen',
INVALID_INPUT: 'Ungültige Eingabe',
},
}))
import { NextRequest } from 'next/server'
import { POST } from '../route'
const VALID_BODY = {
name: 'Anna Müller',
email: 'anna@example.com',
phone: '+41 79 123 45 67',
preferredDate: '2026-06-15',
devices: 'Zwei alte ThinkPads + ein Monitor',
notes: 'Akku vom Laptop ist defekt',
}
function makeRequest(body: unknown) {
return new NextRequest('http://localhost/api/donations/dropoff', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
}
beforeEach(() => {
jest.clearAllMocks()
mockGetClientIp.mockReturnValue('127.0.0.1')
mockCheckRateLimit.mockReturnValue({ allowed: true, retryAfter: 0, remaining: 10, resetAt: 0 })
mockSendCustomEmail.mockResolvedValue(undefined)
})
describe('POST /api/donations/dropoff', () => {
it('returns 200 on a valid full submission', async () => {
const res = await POST(makeRequest(VALID_BODY))
expect(res.status).toBe(200)
const body = await res.json()
expect(body.success).toBe(true)
})
it('sends notification to CONTACT.email and confirmation to the donor', async () => {
await POST(makeRequest(VALID_BODY))
expect(mockSendCustomEmail).toHaveBeenCalledTimes(2)
const firstRecipient = (mockSendCustomEmail.mock.calls[0] as [string, unknown])[0]
const secondRecipient = (mockSendCustomEmail.mock.calls[1] as [string, unknown])[0]
expect(firstRecipient).toBe('kontakt@revamp-it.ch')
expect(secondRecipient).toBe('anna@example.com')
})
it('accepts a minimal valid submission (optional fields omitted)', async () => {
const res = await POST(
makeRequest({
name: 'Beat',
email: 'beat@example.com',
devices: 'Ein alter Drucker, ein Bildschirm',
}),
)
expect(res.status).toBe(200)
})
it('returns 400 when name is missing', async () => {
const res = await POST(makeRequest({ ...VALID_BODY, name: undefined }))
expect(res.status).toBe(400)
})
it('returns 400 when email is invalid', async () => {
const res = await POST(makeRequest({ ...VALID_BODY, email: 'not-an-email' }))
expect(res.status).toBe(400)
})
it('returns 400 when devices description is too short', async () => {
const res = await POST(makeRequest({ ...VALID_BODY, devices: 'kurz' }))
expect(res.status).toBe(400)
})
it('returns 400 when preferredDate is not YYYY-MM-DD', async () => {
const res = await POST(makeRequest({ ...VALID_BODY, preferredDate: '15/06/2026' }))
expect(res.status).toBe(400)
})
it('returns 429 when rate-limit blocks the request', async () => {
mockCheckRateLimit.mockReturnValueOnce({ allowed: false, retryAfter: 60, remaining: 0, resetAt: 0 })
const res = await POST(makeRequest(VALID_BODY))
expect(res.status).toBe(429)
})
it('still returns 200 when sendCustomEmail rejects (fire-and-forget)', async () => {
mockSendCustomEmail.mockRejectedValue(new Error('SMTP down'))
const res = await POST(makeRequest(VALID_BODY))
expect(res.status).toBe(200)
})
})
+63
View File
@@ -0,0 +1,63 @@
/**
* POST /api/donations/dropoff — public donation drop-off announcement
*
* Mirrors the inquiry route shape (rate-limited, validated, two fire-and-
* forget emails). No DB persist here: a drop-off announcement is an intent,
* not a recorded donation — staff records the actual donation in
* /admin/donations once the devices physically arrive. Keeping the public
* route emails-only avoids forcing staff to deduplicate every donation row
* against the visitor-typed device list.
*/
import { NextRequest } from 'next/server'
import { apiError, apiSuccess, apiBadRequest, apiRateLimited } from '@/lib/api/helpers'
import { ERROR_MESSAGES } from '@/config/error-messages'
import { logger } from '@/lib/logger'
import { checkRateLimit, getClientIp } from '@/lib/auth/rate-limiter'
import { sendCustomEmail } from '@/lib/email'
import {
donationDropoffNotification,
donationDropoffConfirmation,
} from '@/lib/email/templates/donation-dropoff'
import { CONTACT } from '@/config/org'
import { DonationDropoffSchema } from '@/lib/schemas/donations'
export async function POST(request: NextRequest) {
try {
const clientIp = getClientIp(request.headers)
const rateLimit = checkRateLimit(clientIp, 'submission')
if (!rateLimit.allowed) {
return apiRateLimited(ERROR_MESSAGES.RATE_LIMITED, {
retryAfter: rateLimit.retryAfter,
remaining: rateLimit.remaining,
resetAt: rateLimit.resetAt,
})
}
const body = await request.json()
const result = DonationDropoffSchema.safeParse(body)
if (!result.success) {
return apiBadRequest(ERROR_MESSAGES.INVALID_INPUT, result.error.flatten().fieldErrors)
}
const fields = result.data
// Both emails fire-and-forget so a transient SMTP failure doesn't
// surface as a 500 to a donor who just filled out the form correctly.
sendCustomEmail(
CONTACT.email,
donationDropoffNotification(fields),
).catch(err => logger.warn('Failed to send donation drop-off notification', { error: err, donorEmail: fields.email }))
sendCustomEmail(
fields.email,
donationDropoffConfirmation(fields),
).catch(err => logger.warn('Failed to send donation drop-off confirmation', { error: err, donorEmail: fields.email }))
logger.info('Donation drop-off announced', { donorEmail: fields.email, hasPreferredDate: !!fields.preferredDate })
return apiSuccess({ message: 'Anmeldung erhalten' })
} catch (error) {
return apiError(error, 'Fehler beim Senden der Anmeldung')
}
}
+114
View File
@@ -0,0 +1,114 @@
/**
* Donation drop-off email templates
*
* Public donate page (/get-involved/donate) lets visitors announce a
* device drop-off via a structured form instead of the legacy mailto
* link. The route sends both emails fire-and-forget — neither failure
* blocks the form submission, but staff need the notification to act.
*
* Persistence model: we intentionally do NOT insert into the donations
* table here. A drop-off announcement is an *intent* — the donation
* itself gets recorded by staff in /admin/donations once the device
* physically arrives. Mirroring the inquiry route's "emails-only"
* shape keeps both paths reviewable as one pattern.
*/
import type { EmailContent } from '../types'
import { createEmailLayout, createTextFooter } from './base-styles'
import { ORG, LOCATIONS, OPENING_HOURS } from '@/config/org'
import { escapeHtml } from '@/lib/utils/escape-html'
interface DropoffFields {
name: string
email: string
phone?: string
preferredDate?: string
devices: string
notes?: string
}
/**
* Notification to staff — someone announced a device drop-off.
*/
export const donationDropoffNotification = (fields: DropoffFields): EmailContent => {
// Every interpolated field is attacker-controlled — escape before HTML.
const eName = escapeHtml(fields.name)
const eEmail = escapeHtml(fields.email)
const ePhone = fields.phone ? escapeHtml(fields.phone) : ''
const eDate = fields.preferredDate ? escapeHtml(fields.preferredDate) : ''
const eDevicesHtml = escapeHtml(fields.devices).replace(/\n/g, '<br>')
const eNotesHtml = fields.notes ? escapeHtml(fields.notes).replace(/\n/g, '<br>') : ''
const optionalRow = (label: string, value: string) =>
value
? `<tr><td style="padding:8px; font-weight:bold; width:140px;">${label}</td><td style="padding:8px;">${value}</td></tr>`
: ''
return {
subject: `Geräte-Abgabe angemeldet — ${fields.name}`,
html: createEmailLayout(
'Neue Geräte-Abgabe',
'header-green',
`
<p>Jemand möchte Geräte spenden:</p>
<table style="width:100%; border-collapse:collapse; margin:20px 0;">
<tr><td style="padding:8px; font-weight:bold; width:140px;">Name</td><td style="padding:8px;">${eName}</td></tr>
<tr style="background:#f3f4f6;"><td style="padding:8px; font-weight:bold;">E-Mail</td><td style="padding:8px;"><a href="mailto:${eEmail}">${eEmail}</a></td></tr>
${optionalRow('Telefon', ePhone)}
${optionalRow('Bevorzugter Termin', eDate)}
</table>
<p><strong>Geräte:</strong></p>
<div style="background:#f9fafb; border-left:4px solid #22c55e; padding:16px; margin:12px 0; border-radius:4px;">
${eDevicesHtml}
</div>
${eNotesHtml ? `<p><strong>Anmerkungen:</strong></p><div style="background:#f9fafb; border-left:4px solid #22c55e; padding:16px; margin:12px 0; border-radius:4px;">${eNotesHtml}</div>` : ''}
<p style="margin-top:24px;">
<a href="mailto:${eEmail}" class="button button-green">Direkt antworten</a>
</p>
`,
),
text: `Neue Geräte-Abgabe\n\nName: ${fields.name}\nE-Mail: ${fields.email}\n${fields.phone ? `Telefon: ${fields.phone}\n` : ''}${fields.preferredDate ? `Bevorzugter Termin: ${fields.preferredDate}\n` : ''}\nGeräte:\n${fields.devices}\n${fields.notes ? `\nAnmerkungen:\n${fields.notes}\n` : ''}\n${createTextFooter()}`,
}
}
/**
* Confirmation to the donor — we received their announcement.
*/
export const donationDropoffConfirmation = (fields: DropoffFields): EmailContent => {
const eName = escapeHtml(fields.name)
const eDevicesHtml = escapeHtml(fields.devices).replace(/\n/g, '<br>')
const dateLine = fields.preferredDate
? `<p>Bevorzugter Termin: <strong>${escapeHtml(fields.preferredDate)}</strong>.</p>`
: ''
return {
subject: `Vielen Dank für deine Geräte-Spende-Anmeldung bei ${ORG.name}`,
html: createEmailLayout(
'Wir haben deine Anmeldung erhalten',
'header-green',
`
<p>Hallo ${eName},</p>
<p>vielen Dank, dass du ${ORG.name} Geräte spenden möchtest! Wir haben deine Anmeldung erhalten.</p>
${dateLine}
<p><strong>Du hast angegeben:</strong></p>
<div style="background:#f9fafb; border-left:4px solid #22c55e; padding:16px; margin:12px 0; border-radius:4px;">
${eDevicesHtml}
</div>
<div class="highlight-box">
<strong>So geht es weiter:</strong>
<ul style="margin:8px 0; padding-left:20px;">
<li>Wir prüfen deine Anmeldung und melden uns in der Regel innerhalb weniger Werktage.</li>
<li>Falls dein Wunschtermin nicht passt oder wir Rückfragen haben, kontaktieren wir dich direkt.</li>
<li>Anschliessend kannst du die Geräte zu unseren Öffnungszeiten vorbeibringen.</li>
</ul>
</div>
<p><strong>Abgabeort:</strong><br>
${ORG.name} ${LOCATIONS.store.name}<br>
${LOCATIONS.store.full}<br>
${OPENING_HOURS.compact}</p>
<p>Bis bald!<br>Das ${ORG.name} Team</p>
`,
),
text: `Hallo ${fields.name},\n\nvielen Dank für deine Geräte-Spende-Anmeldung bei ${ORG.name}!\n\n${fields.preferredDate ? `Bevorzugter Termin: ${fields.preferredDate}\n\n` : ''}Du hast angegeben:\n${fields.devices}\n\nWir melden uns in Kürze bei dir.\n\nAbgabeort: ${LOCATIONS.store.full} (${OPENING_HOURS.compact})\n\n${createTextFooter()}`,
}
}
+3
View File
@@ -111,6 +111,9 @@ export { notificationEmail } from './notification';
// Inquiry (Mitmachen contact form)
export { inquiryNotification, inquiryConfirmation } from './inquiry';
// Donation drop-off announcement (public donate page form)
export { donationDropoffNotification, donationDropoffConfirmation } from './donation-dropoff';
// Referral / invitation templates
export { referralInvitation, referralCouponReceived } from './referral';
@@ -16,6 +16,7 @@ import {
CreateDonationSchema,
UpdateDonationSchema,
GetDonationsQuerySchema,
DonationDropoffSchema,
} from '../donations'
import {
@@ -394,3 +395,65 @@ describe('GetDonationsQuerySchema', () => {
expect(result.success).toBe(false)
})
})
// ============================================================================
// DonationDropoffSchema (public donate-page form)
// ============================================================================
describe('DonationDropoffSchema', () => {
const MIN_VALID = {
name: 'Anna Müller',
email: 'anna@example.com',
devices: 'Zwei alte ThinkPads und ein Monitor',
}
it('accepts a minimal valid submission', () => {
expect(DonationDropoffSchema.safeParse(MIN_VALID).success).toBe(true)
})
it('accepts a full submission with all optional fields', () => {
const result = DonationDropoffSchema.safeParse({
...MIN_VALID,
phone: '+41 79 123 45 67',
preferredDate: '2026-06-15',
notes: 'Akku ist defekt, sonst läuft alles',
})
expect(result.success).toBe(true)
})
it('trims name and devices', () => {
const result = DonationDropoffSchema.safeParse({
...MIN_VALID,
name: ' Anna ',
devices: ' Zwei alte ThinkPads und ein Monitor ',
})
expect(result.success).toBe(true)
if (!result.success) return
expect(result.data.name).toBe('Anna')
expect(result.data.devices).toBe('Zwei alte ThinkPads und ein Monitor')
})
it('rejects a name shorter than 2 chars', () => {
expect(DonationDropoffSchema.safeParse({ ...MIN_VALID, name: 'A' }).success).toBe(false)
})
it('rejects an invalid email', () => {
expect(DonationDropoffSchema.safeParse({ ...MIN_VALID, email: 'not-an-email' }).success).toBe(false)
})
it('rejects a devices description shorter than 10 chars', () => {
expect(DonationDropoffSchema.safeParse({ ...MIN_VALID, devices: 'kurz' }).success).toBe(false)
})
it('rejects a preferredDate not in YYYY-MM-DD format', () => {
expect(
DonationDropoffSchema.safeParse({ ...MIN_VALID, preferredDate: '15/06/2026' }).success,
).toBe(false)
})
it('rejects notes over 2000 chars', () => {
expect(
DonationDropoffSchema.safeParse({ ...MIN_VALID, notes: 'x'.repeat(2001) }).success,
).toBe(false)
})
})
+23
View File
@@ -100,6 +100,29 @@ export const CreateDonationSchema = z.discriminatedUnion('donation_type', [
CreateDeviceDonationSchema,
])
/**
* Public donation drop-off announcement (form on /get-involved/donate).
*
* Different shape from CreateDeviceDonationSchema on purpose: this is an
* *intent* form (donor says "I plan to bring you devices"), not the
* admin-side record of a physically-received donation. We collect just
* enough for staff to follow up — fewer required fields = higher form
* completion vs. the full structured device-category-and-condition flow.
*
* preferredDate is an ISO date string (YYYY-MM-DD), validated loosely
* because we don't gate scheduling on it — staff coordinates via email.
*/
export const DonationDropoffSchema = z.object({
name: z.string().trim().min(2, 'Name muss mindestens 2 Zeichen haben').max(200),
email: z.string().email('Ungültige E-Mail-Adresse'),
phone: z.string().trim().min(3).max(30).optional(),
preferredDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Datum im Format YYYY-MM-DD').optional(),
devices: z.string().trim().min(10, 'Bitte beschreibe, welche Geräte du bringen möchtest (mind. 10 Zeichen)').max(1000),
notes: z.string().trim().max(2000).optional(),
})
export type DonationDropoffInput = z.infer<typeof DonationDropoffSchema>
/**
* Schema for updating a donation
*/