Discord: zentrale Ticket-Rechte, Kanalzugriffe abgleichen, Nummern atomar (#110)
- Ticket-Rechte je Rolle in @kc/platform/ticketPolicy, vom Tickets-Modul UND vom Discord-Worker genutzt. Buchhaltung (nur lesen) kann über Discord kein Ticket mehr anlegen, beantworten, zuweisen oder schließen. - Kundenzugriff auf Ticket-Kanäle wird bei jedem Abgleich synchronisiert: Freigaben entknüpfter/deaktivierter Konten, ausgetretener Mitglieder und gesperrter Kunden werden entfernt. - Nachrichten deaktivierter Kunden-Konten oder gesperrter Kunden werden nicht übernommen; /ticket nur für aktive Organisationen. - Ticketnummer + Ticket + erste Nachricht in einer Transaktion auf einer Verbindung (vorher LAST_INSERT_ID über den Pool). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
914599df50
commit
677186e3f3
5 changed files with 89 additions and 52 deletions
|
|
@ -13,6 +13,8 @@ import { can, canInOrg } from '../../core/policy.js';
|
|||
import type { KcModule } from '../../core/module.js';
|
||||
import { config } from '../../core/config.js';
|
||||
import { MAX_FILES_PER_MESSAGE, MAX_FILE_BYTES, pathFor, storeUpload } from './files.js';
|
||||
import { TICKET_PERMISSIONS } from '@kc/platform/ticketPolicy';
|
||||
const mutable = <T extends Record<string, readonly string[]>>(m: T) => Object.fromEntries(Object.entries(m).map(([k, v]) => [k, [...v]])) as { [K in keyof T]: string[] };
|
||||
|
||||
const ticketLink = (id: string) => `${config.baseUrl}/tickets/${id}`;
|
||||
|
||||
|
|
@ -47,10 +49,7 @@ async function loadTicket(id: string, forCustomer: boolean) {
|
|||
|
||||
export const ticketsModule: KcModule = {
|
||||
name: 'tickets',
|
||||
permissions: {
|
||||
staff: { support: ['tickets.read', 'tickets.write'], accounting: ['tickets.read'], admin: ['tickets.read', 'tickets.write'], superadmin: ['tickets.read', 'tickets.write'] },
|
||||
org: { owner: ['tickets.read', 'tickets.create'], admin: ['tickets.read', 'tickets.create'], member: ['tickets.read', 'tickets.create'] },
|
||||
},
|
||||
permissions: { staff: mutable(TICKET_PERMISSIONS.staff), org: mutable(TICKET_PERMISSIONS.org) }, // gemeinsame Quelle mit dem Discord-Worker
|
||||
register(app: FastifyInstance) {
|
||||
app.post('/tickets', async (req) => {
|
||||
const a = requireAuth(req);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { ChannelType, Client, GatewayIntentBits, OverwriteType, PermissionFlagsBits, REST, Routes, SlashCommandBuilder, type ChatInputCommandInteraction, type Guild, type Message, type OverwriteResolvable, type TextChannel } from 'discord.js';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { pool } from '@kc/platform/db';
|
||||
import { pool, run, tx } from '@kc/platform/db';
|
||||
import { nextSequence } from '@kc/platform/sequences';
|
||||
import { staffMayTicket } from '@kc/platform/ticketPolicy';
|
||||
import { decrypt } from '@kc/platform/crypto';
|
||||
import { enqueue } from '@kc/platform/jobs';
|
||||
import { config } from '@kc/platform/config';
|
||||
|
|
@ -23,13 +25,25 @@ async function loadSettings(): Promise<DiscordSettings> {
|
|||
};
|
||||
}
|
||||
const notify = (event: string, extra: Record<string, unknown>, key: string) => enqueue('discord.notify', { event, ...extra }, { idempotencyKey: key });
|
||||
async function nextTicketNumber(): Promise<string> {
|
||||
await pool.query("UPDATE number_sequences SET next_value = LAST_INSERT_ID(next_value + 1) WHERE name = 'ticket'");
|
||||
const [r] = await pool.query('SELECT LAST_INSERT_ID() AS n') as any;
|
||||
return `T-${r[0].n}`;
|
||||
/** Legt Ticket + erste Nachricht in EINER Transaktion an; die Nummer kommt über dieselbe Verbindung (LAST_INSERT_ID). */
|
||||
async function createTicket(t: { orgId: string; subject: string; status: string; createdBy: string; authorKind: 'customer' | 'staff'; body: string }): Promise<{ id: string; number: string }> {
|
||||
const id = randomUUID();
|
||||
const number = await tx(async (c) => {
|
||||
const n = `T-${await nextSequence(c, 'ticket')}`;
|
||||
await run('INSERT INTO tickets (id, number, org_id, subject, status, priority, created_by) VALUES (?,?,?,?,?,?,?)', [id, n, t.orgId, t.subject, t.status, 'normal', t.createdBy], c);
|
||||
await run('INSERT INTO ticket_messages (id, ticket_id, author_id, author_kind, body) VALUES (?,?,?,?,?)', [randomUUID(), id, t.createdBy, t.authorKind, t.body], c);
|
||||
return n;
|
||||
});
|
||||
return { id, number };
|
||||
}
|
||||
const linkedUser = (discordUserId: string, kind: 'customer' | 'staff') =>
|
||||
pool.query("SELECT id, name FROM users WHERE discord_user_id = ? AND kind = ? AND status = 'active'", [discordUserId, kind]).then(([r]: any) => r[0]);
|
||||
const linkedCustomer = (discordUserId: string) =>
|
||||
pool.query("SELECT id, name FROM users WHERE discord_user_id = ? AND kind = 'customer' AND status = 'active'", [discordUserId]).then(([r]: any) => r[0] as { id: string; name: string } | undefined);
|
||||
/** Verknüpftes, aktives Personal-Konto MIT dem nötigen Ticket-Recht der zentralen Policy (Buchhaltung: nur lesen). */
|
||||
const linkedStaff = async (discordUserId: string, permission: 'tickets.read' | 'tickets.write' = 'tickets.write') => {
|
||||
const u = await pool.query("SELECT id, name, staff_role FROM users WHERE discord_user_id = ? AND kind = 'staff' AND status = 'active'", [discordUserId]).then(([r]: any) => r[0] as { id: string; name: string; staff_role: string | null } | undefined);
|
||||
return u && staffMayTicket(u.staff_role, permission) ? u : undefined;
|
||||
};
|
||||
const NO_STAFF = 'Nur für verknüpfte Personal-Konten mit Schreibrecht für Tickets.';
|
||||
const ticketForThread = (channelId: string) =>
|
||||
pool.query('SELECT tt.ticket_id, tk.number FROM ticket_discord_threads tt JOIN tickets tk ON tk.id = tt.ticket_id WHERE tt.thread_id = ?', [channelId]).then(([r]: any) => r[0]);
|
||||
|
||||
|
|
@ -63,15 +77,13 @@ async function handleTicketCreate(i: ChatInputCommandInteraction): Promise<void>
|
|||
const body = i.options.getString('text', true).slice(0, 2000);
|
||||
const kunde = i.options.getString('kunde')?.trim();
|
||||
|
||||
const customer = await linkedUser(i.user.id, 'customer');
|
||||
const customer = await linkedCustomer(i.user.id);
|
||||
if (customer) {
|
||||
const mem = await pool.query("SELECT org_id FROM memberships WHERE user_id = ? ORDER BY (role = 'owner') DESC LIMIT 1", [customer.id]).then(([r]: any) => r[0]);
|
||||
if (!mem) { await i.reply({ content: 'Für dein Konto ist keine Organisation hinterlegt.', ephemeral: true }); return; }
|
||||
// nur aktive Organisationen (gesperrte Kunden eröffnen keine Tickets per Discord)
|
||||
const mem = await pool.query("SELECT m.org_id FROM memberships m JOIN organizations o ON o.id = m.org_id AND o.status = 'active' WHERE m.user_id = ? ORDER BY (m.role = 'owner') DESC LIMIT 1", [customer.id]).then(([r]: any) => r[0]);
|
||||
if (!mem) { await i.reply({ content: 'Für dein Konto ist keine aktive Organisation hinterlegt.', ephemeral: true }); return; }
|
||||
await i.deferReply({ ephemeral: true });
|
||||
const ticketId = randomUUID();
|
||||
const number = await nextTicketNumber();
|
||||
await pool.query('INSERT INTO tickets (id, number, org_id, subject, status, priority, created_by) VALUES (?,?,?,?,?,?,?)', [ticketId, number, mem.org_id, subject, 'pending_staff', 'normal', customer.id]);
|
||||
await pool.query('INSERT INTO ticket_messages (id, ticket_id, author_id, author_kind, body) VALUES (?,?,?,?,?)', [randomUUID(), ticketId, customer.id, 'customer', body]);
|
||||
const { id: ticketId, number } = await createTicket({ orgId: mem.org_id, subject, status: 'pending_staff', createdBy: customer.id, authorKind: 'customer', body });
|
||||
await notify('ticket.created', { number, subject: subject.slice(0, 100) }, `discord-cmd:${ticketId}`);
|
||||
await postTicketMessage(ticketId, body, 'Kunde');
|
||||
const ch = await ticketChannelId(ticketId);
|
||||
|
|
@ -79,8 +91,8 @@ async function handleTicketCreate(i: ChatInputCommandInteraction): Promise<void>
|
|||
return;
|
||||
}
|
||||
|
||||
const staff = await linkedUser(i.user.id, 'staff');
|
||||
if (!staff) { await i.reply({ content: 'Dein Discord-Konto ist mit keinem Kundencenter-Konto verknüpft (unter „Mein Konto“ → „Mit Discord verbinden“).', ephemeral: true }); return; }
|
||||
const staff = await linkedStaff(i.user.id);
|
||||
if (!staff) { await i.reply({ content: 'Dein Discord-Konto ist mit keinem Kundencenter-Konto mit Ticket-Schreibrecht verknüpft (unter „Mein Konto“ → „Mit Discord verbinden“).', ephemeral: true }); return; }
|
||||
if (!kunde) { await i.reply({ content: 'Als Personal bitte die Option „kunde“ angeben (Kundennummer oder Name), für wen das Ticket ist.', ephemeral: true }); return; }
|
||||
const orgs = await pool.query("SELECT id, name, customer_number FROM organizations WHERE customer_number = ? OR name LIKE CONCAT('%', ?, '%') LIMIT 2", [kunde, kunde]) as [any[], unknown];
|
||||
const matches = orgs[0];
|
||||
|
|
@ -88,29 +100,26 @@ async function handleTicketCreate(i: ChatInputCommandInteraction): Promise<void>
|
|||
if (matches.length > 1) { await i.reply({ content: `Mehrdeutig – bitte die genaue Kundennummer angeben (z. B. gefunden: ${matches.map((m) => m.customer_number).join(', ')}).`, ephemeral: true }); return; }
|
||||
const org = matches[0];
|
||||
await i.deferReply({ ephemeral: true });
|
||||
const ticketId = randomUUID();
|
||||
const number = await nextTicketNumber();
|
||||
// Von Personal angelegt: wartet auf den Kunden, wie beim Anlegen über die Web-Oberfläche.
|
||||
await pool.query('INSERT INTO tickets (id, number, org_id, subject, status, priority, created_by) VALUES (?,?,?,?,?,?,?)', [ticketId, number, org.id, subject, 'pending_customer', 'normal', staff.id]);
|
||||
await pool.query('INSERT INTO ticket_messages (id, ticket_id, author_id, author_kind, body) VALUES (?,?,?,?,?)', [randomUUID(), ticketId, staff.id, 'staff', body]);
|
||||
const { id: ticketId, number } = await createTicket({ orgId: org.id, subject, status: 'pending_customer', createdBy: staff.id, authorKind: 'staff', body });
|
||||
await postTicketMessage(ticketId, body, 'Support');
|
||||
const ch = await ticketChannelId(ticketId);
|
||||
await i.editReply({ content: `Ticket ${number} für ${org.name} (${org.customer_number}) wurde angelegt.${ch ? ` <#${ch}>` : ''}` });
|
||||
}
|
||||
/** Weist das Ticket des aktuellen Threads einer per Discord verknüpften Personal-Person zu. */
|
||||
async function handleAssign(i: ChatInputCommandInteraction): Promise<void> {
|
||||
if (!(await linkedUser(i.user.id, 'staff'))) { await i.reply({ content: 'Nur für verknüpfte Personal-Konten.', ephemeral: true }); return; }
|
||||
if (!(await linkedStaff(i.user.id))) { await i.reply({ content: NO_STAFF, ephemeral: true }); return; }
|
||||
const t = await ticketForThread(i.channelId);
|
||||
if (!t) { await i.reply({ content: 'Dieser Befehl funktioniert nur innerhalb eines Ticket-Threads.', ephemeral: true }); return; }
|
||||
const target = i.options.getUser('mitarbeiter', true);
|
||||
const assignee = await linkedUser(target.id, 'staff');
|
||||
const assignee = await linkedStaff(target.id); // nur wer im Web Tickets bearbeiten darf, kann sie auch zugewiesen bekommen
|
||||
if (!assignee) { await i.reply({ content: `${target.username} hat kein verknüpftes Personal-Konto.`, ephemeral: true }); return; }
|
||||
await pool.query('UPDATE tickets SET assigned_to = ? WHERE id = ?', [assignee.id, t.ticket_id]);
|
||||
await i.reply({ content: `Ticket ${t.number} wurde ${assignee.name} zugewiesen.` });
|
||||
}
|
||||
/** Schließt das Ticket des aktuellen Threads. */
|
||||
async function handleClose(i: ChatInputCommandInteraction): Promise<void> {
|
||||
if (!(await linkedUser(i.user.id, 'staff'))) { await i.reply({ content: 'Nur für verknüpfte Personal-Konten.', ephemeral: true }); return; }
|
||||
if (!(await linkedStaff(i.user.id))) { await i.reply({ content: NO_STAFF, ephemeral: true }); return; }
|
||||
const t = await ticketForThread(i.channelId);
|
||||
if (!t) { await i.reply({ content: 'Dieser Befehl funktioniert nur innerhalb eines Ticket-Threads.', ephemeral: true }); return; }
|
||||
await pool.query("UPDATE tickets SET status = 'closed', closed_at = UTC_TIMESTAMP(3) WHERE id = ?", [t.ticket_id]);
|
||||
|
|
@ -123,7 +132,7 @@ async function handle(i: ChatInputCommandInteraction): Promise<void> {
|
|||
if (i.commandName === 'zuweisen') return handleAssign(i);
|
||||
if (i.commandName === 'schliessen') return handleClose(i);
|
||||
// Alle Antworten ephemeral: nie vertrauliche Daten in Kanälen sichtbar machen. Berechtigung = verknüpftes Personal-Konto (wie /zuweisen, /schliessen).
|
||||
if (!(await linkedUser(i.user.id, 'staff'))) { await i.reply({ content: 'Nur für verknüpfte Personal-Konten.', ephemeral: true }); return; }
|
||||
if (!(await linkedStaff(i.user.id, 'tickets.read'))) { await i.reply({ content: 'Nur für verknüpfte Personal-Konten.', ephemeral: true }); return; }
|
||||
if (i.commandName === 'kc-status') {
|
||||
const [rows] = await pool.query('SELECT status, COUNT(*) n FROM jobs GROUP BY status') as any;
|
||||
const jobs = rows.length ? rows.map((r: any) => `${r.status}: ${r.n}`).join(', ') : 'keine';
|
||||
|
|
@ -144,7 +153,9 @@ async function handleThreadMessage(msg: Message, log: (m: string) => void): Prom
|
|||
if (t.status === 'closed') { await msg.reply('Dieses Ticket ist geschlossen. Bitte im Kundencenter ein neues Ticket eröffnen oder den Befehl `/ticket` nutzen.').catch(() => undefined); return; }
|
||||
const body = msg.content.trim().slice(0, 10000);
|
||||
if (!body) return;
|
||||
const staff = await linkedUser(msg.author.id, 'staff');
|
||||
const staffAny = await linkedStaff(msg.author.id, 'tickets.read');
|
||||
const staff = staffAny && staffMayTicket(staffAny.staff_role, 'tickets.write') ? staffAny : undefined;
|
||||
if (staffAny && !staff) { await msg.reply('Dein Konto darf Tickets nur lesen – die Nachricht wurde nicht ins Ticket übernommen.').catch(() => undefined); return; }
|
||||
if (staff) {
|
||||
await pool.query('INSERT INTO ticket_messages (id, ticket_id, author_id, author_kind, body) VALUES (?,?,?,?,?)', [randomUUID(), t.ticket_id, staff.id, 'staff', body]);
|
||||
await pool.query("UPDATE tickets SET status = 'pending_customer', last_message_at = UTC_TIMESTAMP(3), resolved_at = NULL, closed_at = NULL WHERE id = ?", [t.ticket_id]);
|
||||
|
|
@ -154,10 +165,11 @@ async function handleThreadMessage(msg: Message, log: (m: string) => void): Prom
|
|||
log(`Discord: Support-Antwort zu Ticket ${t.number} übernommen.`);
|
||||
return;
|
||||
}
|
||||
const u = await pool.query("SELECT id, name FROM users WHERE discord_user_id = ? AND kind = 'customer'", [msg.author.id]).then(([r]: any) => r[0]);
|
||||
if (!u) return; // Discord-Konto ohne Verknüpfung: nicht zuordenbar
|
||||
const member = await pool.query('SELECT 1 AS x FROM memberships WHERE user_id = ? AND org_id = ?', [u.id, t.org_id]).then(([r]: any) => r[0]);
|
||||
const u = await linkedCustomer(msg.author.id); // nur aktive Konten
|
||||
if (!u) return; // Discord-Konto ohne (aktive) Verknüpfung: nicht zuordenbar
|
||||
const member = await pool.query('SELECT o.status FROM memberships m JOIN organizations o ON o.id = m.org_id WHERE m.user_id = ? AND m.org_id = ?', [u.id, t.org_id]).then(([r]: any) => r[0]);
|
||||
if (!member) return;
|
||||
if (member.status !== 'active') { await msg.reply('Dieses Kundenkonto ist derzeit gesperrt – die Nachricht wurde nicht übernommen.').catch(() => undefined); return; }
|
||||
await pool.query('INSERT INTO ticket_messages (id, ticket_id, author_id, author_kind, body) VALUES (?,?,?,?,?)', [randomUUID(), t.ticket_id, u.id, 'customer', body]);
|
||||
await pool.query("UPDATE tickets SET status = 'pending_staff', last_message_at = UTC_TIMESTAMP(3), resolved_at = NULL, closed_at = NULL WHERE id = ?", [t.ticket_id]);
|
||||
await notify('ticket.message', { number: t.number }, `discord-in:${msg.id}`);
|
||||
|
|
@ -172,7 +184,7 @@ const BOT_PERMS = [...CHANNEL_PERMS, PermissionFlagsBits.ManageChannels];
|
|||
const slug = (v: string) => v.toLowerCase().replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
||||
const ticketLink = (id: string) => `${config.baseUrl}/tickets/${id}`;
|
||||
/** Discord-Konten der Kunden-Mitglieder (nur verknüpfte, aktive Benutzer der Organisation). */
|
||||
const orgDiscordIds = (orgId: string) => pool.query("SELECT u.discord_user_id FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.org_id = ? AND u.kind = 'customer' AND u.status = 'active' AND u.discord_user_id IS NOT NULL", [orgId])
|
||||
const orgDiscordIds = (orgId: string) => pool.query("SELECT u.discord_user_id FROM memberships m JOIN users u ON u.id = m.user_id JOIN organizations o ON o.id = m.org_id AND o.status = 'active' WHERE m.org_id = ? AND u.kind = 'customer' AND u.status = 'active' AND u.discord_user_id IS NOT NULL", [orgId])
|
||||
.then(([r]: any) => (r as { discord_user_id: string }[]).map((x) => x.discord_user_id));
|
||||
function overwrites(guild: Guild, s: DiscordSettings, customerIds: string[]): OverwriteResolvable[] {
|
||||
return [
|
||||
|
|
@ -222,11 +234,18 @@ async function ensureTicketChannel(s: DiscordSettings, ticketId: string, withOpe
|
|||
return { channel, created: true };
|
||||
});
|
||||
}
|
||||
/** Ergänzt Kunden-Mitglieder, die ihr Discord erst nach dem Anlegen des Kanals verknüpft haben (nur wenn etwas fehlt). */
|
||||
async function grantCustomers(channel: TextChannel, orgId: string): Promise<void> {
|
||||
for (const id of await orgDiscordIds(orgId)) {
|
||||
/** Gleicht die Kunden-Freigaben des Kanals mit den aktuell berechtigten Mitgliedern ab: ergänzt neu verknüpfte und
|
||||
* ENTFERNT Freigaben von Konten, die entknüpft, deaktiviert, aus der Organisation entfernt oder deren Kunde gesperrt
|
||||
* ist. Rollen-Freigaben (Support) und der Bot bleiben unberührt. */
|
||||
async function syncCustomerAccess(channel: TextChannel, orgId: string): Promise<void> {
|
||||
const wanted = new Set(await orgDiscordIds(orgId));
|
||||
const botId = channel.client.user.id;
|
||||
for (const id of wanted) {
|
||||
if (!channel.permissionOverwrites.cache.has(id)) await channel.permissionOverwrites.create(id, { ViewChannel: true, SendMessages: true, ReadMessageHistory: true, AttachFiles: true }, { type: OverwriteType.Member, reason: 'Kunde hat Discord verknüpft' });
|
||||
}
|
||||
for (const ow of [...channel.permissionOverwrites.cache.values()]) {
|
||||
if (ow.type === OverwriteType.Member && ow.id !== botId && !wanted.has(ow.id)) await ow.delete('Kein Zugriff mehr (Verknüpfung getrennt, Konto/Kunde gesperrt oder nicht mehr Mitglied)');
|
||||
}
|
||||
}
|
||||
/** Abgleich (minütlich): Kanäle für offene Tickets anlegen, Kanäle geschlossener Tickets löschen, Support-Meldekanal anlegen. */
|
||||
export async function reconcileTicketChannels(log: (m: string) => void): Promise<void> {
|
||||
|
|
@ -256,7 +275,7 @@ export async function reconcileTicketChannels(log: (m: string) => void): Promise
|
|||
const [open] = await pool.query("SELECT tk.id, tk.org_id, tt.thread_id FROM tickets tk LEFT JOIN ticket_discord_threads tt ON tt.ticket_id = tk.id WHERE tk.status <> 'closed' AND (tt.thread_id IS NOT NULL OR tk.created_at < DATE_SUB(UTC_TIMESTAMP(3), INTERVAL 2 MINUTE))") as any;
|
||||
for (const r of open) {
|
||||
const res = await ensureTicketChannel(s, r.id, true);
|
||||
if (res && !res.created) await grantCustomers(res.channel, r.org_id);
|
||||
if (res && !res.created) await syncCustomerAccess(res.channel, r.org_id);
|
||||
}
|
||||
}
|
||||
/** Nachricht ins Ticket in Discord übernehmen. Kategorie-Modus: Kanal je Ticket (legt ihn bei Bedarf an).
|
||||
|
|
@ -268,7 +287,7 @@ export async function postTicketMessage(ticketId: string, body: string, authorLa
|
|||
const res = await ensureTicketChannel(s, ticketId, false);
|
||||
if (!res) return; // Ticket geschlossen oder unbekannt
|
||||
const t = await pool.query('SELECT org_id FROM tickets WHERE id = ?', [ticketId]).then(([r]: any) => r[0]);
|
||||
if (t && !res.created) await grantCustomers(res.channel, t.org_id);
|
||||
if (t && !res.created) await syncCustomerAccess(res.channel, t.org_id);
|
||||
await res.channel.send({ content: `**${authorLabel}:** ${body}`.slice(0, 2000), allowedMentions: { parse: [] } });
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
9
packages/platform/src/ticketPolicy.ts
Normal file
9
packages/platform/src/ticketPolicy.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
/** Ticket-Rechte je Rolle – EINE Quelle für API (KcModule.permissions im Tickets-Modul) und Worker (Discord), damit
|
||||
* z. B. die Buchhaltung über Discord nicht mehr darf als im Web (dort nur lesend). */
|
||||
export const TICKET_PERMISSIONS = {
|
||||
staff: { support: ['tickets.read', 'tickets.write'], accounting: ['tickets.read'], admin: ['tickets.read', 'tickets.write'], superadmin: ['tickets.read', 'tickets.write'] },
|
||||
org: { owner: ['tickets.read', 'tickets.create'], admin: ['tickets.read', 'tickets.create'], member: ['tickets.read', 'tickets.create'] },
|
||||
} as const satisfies { staff: Record<string, readonly string[]>; org: Record<string, readonly string[]> };
|
||||
|
||||
export const staffMayTicket = (staffRole: string | null | undefined, permission: 'tickets.read' | 'tickets.write'): boolean =>
|
||||
!!staffRole && ((TICKET_PERMISSIONS.staff as Record<string, readonly string[]>)[staffRole] ?? []).includes(permission);
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { csvCell, csvSafe } from '../src/csv.js';
|
||||
|
||||
describe('CSV-Zellen (Formel-Injection)', () => {
|
||||
it('neutralisiert Formelanfänge in Textzellen', () => {
|
||||
for (const s of ['=1+1', '+49 123', '-2+3', '@SUM(A1)', '\t=1', '\r=1']) expect(csvSafe(s).startsWith("'")).toBe(true);
|
||||
expect(csvCell('=HYPERLINK("http://x")')).toBe(`"'=HYPERLINK(""http://x"")"`);
|
||||
expect(csvCell('Kunde A; GmbH')).toBe('"Kunde A; GmbH"');
|
||||
});
|
||||
it('lässt normale Texte unverändert', () => {
|
||||
expect(csvCell('Musterfirma GmbH')).toBe('Musterfirma GmbH');
|
||||
expect(csvCell('')).toBe('');
|
||||
});
|
||||
});
|
||||
24
packages/platform/test/helpers.test.ts
Normal file
24
packages/platform/test/helpers.test.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { csvCell, csvSafe } from '../src/csv.js';
|
||||
|
||||
describe('CSV-Zellen (Formel-Injection)', () => {
|
||||
it('neutralisiert Formelanfänge in Textzellen', () => {
|
||||
for (const s of ['=1+1', '+49 123', '-2+3', '@SUM(A1)', '\t=1', '\r=1']) expect(csvSafe(s).startsWith("'")).toBe(true);
|
||||
expect(csvCell('=HYPERLINK("http://x")')).toBe(`"'=HYPERLINK(""http://x"")"`);
|
||||
expect(csvCell('Kunde A; GmbH')).toBe('"Kunde A; GmbH"');
|
||||
});
|
||||
it('lässt normale Texte unverändert', () => {
|
||||
expect(csvCell('Musterfirma GmbH')).toBe('Musterfirma GmbH');
|
||||
expect(csvCell('')).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
import { staffMayTicket } from '../src/ticketPolicy.js';
|
||||
describe('Ticket-Policy (gemeinsam für Web und Discord, #110)', () => {
|
||||
it('Buchhaltung darf lesen, aber nicht schreiben; Support/Admin dürfen schreiben; Kunden-/unbekannte Rollen nichts', () => {
|
||||
expect(staffMayTicket('accounting', 'tickets.read')).toBe(true);
|
||||
expect(staffMayTicket('accounting', 'tickets.write')).toBe(false);
|
||||
for (const r of ['support', 'admin', 'superadmin']) expect(staffMayTicket(r, 'tickets.write')).toBe(true);
|
||||
expect(staffMayTicket(null, 'tickets.read')).toBe(false); expect(staffMayTicket('owner', 'tickets.read')).toBe(false);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue