app: uploaded images for announcements, campaigns and events (APP-1.0-PLAN §10)
Photos (JPEG, PNG, WebP, checked by their bytes) uploaded in the admin are turned upright, stripped of their metadata and kept at most 2000 px wide in backend/uploads (UPLOAD_DIR), served at /api/uploads (never a listing, a sandboxing CSP). Content keeps the image's full address, so an upload and an image from elsewhere work alike. 5 GB included or the licence's storage limit; an image still in use can't be deleted. The announcement, campaign and event forms get Upload a photo next to the address. Migration media. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,3 +3,5 @@ dist/
|
||||
src/generated/
|
||||
.env
|
||||
/backups/
|
||||
# images uploaded in the admin (media/media.ts)
|
||||
/uploads/
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
"express": "^5.3.0",
|
||||
"nodemailer": "^10.3.0",
|
||||
"pg-boss": "^11.1.2",
|
||||
"sharp": "^0.35.5",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Church App 1.0.0: uploads (docs/APP-1.0-PLAN.md §10): images uploaded in the admin.
|
||||
-- CreateTable
|
||||
CREATE TABLE "MediaAsset" (
|
||||
"id" TEXT NOT NULL,
|
||||
"filename" TEXT NOT NULL,
|
||||
"mime" TEXT NOT NULL,
|
||||
"bytes" INTEGER NOT NULL,
|
||||
"width" INTEGER,
|
||||
"height" INTEGER,
|
||||
"alt" TEXT NOT NULL DEFAULT '',
|
||||
"uploadedBy" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MediaAsset_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MediaAsset_filename_key" ON "MediaAsset"("filename");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "MediaAsset_createdAt_idx" ON "MediaAsset"("createdAt");
|
||||
|
||||
@@ -332,6 +332,26 @@ model NotificationSettings {
|
||||
|
||||
/// Messages sent per local day and channel, for the heartbeat (`messages.email30d`, `whatsapp30d`).
|
||||
/// Counts only: kept when a member or their messages are deleted. `key` is `<day>:<channel>`.
|
||||
// ── Uploads (§10) ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// An image uploaded in the admin (announcements, campaigns, events), kept in backend/uploads and
|
||||
/// served at /api/uploads/<filename>: turned upright, stripped of its metadata (a phone photo can
|
||||
/// carry where it was taken), at most 2000 px wide.
|
||||
model MediaAsset {
|
||||
id String @id @default(uuid())
|
||||
/// YYYY/MM/<uuid>.<ext>, under the uploads folder.
|
||||
filename String @unique
|
||||
mime String
|
||||
bytes Int
|
||||
width Int?
|
||||
height Int?
|
||||
alt String @default("")
|
||||
uploadedBy String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model MessageCount {
|
||||
key String @id
|
||||
day String
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
* GET /jobs, PUT /jobs/:name { enabled?, cron? }, POST /jobs/:name/run Background jobs
|
||||
* GET /audit?before= the audit log; GET /access?before= the access log
|
||||
* GET /share, POST /share the App's link (and the poster), and "shared" for the checklist
|
||||
* GET /media, POST /media?alt= (the image's bytes), DELETE /media/:id uploaded images (anyone who
|
||||
* writes content: Content admin, Devotional writer, Prayer coordinator)
|
||||
*/
|
||||
import express, { type Request } from 'express';
|
||||
import { z } from 'zod';
|
||||
@@ -31,6 +33,7 @@ import { wallDay } from '../prayer/service.js';
|
||||
import { wallSettings } from '../prayer/wall.js';
|
||||
import { accessLogList, auditLog } from './logs.js';
|
||||
import { addMember, listMembers, setRoles } from './members.js';
|
||||
import { deleteMedia, listMedia, MAX_UPLOAD_BYTES, upload } from '../media/media.js';
|
||||
|
||||
const modulesBody = z.object(Object.fromEntries(APP_MODULES.map((m) => [m, z.boolean().optional()]))).strict();
|
||||
|
||||
@@ -156,6 +159,21 @@ export function adminRouter(ctx: Ctx) {
|
||||
r.get('/audit', full, handle(async (req) => ({ entries: await auditLog(ctx, { before: before(req) }) })));
|
||||
r.get('/access', full, handle(async (req) => ({ entries: await accessLogList(ctx, { before: before(req) }) })));
|
||||
|
||||
// ─── Uploaded images ───
|
||||
const writers = requireRole(ctx, ['content_admin', 'devotional_writer', 'prayer_coordinator']);
|
||||
r.get('/media', writers, handle(() => listMedia(ctx)));
|
||||
r.post('/media', writers, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle(async (req, res) => {
|
||||
const out = await upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), typeof req.query.alt === 'string' ? req.query.alt : '', req.signed!.member.id);
|
||||
await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'media_uploaded', targetType: 'media', targetId: out.id, metadata: { bytes: out.bytes }, ip: clientIp(req) });
|
||||
res.status(201);
|
||||
return out;
|
||||
}));
|
||||
r.delete('/media/:id', writers, handle(async (req) => {
|
||||
const m = await deleteMedia(ctx, String(req.params.id));
|
||||
await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'media_deleted', targetType: 'media', targetId: m.id, metadata: { name: m.filename }, ip: clientIp(req) });
|
||||
return { ok: true };
|
||||
}));
|
||||
|
||||
// ─── Share the App ───
|
||||
r.get('/share', full, handle(async () => {
|
||||
const profile = await churchProfile(ctx);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* rest to Next.js.
|
||||
*
|
||||
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
|
||||
* /api/uploads/… images uploaded in the admin (media/media.ts)
|
||||
* /api/v1/app the church, its colours and style, the modules on (public)
|
||||
* /api/auth/… signing in through the church's Accounts
|
||||
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
|
||||
@@ -23,6 +24,7 @@
|
||||
* /api/v1/admin/messaging Settings → Email and WhatsApp: the church's settings from Accounts, Send a test
|
||||
* /api/accounts/v1/messaging-changed Accounts: the email or WhatsApp settings changed (links/routes.ts)
|
||||
*/
|
||||
import path from 'node:path';
|
||||
import express from 'express';
|
||||
import type { Ctx } from './context.js';
|
||||
import { adminRouter } from './admin/routes.js';
|
||||
@@ -37,6 +39,7 @@ import { prayerRouter } from './prayer/routes.js';
|
||||
import { requestsAdminRouter, requestsRouter } from './requests/routes.js';
|
||||
import { contentAdminRouter, contentRouter } from './content/routes.js';
|
||||
import { messagingAdminRouter, notificationsRouter } from './messaging/routes.js';
|
||||
import { uploadDir } from './media/media.js';
|
||||
|
||||
export function createApp(ctx: Ctx) {
|
||||
const app = express();
|
||||
@@ -62,6 +65,12 @@ export function createApp(ctx: Ctx) {
|
||||
return appInfo(ctx);
|
||||
}));
|
||||
|
||||
// Uploaded images: never a directory listing, never outside the folder (express.static checks).
|
||||
app.use('/api/uploads', express.static(path.resolve(uploadDir(ctx)), {
|
||||
index: false, dotfiles: 'deny', fallthrough: false, maxAge: '30d', immutable: true,
|
||||
setHeaders: (res) => { res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox"); },
|
||||
}));
|
||||
|
||||
app.use('/api', authRouter(ctx));
|
||||
app.use('/api', linksRouter(ctx));
|
||||
app.use('/api', prayerRouter(ctx));
|
||||
|
||||
@@ -28,6 +28,12 @@ export type Config = {
|
||||
sessionDays: number;
|
||||
/** ... up to this many days from the sign-in (decision 7: 90). */
|
||||
sessionMaxDays: number;
|
||||
/** Where uploaded images are kept (UPLOAD_DIR; backend/uploads by default). */
|
||||
uploadDir: string | null;
|
||||
/** Where backups go (backend/backups; tests set their own). */
|
||||
backupDir: string | null;
|
||||
/** The database, for pg_dump (backups). */
|
||||
databaseUrl: string | null;
|
||||
};
|
||||
|
||||
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
|
||||
@@ -64,5 +70,8 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
sessionDays: Math.min(sessionMaxDays, Math.max(1, Number(env.SESSION_DAYS) || 8)),
|
||||
sessionMaxDays,
|
||||
uploadDir: env.UPLOAD_DIR?.trim() || null,
|
||||
backupDir: null,
|
||||
databaseUrl: env.DATABASE_URL?.trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Uploaded images (APP-1.0-PLAN §10, as the Website's media library, smaller): photos for
|
||||
* announcements, campaigns and events, as JPEG, PNG or WebP, checked by their bytes, not their
|
||||
* name. Each is turned upright, **stripped of its metadata** (a phone photo can carry where it was
|
||||
* taken) and kept at most 2000 px wide, in backend/uploads (UPLOAD_DIR), served at
|
||||
* /api/uploads/<filename> (app.ts). Content keeps the image's full address, so an upload and an
|
||||
* image from elsewhere work the same; the export (§11) and backups know an upload by its address.
|
||||
*
|
||||
* Storage: 5 GB included, or the licence's `limits.storageBytes`. When it's full, uploads stop;
|
||||
* what's there keeps showing. An image in use can't be deleted.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import sharp from 'sharp';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { licenceStatus } from '../hub/licence.js';
|
||||
import { ApiError } from '../http.js';
|
||||
|
||||
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
||||
export const INCLUDED_STORAGE_BYTES = 5 * 1024 ** 3;
|
||||
const MAX_WIDTH = 2000;
|
||||
|
||||
/** backend/uploads, from src/ and dist/ alike. */
|
||||
export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads');
|
||||
export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defaultUploadDir());
|
||||
|
||||
/** The address an upload is shown at. */
|
||||
export const mediaUrl = (ctx: Ctx, filename: string) => `${ctx.config.publicUrl}/api/uploads/${filename}`;
|
||||
|
||||
/** The upload's filename when `url` is one of this App's uploads, else null. */
|
||||
export function uploadedFilename(ctx: Ctx, url: string | null | undefined): string | null {
|
||||
const prefix = `${ctx.config.publicUrl}/api/uploads/`;
|
||||
if (!url || !url.startsWith(prefix)) return null;
|
||||
const name = url.slice(prefix.length);
|
||||
return /^[0-9]{4}\/[0-9]{2}\/[0-9a-f-]{36}\.(jpg|png|webp)$/.test(name) ? name : null;
|
||||
}
|
||||
|
||||
type Kind = { ext: 'jpg' | 'png' | 'webp'; mime: string };
|
||||
|
||||
/** What the bytes are, whatever the name says. */
|
||||
export function sniff(b: Buffer): Kind | null {
|
||||
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
|
||||
if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
|
||||
if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function storage(ctx: Ctx): Promise<{ usedBytes: number; limitBytes: number; full: boolean; percent: number }> {
|
||||
const [sum, licence] = await Promise.all([ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }), licenceStatus(ctx)]);
|
||||
const fromLicence = (licence.claims as { limits?: { storageBytes?: number } } | null)?.limits?.storageBytes;
|
||||
const limitBytes = typeof fromLicence === 'number' ? fromLicence : INCLUDED_STORAGE_BYTES;
|
||||
const usedBytes = sum._sum.bytes ?? 0;
|
||||
return { usedBytes, limitBytes, full: usedBytes >= limitBytes, percent: limitBytes ? Math.min(100, Math.round((usedBytes / limitBytes) * 100)) : 100 };
|
||||
}
|
||||
|
||||
const view = (ctx: Ctx, m: { id: string; filename: string; mime: string; bytes: number; width: number | null; height: number | null; alt: string; createdAt: Date }) => ({
|
||||
id: m.id, url: mediaUrl(ctx, m.filename), mime: m.mime, bytes: m.bytes, width: m.width, height: m.height, alt: m.alt, createdAt: m.createdAt.toISOString(),
|
||||
});
|
||||
|
||||
export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
|
||||
if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.');
|
||||
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That photo is larger than 15 MB. Make it smaller and try again.');
|
||||
const kind = sniff(body);
|
||||
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.');
|
||||
const s = await storage(ctx);
|
||||
if (s.full) throw new ApiError(409, 'STORAGE_FULL', 'The App\'s storage is full, so uploads have stopped. Delete images you no longer use, or ask Cross Code for more; everything uploaded keeps showing.');
|
||||
let out: Buffer;
|
||||
let width: number | null;
|
||||
let height: number | null;
|
||||
try {
|
||||
// rotate() follows the EXIF orientation; sharp writes no metadata unless asked, so EXIF, GPS and XMP are gone.
|
||||
const img = sharp(body, { failOn: 'error' }).rotate().resize({ width: MAX_WIDTH, withoutEnlargement: true });
|
||||
const encoded = kind.ext === 'png' ? img.png({ compressionLevel: 9 }) : kind.ext === 'webp' ? img.webp({ quality: 82 }) : img.jpeg({ quality: 82, mozjpeg: true });
|
||||
const { data, info } = await encoded.toBuffer({ resolveWithObject: true });
|
||||
out = data;
|
||||
width = info.width ?? null;
|
||||
height = info.height ?? null;
|
||||
} catch {
|
||||
throw new ApiError(415, 'NOT_AN_IMAGE', 'That photo can\'t be read. Save it again as JPEG, PNG or WebP and try again.');
|
||||
}
|
||||
if (s.usedBytes + out.length > s.limitBytes) throw new ApiError(409, 'STORAGE_FULL', 'That photo doesn\'t fit in the storage that\'s left, so it wasn\'t added.');
|
||||
const now = ctx.now();
|
||||
const filename = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.${kind.ext}`;
|
||||
const file = path.join(uploadDir(ctx), filename);
|
||||
await fs.mkdir(path.dirname(file), { recursive: true });
|
||||
await fs.writeFile(file, out);
|
||||
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: kind.mime, bytes: out.length, width, height, alt: alt.trim().slice(0, 300), uploadedBy: by } });
|
||||
return view(ctx, row);
|
||||
}
|
||||
|
||||
/** Where each upload is used (announcements, campaigns, events), by filename. */
|
||||
export async function usage(ctx: Ctx): Promise<Map<string, string[]>> {
|
||||
const [announcements, campaigns, events] = await Promise.all([
|
||||
ctx.db.announcement.findMany({ where: { imageUrl: { not: null } }, select: { title: true, imageUrl: true } }),
|
||||
ctx.db.prayerCampaign.findMany({ where: { imageUrl: { not: null } }, select: { title: true, imageUrl: true } }),
|
||||
ctx.db.simpleEvent.findMany({ where: { imageUrl: { not: null } }, select: { title: true, imageUrl: true } }),
|
||||
]);
|
||||
const used = new Map<string, string[]>();
|
||||
const add = (what: string, url: string | null) => {
|
||||
const f = uploadedFilename(ctx, url);
|
||||
if (f) used.set(f, [...(used.get(f) ?? []), what]);
|
||||
};
|
||||
for (const a of announcements) add(`Announcement "${a.title}"`, a.imageUrl);
|
||||
for (const c of campaigns) add(`Campaign "${c.title}"`, c.imageUrl);
|
||||
for (const e of events) add(`Event "${e.title}"`, e.imageUrl);
|
||||
return used;
|
||||
}
|
||||
|
||||
export async function listMedia(ctx: Ctx) {
|
||||
const [rows, used, s] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' }, take: 500 }), usage(ctx), storage(ctx)]);
|
||||
return { storage: s, media: rows.map((m) => ({ ...view(ctx, m), usedBy: used.get(m.filename) ?? [] })) };
|
||||
}
|
||||
|
||||
export async function deleteMedia(ctx: Ctx, id: string) {
|
||||
const m = await ctx.db.mediaAsset.findUnique({ where: { id } });
|
||||
if (!m) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such image.');
|
||||
const usedBy = (await usage(ctx)).get(m.filename);
|
||||
if (usedBy?.length) throw new ApiError(409, 'IN_USE', `That image is still used: ${usedBy.join(', ')}. Change those first.`);
|
||||
await ctx.db.mediaAsset.delete({ where: { id } });
|
||||
await fs.rm(path.join(uploadDir(ctx), m.filename), { force: true });
|
||||
return m;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import sharp from 'sharp';
|
||||
import { cookieHeader, harness, MEMBER, PASTOR, signInAs, SITE, type Harness } from './support/harness.js';
|
||||
|
||||
const EDITOR = '77777777-7777-4777-8777-777777777777';
|
||||
const ORIGIN = 'https://app.hope.test';
|
||||
|
||||
async function setup() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cca-uploads-'));
|
||||
const h = await harness({ env: { UPLOAD_DIR: dir } }) as Harness;
|
||||
const as = (cookies: Record<string, string>) => ({
|
||||
get: (p: string) => request(h.app).get(p).set('Cookie', cookieHeader(cookies)),
|
||||
upload: (body: Buffer, type = 'image/jpeg') => request(h.app).post('/api/v1/admin/media?alt=Carols').set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).set('Content-Type', type).send(body),
|
||||
del: (p: string) => request(h.app).delete(p).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN),
|
||||
post: (p: string, body: object) => request(h.app).post(p).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body),
|
||||
});
|
||||
const editor = as(await signInAs(h, { sub: EDITOR, name: 'Editor', roles: ['content_admin'] }, true));
|
||||
const owner = as(await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', roles: ['owner'] }, true));
|
||||
const member = as(await signInAs(h, { sub: MEMBER, name: 'Thandi' }));
|
||||
return { h, dir, editor, owner, member };
|
||||
}
|
||||
|
||||
/** A phone photo: a JPEG with EXIF (a copyright line standing in for GPS). */
|
||||
const photo = () => sharp({ create: { width: 3000, height: 2000, channels: 3, background: '#c33' } }).jpeg().withExif({ IFD0: { Copyright: 'Where-I-live-123' } }).toBuffer();
|
||||
|
||||
describe('uploaded images (§10)', () => {
|
||||
it('keeps a photo without its metadata, at most 2000 px wide, and serves it', async () => {
|
||||
const { h, dir, editor, member } = await setup();
|
||||
assert.equal((await member.upload(await photo())).status, 403);
|
||||
const res = await editor.upload(await photo());
|
||||
assert.equal(res.status, 201);
|
||||
assert.equal(res.body.width, 2000);
|
||||
assert.equal(res.body.alt, 'Carols');
|
||||
assert.ok(res.body.url.startsWith(`${SITE}/api/uploads/`));
|
||||
const file = path.join(dir, res.body.url.slice(`${SITE}/api/uploads/`.length));
|
||||
const saved = fs.readFileSync(file);
|
||||
assert.ok(!saved.includes(Buffer.from('Where-I-live-123')));
|
||||
const served = await request(h.app).get(new URL(res.body.url).pathname);
|
||||
assert.equal(served.status, 200);
|
||||
assert.equal(served.headers['content-type'], 'image/jpeg');
|
||||
assert.match(served.headers['content-security-policy'], /sandbox/);
|
||||
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/../../package.json')).status));
|
||||
});
|
||||
|
||||
it('refuses what isn\'t a photo, whatever it\'s called', async () => {
|
||||
const { editor } = await setup();
|
||||
const res = await editor.upload(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'), 'image/png');
|
||||
assert.equal(res.status, 415);
|
||||
assert.equal(res.body.error.code, 'NOT_AN_IMAGE');
|
||||
});
|
||||
|
||||
it('won\'t delete an image an announcement still uses, and lists where each is used', async () => {
|
||||
const { h, editor } = await setup();
|
||||
const img = (await editor.upload(await photo())).body;
|
||||
await h.db.announcement.create({ data: { slug: 'carols', title: 'Carols', body: 'x', imageUrl: img.url, publishAt: new Date() } });
|
||||
const list = await editor.get('/api/v1/admin/media');
|
||||
assert.deepEqual(list.body.media[0].usedBy, ['Announcement "Carols"']);
|
||||
assert.ok(list.body.storage.usedBytes > 0);
|
||||
assert.equal((await editor.del(`/api/v1/admin/media/${img.id}`)).body.error.code, 'IN_USE');
|
||||
await h.db.announcement.deleteMany({});
|
||||
assert.equal((await editor.del(`/api/v1/admin/media/${img.id}`)).status, 200);
|
||||
assert.equal((await request(h.app).get(new URL(img.url).pathname)).status, 404);
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,7 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
outboxMessage: () => ({ sentAt: null, sentVia: null, failedAt: null, error: null, attempts: 0 }),
|
||||
notificationSettings: () => ({ requestUpdates: 'email', announcements: 'off', devotional: 'off', devotionalTime: '06:00', devotionalOfferedAt: null, lastDevotionalDate: null }),
|
||||
messageCount: () => ({ count: 0 }),
|
||||
mediaAsset: () => ({ width: null, height: null, alt: '', uploadedBy: null }),
|
||||
prayerRequest: () => ({ visibility: 'team', showName: false, anonymous: false, moderation: 'none', redactedAt: null, redactionNote: null, removedReason: null, moderatedById: null, moderatedAt: null, escalatedAt: null, escalatedById: null, escalationNote: null, closedAt: null }),
|
||||
prayerRequestUpdate: () => ({ authorId: null }),
|
||||
announcement: () => ({ imageUrl: null, buttonLabel: null, buttonUrl: null, campus: null, audience: 'everyone', pinned: false, publishAt: null, endsAt: null, sendEmail: false, sendWhatsApp: false, sentAt: null, createdById: null }),
|
||||
@@ -31,7 +32,7 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
};
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', notificationSettings: 'memberId', messageCount: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
|
||||
/** Unique fields: one field, or several together (`@@unique([a, b])`). */
|
||||
const UNIQUE: Record<string, (string | string[])[]> = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] };
|
||||
const UNIQUE: Record<string, (string | string[])[]> = { mediaAsset: ['filename'], session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] };
|
||||
const HAS_UPDATED_AT = new Set(['notificationSettings', 'member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest', 'announcement', 'devotional', 'simpleEvent']);
|
||||
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
|
||||
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { ImageField } from "./ImageField";
|
||||
import { adminCall, Field, fromLocalInput, input, Notice, Panel, toLocalInput, type Msg } from "./kit";
|
||||
|
||||
type Row = {
|
||||
@@ -73,7 +74,7 @@ export function AdminAnnouncements({ timezone, campuses }: { timezone: string; c
|
||||
<Field label="Title" error={errors.title}><input required maxLength={160} value={form.title} onChange={(e) => set("title", e.target.value)} className={input} /></Field>
|
||||
<Field label="Text" error={errors.body} hint="Markdown: **bold**, *italics*, lists and [links](https://…). No HTML."><textarea required rows={8} maxLength={20000} value={form.body} onChange={(e) => set("body", e.target.value)} className={input} /></Field>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Field label="Image address (optional)" error={errors.imageUrl}><input type="url" value={form.imageUrl ?? ""} onChange={(e) => set("imageUrl", e.target.value)} className={input} /></Field>
|
||||
<ImageField value={form.imageUrl} onChange={(url) => set("imageUrl", url)} error={errors.imageUrl} alt={form.title} />
|
||||
<Field label="Button words (optional)" error={errors.buttonLabel}><input maxLength={40} value={form.buttonLabel ?? ""} onChange={(e) => set("buttonLabel", e.target.value)} className={input} placeholder="Sign up" /></Field>
|
||||
<Field label="Button link" error={errors.buttonUrl}><input type="url" value={form.buttonUrl ?? ""} onChange={(e) => set("buttonUrl", e.target.value)} className={input} /></Field>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { ImageField } from "./ImageField";
|
||||
import { adminCall, Field, input, Notice, Panel, type Msg } from "./kit";
|
||||
|
||||
type Row = {
|
||||
@@ -82,7 +83,7 @@ export function AdminEvents({ today }: { today: string }) {
|
||||
<Field label="Where" error={errors.location}><input maxLength={200} value={form.location ?? ""} onChange={(e) => set("location", e.target.value)} className={input} /></Field>
|
||||
<Field label="Description" error={errors.description}><textarea rows={5} maxLength={10000} value={form.description ?? ""} onChange={(e) => set("description", e.target.value)} className={input} /></Field>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Image address (optional)" error={errors.imageUrl}><input type="url" value={form.imageUrl ?? ""} onChange={(e) => set("imageUrl", e.target.value)} className={input} /></Field>
|
||||
<ImageField value={form.imageUrl} onChange={(url) => set("imageUrl", url)} error={errors.imageUrl} alt={form.title} />
|
||||
<Field label="More info link (optional)" error={errors.link}><input type="url" value={form.link ?? ""} onChange={(e) => set("link", e.target.value)} className={input} /></Field>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-6 text-sm font-medium">
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useRef, useState } from "react";
|
||||
import { errorMessage } from "@/lib/prayer";
|
||||
import { input } from "./kit";
|
||||
|
||||
/**
|
||||
* An image for an announcement, campaign or event (APP-1.0-PLAN §10): upload a photo (JPEG, PNG or
|
||||
* WebP; kept without its metadata, at most 2000 px wide) or give an image's address. Shows a
|
||||
* preview and Remove.
|
||||
*/
|
||||
export function ImageField({ value, onChange, error, label = "Image (optional)", alt = "" }: { value: string | null; onChange: (url: string | null) => void; error?: string; label?: string; alt?: string }) {
|
||||
const id = useId();
|
||||
const file = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
|
||||
async function upload(f: File) {
|
||||
setBusy(true);
|
||||
setProblem(null);
|
||||
try {
|
||||
const res = await fetch(`/api/v1/admin/media?alt=${encodeURIComponent(alt)}`, { method: "POST", headers: { "Content-Type": f.type || "application/octet-stream" }, body: f });
|
||||
if (!res.ok) {
|
||||
setProblem(await errorMessage(res, "The photo wasn't uploaded. Please try again."));
|
||||
return;
|
||||
}
|
||||
onChange(((await res.json()) as { url: string }).url);
|
||||
} catch {
|
||||
setProblem("The App's server can't be reached. Please try again.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
if (file.current) file.current.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2 text-sm">
|
||||
<label htmlFor={id} className="block font-medium">{label}</label>
|
||||
{value && (
|
||||
<div className="flex items-start gap-3">
|
||||
<img src={value} alt="" className="h-20 w-32 rounded-md border border-gray-200 object-cover" />
|
||||
<button type="button" className="text-sm font-semibold underline" onClick={() => onChange(null)}>Remove</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button type="button" className="cca-btn-quiet" disabled={busy} onClick={() => file.current?.click()}>{busy ? "Uploading…" : value ? "Upload another photo" : "Upload a photo"}</button>
|
||||
<input ref={file} type="file" accept="image/jpeg,image/png,image/webp" className="sr-only" tabIndex={-1} aria-hidden onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])} />
|
||||
<span className="text-gray-500">or its address:</span>
|
||||
</div>
|
||||
<input id={id} type="url" value={value ?? ""} onChange={(e) => onChange(e.target.value || null)} className={input} placeholder="https://…" />
|
||||
{(problem || error) && <p role="alert" className="text-xs text-red-700">{problem ?? error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { addDays, dayName, duration, errorMessage, hhmm, span, type Recurrence } from "@/lib/prayer";
|
||||
import { ImageField } from "@/components/admin/ImageField";
|
||||
|
||||
const TABS = [
|
||||
{ key: "week", label: "This week" },
|
||||
@@ -325,7 +326,7 @@ function Campaigns({ today }: { today: string }) {
|
||||
<label className="text-sm font-medium">Aim<input maxLength={200} value={editing.goal ?? ""} onChange={(e) => setEditing({ ...editing, goal: e.target.value })} className={input} /></label>
|
||||
<label className="text-sm font-medium">People per slot<input type="number" min={1} max={50} value={editing.targetPerSlot ?? ""} placeholder="As the wall" onChange={(e) => setEditing({ ...editing, targetPerSlot: e.target.value ? Number(e.target.value) : null })} className={input} /></label>
|
||||
</div>
|
||||
<label className="block text-sm font-medium">Image address (optional)<input type="url" value={editing.imageUrl ?? ""} onChange={(e) => setEditing({ ...editing, imageUrl: e.target.value })} className={input} /></label>
|
||||
<ImageField value={editing.imageUrl} onChange={(url) => setEditing({ ...editing, imageUrl: url })} alt={editing.title} />
|
||||
<p className="text-xs text-gray-600">During a campaign, Home and the Prayer tab lead with it: days left, coverage so far and hours prayed (self-reported). Never rankings or anyone's own total.</p>
|
||||
<div className="flex gap-2"><button className="cca-btn">Save</button><button type="button" className="cca-btn-quiet" onClick={() => setEditing(null)}>Cancel</button></div>
|
||||
</form>
|
||||
|
||||
Reference in New Issue
Block a user