feat: Admin-Bereich im Kundenportal (Ticketsystem-Login, Projektsuche, Kundenverwaltung)

- Login: Appwrite-User mit Label 'admin' (Ticketsystem-Mitarbeiter) bekommen
  eine Admin-Session und landen auf /admin.html
- Admin-Dashboard: Statistik-Uebersicht, Projektsuche ueber alle Projekte
  (inkl. Preview-/Gitea-Links, Vorschau ohne Kunden-Login), Kundenliste mit
  Portal-Status, letztem Login und Projektanzahl
- Kundennummer (code) direkt im Admin-Bereich pflegbar
- 'Als Kunde ansehen': Admin sieht das Portal exakt wie der Kunde (Banner
  mit Rueckweg zur Admin-Uebersicht)
- Kunden-Dashboard: neue Bereiche 'Meine Rechnungen' (InvoiceNinja inkl.
  Link ins Rechnungsportal) und 'Was wurde gemacht' (Tickets + Worksheets
  aus dem Ticketsystem, ohne interne Akquise-Tickets); Kundennummer im Header
- Admin-API /api/portal-admin/* (Session-basiert), Kunden-API /api/invoices
  und /api/activity
- appwriteClient: uebrig gebliebene Debug-Instrumentierung entfernt

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-11 17:09:39 +00:00
parent 0320042045
commit 177ee6a13d
12 changed files with 1085 additions and 54 deletions

View File

@@ -1,22 +1,5 @@
import { config } from '../config.js'
const DEBUG_LOG = (location, message, data, hypothesisId) => {
// #region agent log
fetch('http://127.0.0.1:7281/ingest/30e8e71c-b377-4e72-84f9-593826c6d234', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Debug-Session-Id': '80bbfc' },
body: JSON.stringify({
sessionId: '80bbfc',
location,
message,
data,
hypothesisId,
timestamp: Date.now(),
}),
}).catch(() => {})
// #endregion
}
function appwriteHeaders() {
return {
'Content-Type': 'application/json',
@@ -78,7 +61,6 @@ export async function loginWithAppwrite(email, password) {
const now = Date.now()
if (now < appwriteLoginBlockedUntil) {
const waitSec = Math.ceil((appwriteLoginBlockedUntil - now) / 1000)
DEBUG_LOG('appwriteClient.js:cooldown', 'login blocked locally', { waitSec }, 'H8')
const error = new Error(
`Zu viele Anmeldeversuche. Bitte warte noch ${waitSec} Sekunden.`
)
@@ -92,15 +74,7 @@ export async function loginWithAppwrite(email, password) {
method: 'POST',
body: { email, password },
})
DEBUG_LOG('appwriteClient.js:session', 'createEmailPasswordSession ok', {
hasUserId: Boolean(session?.userId),
sessionId: session?.$id || null,
}, 'H6')
} catch (err) {
DEBUG_LOG('appwriteClient.js:session', 'createEmailPasswordSession fail', {
message: err?.message?.slice(0, 120),
code: err?.code,
}, 'H1')
if (err.status === 429) {
appwriteLoginBlockedUntil = Date.now() + APPWRITE_RATE_LIMIT_COOLDOWN_MS
}
@@ -116,7 +90,6 @@ export async function loginWithAppwrite(email, password) {
}
const user = { $id: session.userId, email, name: '' }
DEBUG_LOG('appwriteClient.js:user', 'using session userId', { userId: user.$id }, 'H7')
clearLoginCooldown()
return user

View File

@@ -0,0 +1,57 @@
import { config } from '../config.js'
import { listDocuments, Query } from './appwriteAdmin.js'
/**
* Tickets + zugehoerige Worksheets eines Kunden ("was wurde gemacht").
* excludeTypes: Ticket-Typen, die der Kunde nicht sehen soll (z. B. Akquise).
*/
export async function getCustomerActivity(customerId, { ticketLimit = 25, excludeTypes = [] } = {}) {
if (!customerId) return []
let workorders = await listDocuments(config.collections.workorders, [
Query.equal('customerId', customerId),
Query.orderDesc('$createdAt'),
Query.limit(ticketLimit),
])
if (excludeTypes.length) {
const blocked = new Set(excludeTypes.map((t) => t.toLowerCase()))
workorders = workorders.filter((w) => !blocked.has(String(w.type || '').toLowerCase()))
}
const ids = workorders.map((w) => w.$id)
let worksheets = []
if (ids.length) {
worksheets = await listDocuments(config.collections.worksheets, [
Query.equal('workorderId', ids),
Query.orderDesc('$createdAt'),
Query.limit(300),
]).catch(() => [])
}
const sheetsByWorkorder = {}
for (const ws of worksheets) {
if (ws.isComment) continue
const list = (sheetsByWorkorder[ws.workorderId] ||= [])
list.push({
wsid: ws.wsid || '',
employeeName: ws.employeeName || ws.employeeShort || '',
serviceType: ws.serviceType || '',
newStatus: ws.newStatus || '',
totalTime: ws.totalTime || '',
date: ws.endDate || ws.startDate || '',
details: ws.details || '',
createdAt: ws.createdAt || ws.$createdAt || '',
})
}
return workorders.map((w) => ({
id: w.$id,
woid: w.woid || '',
topic: w.topic || w.title || '',
status: w.status || '',
type: w.type || '',
createdAt: w.createdAt || w.$createdAt || '',
worksheets: (sheetsByWorkorder[w.$id] || []).slice(0, 20),
}))
}

View File

@@ -35,6 +35,75 @@ export function sanitizeInvoiceClient(client) {
}
}
const INVOICE_STATUS_LABELS = {
1: 'Entwurf',
2: 'Offen',
3: 'Teilzahlung',
4: 'Bezahlt',
5: 'Storniert',
6: 'Storniert',
}
export function sanitizeInvoice(inv) {
const today = new Date().toISOString().slice(0, 10)
const balance = Number(inv.balance ?? 0)
const statusId = Number(inv.status_id ?? 0)
const overdue = balance > 0 && Boolean(inv.due_date) && inv.due_date < today && statusId !== 5
const invitationKey = inv.invitations?.[0]?.key || ''
return {
id: inv.id,
number: inv.number || '',
date: inv.date || '',
dueDate: inv.due_date || '',
amount: Number(inv.amount ?? 0),
balance,
statusId,
status: overdue ? 'Überfällig' : INVOICE_STATUS_LABELS[statusId] || 'Offen',
overdue,
poNumber: inv.po_number || '',
publicNotes: inv.public_notes || '',
// Link ins InvoiceNinja-Kundenportal (Rechnung ansehen/zahlen)
portalUrl: invitationKey ? `${config.invoiceNinja.url}/client/invoice/${invitationKey}` : '',
}
}
/** Rechnungen eines InvoiceNinja-Clients (fuer Kundenportal + Admin-Ansicht). */
export async function listInvoicesForClient(clientId, { includeDrafts = false } = {}) {
const token = config.invoiceNinja.apiToken
if (!token) {
const error = new Error('INVOICE_NINJA_API_TOKEN ist nicht konfiguriert')
error.status = 503
throw error
}
if (!clientId) return []
const url = new URL(`${config.invoiceNinja.url}/api/v1/invoices`)
url.searchParams.set('client_id', String(clientId))
url.searchParams.set('per_page', '100')
url.searchParams.set('sort', 'date|desc')
const response = await fetch(url, {
headers: {
'X-API-TOKEN': token,
'X-Requested-With': 'XMLHttpRequest',
Accept: 'application/json',
},
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
const error = new Error(data.message || 'Invoice Ninja API Fehler')
error.status = response.status === 401 ? 502 : response.status
throw error
}
return (data.data || [])
.filter((inv) => !inv.is_deleted)
.map(sanitizeInvoice)
.filter((inv) => includeDrafts || inv.statusId !== 1)
}
export async function listInvoiceNinjaClients() {
const token = config.invoiceNinja.apiToken
if (!token) {