248 lines
7.5 KiB
TypeScript
248 lines
7.5 KiB
TypeScript
import "server-only";
|
|
|
|
import { desc, eq, gte } from "drizzle-orm";
|
|
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
|
|
import { db } from "@/db/client";
|
|
import { announcements } from "@/db/schema";
|
|
import type * as schema from "@/db/schema";
|
|
import { writeAudit } from "@/modules/audit/write";
|
|
|
|
// A hint for an event (e.g. a match) stays visible until three days after the
|
|
// event date, so it covers match day plus the following days without any
|
|
// manual cleanup.
|
|
export const ANNOUNCEMENT_VISIBLE_DAYS_AFTER_EVENT = 3;
|
|
|
|
export const ANNOUNCEMENT_MAX_MESSAGE_LENGTH = 500;
|
|
|
|
export type Announcement = {
|
|
id: string;
|
|
message: string;
|
|
eventDate: string;
|
|
createdAt: Date;
|
|
};
|
|
|
|
export type AdminAnnouncement = Announcement & {
|
|
/** Last day (ISO date) on which editorial users still see the hint. */
|
|
visibleUntil: string;
|
|
isActive: boolean;
|
|
};
|
|
|
|
export type AnnouncementError =
|
|
| "INVALID_MESSAGE"
|
|
| "INVALID_EVENT_DATE"
|
|
| "ANNOUNCEMENT_NOT_FOUND";
|
|
|
|
export class AnnouncementServiceError extends Error {
|
|
readonly name = "AnnouncementServiceError";
|
|
|
|
constructor(readonly code: AnnouncementError) {
|
|
super(code);
|
|
}
|
|
}
|
|
|
|
export type CreateAnnouncementInput = {
|
|
message: string;
|
|
eventDate: string;
|
|
adminUserId: string;
|
|
};
|
|
|
|
export type AnnouncementRepository = {
|
|
insert(input: {
|
|
message: string;
|
|
eventDate: string;
|
|
adminUserId: string;
|
|
}): Promise<Announcement>;
|
|
listVisibleOn(today: string): Promise<Announcement[]>;
|
|
listAll(): Promise<Announcement[]>;
|
|
deleteById(
|
|
id: string,
|
|
): Promise<{ id: string; message: string; eventDate: string } | null>;
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Date helpers (pure, so the visibility window is unit-testable)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Today's calendar date in the portal's timezone (Europe/Berlin). */
|
|
export function isoDateInBerlin(instant: Date): string {
|
|
return new Intl.DateTimeFormat("en-CA", { timeZone: "Europe/Berlin" }).format(instant);
|
|
}
|
|
|
|
/** Shifts an ISO date (YYYY-MM-DD) by a whole number of days. */
|
|
export function shiftIsoDate(isoDate: string, days: number): string {
|
|
const [year, month, day] = isoDate.split("-").map(Number);
|
|
const shifted = new Date(Date.UTC(year, month - 1, day + days));
|
|
return shifted.toISOString().slice(0, 10);
|
|
}
|
|
|
|
/** Event dates from this day on are still visible on `today`. */
|
|
export function minVisibleEventDate(today: string): string {
|
|
return shiftIsoDate(today, -ANNOUNCEMENT_VISIBLE_DAYS_AFTER_EVENT);
|
|
}
|
|
|
|
export function isValidIsoDate(value: string): boolean {
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
|
return false;
|
|
}
|
|
const [year, month, day] = value.split("-").map(Number);
|
|
const parsed = new Date(Date.UTC(year, month - 1, day));
|
|
return (
|
|
parsed.getUTCFullYear() === year &&
|
|
parsed.getUTCMonth() === month - 1 &&
|
|
parsed.getUTCDate() === day
|
|
);
|
|
}
|
|
|
|
/** Formats an ISO date (YYYY-MM-DD) as TT.MM.JJJJ without timezone round-trips. */
|
|
export function formatIsoDateGerman(isoDate: string): string {
|
|
const [year, month, day] = isoDate.split("-");
|
|
return `${day}.${month}.${year}`;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Service
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export function createAnnouncementService({
|
|
repository,
|
|
audit,
|
|
}: {
|
|
repository: AnnouncementRepository;
|
|
audit: { writeAudit: typeof writeAudit };
|
|
}) {
|
|
return {
|
|
async createAnnouncement(input: CreateAnnouncementInput): Promise<Announcement> {
|
|
const message = input.message.trim();
|
|
if (message.length === 0 || message.length > ANNOUNCEMENT_MAX_MESSAGE_LENGTH) {
|
|
throw new AnnouncementServiceError("INVALID_MESSAGE");
|
|
}
|
|
if (!isValidIsoDate(input.eventDate)) {
|
|
throw new AnnouncementServiceError("INVALID_EVENT_DATE");
|
|
}
|
|
|
|
const created = await repository.insert({
|
|
message,
|
|
eventDate: input.eventDate,
|
|
adminUserId: input.adminUserId,
|
|
});
|
|
|
|
await audit.writeAudit({
|
|
type: "announcement_created",
|
|
actorUserId: input.adminUserId,
|
|
actorType: "admin",
|
|
entityType: "announcement",
|
|
entityId: created.id,
|
|
metadata: { eventDate: created.eventDate, message: created.message },
|
|
});
|
|
|
|
return created;
|
|
},
|
|
|
|
/** Hints currently visible to editorial users. */
|
|
async listActiveAnnouncements(now: Date): Promise<Announcement[]> {
|
|
return repository.listVisibleOn(isoDateInBerlin(now));
|
|
},
|
|
|
|
/** Every hint for the admin overview with its computed visibility. */
|
|
async listAnnouncements(now: Date): Promise<AdminAnnouncement[]> {
|
|
const today = isoDateInBerlin(now);
|
|
const rows = await repository.listAll();
|
|
return rows.map((row) => ({
|
|
...row,
|
|
// Visible while eventDate >= today - 3d ⇔ today <= eventDate + 3d.
|
|
visibleUntil: shiftIsoDate(row.eventDate, ANNOUNCEMENT_VISIBLE_DAYS_AFTER_EVENT),
|
|
isActive: row.eventDate >= minVisibleEventDate(today),
|
|
}));
|
|
},
|
|
|
|
async deleteAnnouncement(input: {
|
|
id: string;
|
|
adminUserId: string;
|
|
}): Promise<void> {
|
|
const deleted = await repository.deleteById(input.id);
|
|
if (!deleted) {
|
|
throw new AnnouncementServiceError("ANNOUNCEMENT_NOT_FOUND");
|
|
}
|
|
|
|
await audit.writeAudit({
|
|
type: "announcement_deleted",
|
|
actorUserId: input.adminUserId,
|
|
actorType: "admin",
|
|
entityType: "announcement",
|
|
entityId: deleted.id,
|
|
metadata: { eventDate: deleted.eventDate, message: deleted.message },
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Drizzle repository
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export function createAnnouncementRepository(
|
|
database: NodePgDatabase<typeof schema>,
|
|
): AnnouncementRepository {
|
|
return {
|
|
async insert(input) {
|
|
const [row] = await database
|
|
.insert(announcements)
|
|
.values({
|
|
message: input.message,
|
|
eventDate: input.eventDate,
|
|
createdByUserId: input.adminUserId,
|
|
})
|
|
.returning({
|
|
id: announcements.id,
|
|
message: announcements.message,
|
|
eventDate: announcements.eventDate,
|
|
createdAt: announcements.createdAt,
|
|
});
|
|
return row;
|
|
},
|
|
|
|
async listVisibleOn(today) {
|
|
return database
|
|
.select({
|
|
id: announcements.id,
|
|
message: announcements.message,
|
|
eventDate: announcements.eventDate,
|
|
createdAt: announcements.createdAt,
|
|
})
|
|
.from(announcements)
|
|
.where(gte(announcements.eventDate, minVisibleEventDate(today)))
|
|
.orderBy(desc(announcements.eventDate), desc(announcements.createdAt));
|
|
},
|
|
|
|
async listAll() {
|
|
return database
|
|
.select({
|
|
id: announcements.id,
|
|
message: announcements.message,
|
|
eventDate: announcements.eventDate,
|
|
createdAt: announcements.createdAt,
|
|
})
|
|
.from(announcements)
|
|
.orderBy(desc(announcements.createdAt));
|
|
},
|
|
|
|
async deleteById(id) {
|
|
const [row] = await database
|
|
.delete(announcements)
|
|
.where(eq(announcements.id, id))
|
|
.returning({
|
|
id: announcements.id,
|
|
message: announcements.message,
|
|
eventDate: announcements.eventDate,
|
|
});
|
|
return row ?? null;
|
|
},
|
|
};
|
|
}
|
|
|
|
export const announcementService = createAnnouncementService({
|
|
repository: createAnnouncementRepository(db),
|
|
audit: { writeAudit },
|
|
});
|