- ci.sh: Stilprüfung (ops/test/check-style.mjs: LF, Schlusszeilenumbruch, Leerzeichen am Zeilenende, Tabs, .only/debugger, console.log in Bibliotheken/Web – meldet nur, formatiert nichts um), pnpm audit ab high, pnpm -r typecheck nach dem Build. 'pnpm check' für lokal. - Audit-Fund behoben: source-map-js >= 1.2.2 per pnpm-Override (nur Testwerkzeuge betroffen). - Worker-Tests: Job-Runner (Backoff, needs_review nach max_attempts, Lease frei) und Discord-Nachrichtenübernahme mit nachgebauten Nachrichten (Kunde, Support inkl. Mail mit Antwort-Bezug, Buchhaltung abgewiesen, gesperrter Kunde, unbekanntes Konto, geschlossenes Ticket). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7b6a56bb9f
commit
ce290143e6
7 changed files with 126 additions and 9 deletions
74
apps/api/test/worker.test.ts
Normal file
74
apps/api/test/worker.test.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { beforeAll, describe, expect, it } from 'vitest';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { one, query, run } from '../src/core/db.js';
|
||||
import { runOnce } from '../../worker/src/jobs.js';
|
||||
import { handleThreadMessage } from '../../worker/src/discord.js';
|
||||
import { makeUser } from './helpers.js';
|
||||
|
||||
const log = () => undefined;
|
||||
const runJob = async (id: string) => { await run('UPDATE jobs SET run_at = UTC_TIMESTAMP(3) WHERE id = ?', [id]); return runOnce(log); };
|
||||
|
||||
describe('Worker: Job-Runner', () => {
|
||||
it('Fehler wird mit Backoff wiederholt und landet nach max_attempts in needs_review', async () => {
|
||||
const id = randomUUID();
|
||||
await run("INSERT INTO jobs (id, type, payload, status, max_attempts, run_at) VALUES (?, 'x.unbekannt', '{}', 'scheduled', 2, UTC_TIMESTAMP(3))", [id]);
|
||||
await runJob(id);
|
||||
let j = (await one('SELECT status, attempts, run_at, last_error FROM jobs WHERE id = ?', [id]))!;
|
||||
expect(j.status).toBe('retrying'); expect(j.attempts).toBe(1); expect(j.last_error).toMatch(/Kein Handler/);
|
||||
expect(new Date(j.run_at).getTime()).toBeGreaterThan(Date.now() + 30_000); // Backoff
|
||||
await runJob(id);
|
||||
j = (await one('SELECT status, attempts, lease_id FROM jobs WHERE id = ?', [id]))!;
|
||||
expect(j.status).toBe('needs_review'); expect(j.attempts).toBe(2); expect(j.lease_id).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Worker: Discord-Nachrichten im Ticketkanal (#110)', () => {
|
||||
let org: string; let ticket: string; let customer: string; let support: string; let accounting: string;
|
||||
const channel = `chan-${randomUUID().slice(0, 8)}`;
|
||||
const replies: string[] = [];
|
||||
const msg = (authorId: string, content: string) => ({ id: randomUUID(), author: { id: authorId, bot: false }, inGuild: () => true, channel: { id: channel }, content, reply: async (t: string) => { replies.push(t); } }) as never;
|
||||
const messages = () => query('SELECT author_kind, body FROM ticket_messages WHERE ticket_id = ? ORDER BY created_at', [ticket]);
|
||||
|
||||
beforeAll(async () => {
|
||||
org = randomUUID(); await run("INSERT INTO organizations (id, customer_number, name, customer_type) VALUES (?, 'K-DISC1', 'Discord AG', 'business')", [org]);
|
||||
customer = await makeUser({ email: 'disc-kunde@example.com' }); await run("INSERT INTO memberships (org_id, user_id, role) VALUES (?,?,'owner')", [org, customer]);
|
||||
support = await makeUser({ email: 'disc-support@example.com', kind: 'staff', staffRole: 'support' });
|
||||
accounting = await makeUser({ email: 'disc-buchhaltung@example.com', kind: 'staff', staffRole: 'accounting' });
|
||||
for (const [u, d] of [[customer, 'd-kunde'], [support, 'd-support'], [accounting, 'd-buha']]) await run('UPDATE users SET discord_user_id = ? WHERE id = ?', [d, u]);
|
||||
ticket = randomUUID();
|
||||
await run("INSERT INTO tickets (id, number, org_id, subject, status, priority, created_by) VALUES (?, 'T-88001', ?, 'Discord', 'pending_customer', 'normal', ?)", [ticket, org, customer]);
|
||||
await run('INSERT INTO ticket_discord_threads (ticket_id, thread_id) VALUES (?,?)', [ticket, channel]);
|
||||
});
|
||||
|
||||
it('Kundenantwort wird übernommen und setzt „wartet auf Support“', async () => {
|
||||
await handleThreadMessage(msg('d-kunde', 'Hallo vom Kunden'), log);
|
||||
expect((await messages()).map((m) => m.body)).toEqual(['Hallo vom Kunden']);
|
||||
expect((await one('SELECT status FROM tickets WHERE id = ?', [ticket]))!.status).toBe('pending_staff');
|
||||
});
|
||||
it('Support-Antwort wird übernommen, Mail mit signiertem Antwort-Bezug wird eingeplant', async () => {
|
||||
await handleThreadMessage(msg('d-support', 'Antwort vom Support'), log);
|
||||
expect((await messages()).at(-1)).toMatchObject({ author_kind: 'staff', body: 'Antwort vom Support' });
|
||||
const job = await one("SELECT payload FROM jobs WHERE type = 'mail.template' ORDER BY created_at DESC LIMIT 1");
|
||||
const p = typeof job!.payload === 'string' ? JSON.parse(job!.payload) : job!.payload;
|
||||
expect(p.replyTicketId).toBe(ticket); expect(p.to).toBe('disc-kunde@example.com');
|
||||
});
|
||||
it('Buchhaltung (nur lesen) kann nicht antworten', async () => {
|
||||
const before = (await messages()).length;
|
||||
await handleThreadMessage(msg('d-buha', 'darf ich nicht'), log);
|
||||
expect((await messages()).length).toBe(before); expect(replies.at(-1)).toMatch(/nur lesen/);
|
||||
});
|
||||
it('gesperrter Kunde und unbekanntes Discord-Konto werden nicht übernommen', async () => {
|
||||
await run("UPDATE organizations SET status = 'suspended' WHERE id = ?", [org]);
|
||||
const before = (await messages()).length;
|
||||
await handleThreadMessage(msg('d-kunde', 'gesperrt'), log);
|
||||
await handleThreadMessage(msg('fremd-123', 'wer bin ich'), log);
|
||||
expect((await messages()).length).toBe(before); expect(replies.at(-1)).toMatch(/gesperrt/);
|
||||
await run("UPDATE organizations SET status = 'active' WHERE id = ?", [org]);
|
||||
});
|
||||
it('geschlossenes Ticket nimmt keine Nachrichten an', async () => {
|
||||
await run("UPDATE tickets SET status = 'closed' WHERE id = ?", [ticket]);
|
||||
const before = (await messages()).length;
|
||||
await handleThreadMessage(msg('d-kunde', 'noch was'), log);
|
||||
expect((await messages()).length).toBe(before); expect(replies.at(-1)).toMatch(/geschlossen/);
|
||||
});
|
||||
});
|
||||
|
|
@ -146,7 +146,8 @@ async function handle(i: ChatInputCommandInteraction): Promise<void> {
|
|||
|
||||
/** Nachricht im Ticket-Thread bzw. Ticket-Kanal übernehmen: vom Kunden als Kundenantwort, vom Personal (verknüpftes Konto)
|
||||
* als Support-Antwort wie im Kundencenter (Status "wartet auf Kunde", Mail an den Ersteller). Andere Nachrichten werden ignoriert. */
|
||||
async function handleThreadMessage(msg: Message, log: (m: string) => void): Promise<void> {
|
||||
/** Exportiert für Worker-Tests (nachgebaute Discord-Nachrichten). */
|
||||
export async function handleThreadMessage(msg: Message, log: (m: string) => void): Promise<void> {
|
||||
if (msg.author.bot || !msg.inGuild()) return;
|
||||
const t = await pool.query('SELECT tt.ticket_id, tk.number, tk.subject, tk.org_id, tk.status, tk.created_by FROM ticket_discord_threads tt JOIN tickets tk ON tk.id = tt.ticket_id WHERE tt.thread_id = ?', [msg.channel.id]).then(([r]: any) => r[0]);
|
||||
if (!t) return;
|
||||
|
|
|
|||
27
ops/test/check-style.mjs
Normal file
27
ops/test/check-style.mjs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
#!/usr/bin/env node
|
||||
// Nicht-destruktive Stil- und Hygieneprüfung für die CI (#96/#14). Formatiert nichts um – meldet nur.
|
||||
// Regeln: LF-Zeilenenden, Schlusszeilenumbruch, keine Leerzeichen am Zeilenende / Tabs in TS/TSX,
|
||||
// kein .only()/debugger in Tests/Code, kein console.log in Bibliotheken und Web (CLI und Worker-Logger ausgenommen).
|
||||
// Aufruf: node ops/test/check-style.mjs (Exit 1 bei Funden)
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const files = execFileSync('git', ['ls-files'], { encoding: 'utf8' }).split('\n').filter(Boolean)
|
||||
.filter((f) => /\.(ts|tsx|mjs|js|json|md|sql|css|yml|yaml|sh)$/.test(f) && f !== 'pnpm-lock.yaml' && !f.startsWith('docs/api-specs/'));
|
||||
const out = [];
|
||||
for (const f of files) {
|
||||
const b = readFileSync(f); const s = b.toString('utf8');
|
||||
if (b.includes('\r\n')) out.push(`${f}: CRLF-Zeilenenden`);
|
||||
if (b.length && b[b.length - 1] !== 0x0a) out.push(`${f}: kein Zeilenumbruch am Dateiende`);
|
||||
if (!/\.(ts|tsx|mjs)$/.test(f)) continue;
|
||||
s.split('\n').forEach((l, i) => {
|
||||
const at = `${f}:${i + 1}`;
|
||||
if (/[ \t]+$/.test(l)) out.push(`${at}: Leerzeichen am Zeilenende`);
|
||||
if (l.includes('\t')) out.push(`${at}: Tabulator`);
|
||||
if (/\b(it|describe|test)\.only\(/.test(l)) out.push(`${at}: .only() lässt andere Tests aus`);
|
||||
if (/^\s*debugger;?\s*$/.test(l)) out.push(`${at}: debugger`);
|
||||
if (/console\.log\(/.test(l) && /^(packages\/|apps\/web\/|apps\/api\/src\/(?!cli\/))/.test(f)) out.push(`${at}: console.log (Logger verwenden)`);
|
||||
});
|
||||
}
|
||||
if (out.length) { console.error(`Stilprüfung: ${out.length} Fund(e)\n` + out.join('\n')); process.exit(1); }
|
||||
console.log(`Stilprüfung: ${files.length} Dateien ohne Befund`);
|
||||
|
|
@ -3,8 +3,12 @@
|
|||
# aufgelöst), dann alle Testsuiten. Bricht beim ersten Fehler ab.
|
||||
set -euo pipefail
|
||||
node ops/test/check-boundaries.mjs --selftest
|
||||
node ops/test/check-style.mjs
|
||||
pnpm install --frozen-lockfile
|
||||
# Sicherheitslücken in Abhängigkeiten (ab "high") lassen den Lauf scheitern; braucht Netz zur npm-Registry
|
||||
pnpm audit --audit-level high
|
||||
pnpm build
|
||||
pnpm -r typecheck
|
||||
pnpm --filter @kc/platform test
|
||||
pnpm --filter "./packages/connector-*" test
|
||||
pnpm --filter @kc/api test
|
||||
|
|
|
|||
12
package.json
12
package.json
|
|
@ -3,7 +3,9 @@
|
|||
"private": true,
|
||||
"version": "0.0.1",
|
||||
"packageManager": "pnpm@10.14.0",
|
||||
"engines": { "node": ">=22" },
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"dev:api": "pnpm --filter @kc/api dev",
|
||||
"dev:worker": "pnpm --filter @kc/worker dev",
|
||||
|
|
@ -12,6 +14,12 @@
|
|||
"typecheck": "pnpm -r typecheck",
|
||||
"test": "pnpm -r test",
|
||||
"migrate": "pnpm --filter @kc/api migrate",
|
||||
"cli": "pnpm --filter @kc/api cli"
|
||||
"cli": "pnpm --filter @kc/api cli",
|
||||
"check": "node ops/test/check-boundaries.mjs --selftest && node ops/test/check-style.mjs"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"source-map-js": ">=1.2.2"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
13
pnpm-lock.yaml
generated
13
pnpm-lock.yaml
generated
|
|
@ -4,6 +4,9 @@ settings:
|
|||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
overrides:
|
||||
source-map-js: '>=1.2.2'
|
||||
|
||||
importers:
|
||||
|
||||
.: {}
|
||||
|
|
@ -1775,8 +1778,8 @@ packages:
|
|||
sonic-boom@4.2.1:
|
||||
resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==}
|
||||
|
||||
source-map-js@1.2.1:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
source-map-js@1.2.2:
|
||||
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
split2@4.2.0:
|
||||
|
|
@ -3136,13 +3139,13 @@ snapshots:
|
|||
dependencies:
|
||||
nanoid: 3.3.19
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.1
|
||||
source-map-js: 1.2.2
|
||||
|
||||
postcss@8.5.28:
|
||||
dependencies:
|
||||
nanoid: 3.3.19
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.1
|
||||
source-map-js: 1.2.2
|
||||
|
||||
process-warning@4.0.1: {}
|
||||
|
||||
|
|
@ -3271,7 +3274,7 @@ snapshots:
|
|||
dependencies:
|
||||
atomic-sleep: 1.0.0
|
||||
|
||||
source-map-js@1.2.1: {}
|
||||
source-map-js@1.2.2: {}
|
||||
|
||||
split2@4.2.0: {}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue