diff --git a/apps/api/src/modules/domains/index.ts b/apps/api/src/modules/domains/index.ts index 5783b57..75ef4f6 100644 --- a/apps/api/src/modules/domains/index.ts +++ b/apps/api/src/modules/domains/index.ts @@ -8,29 +8,14 @@ import { rl } from '../../core/config.js'; import type { KcModule } from '../../core/module.js'; import { randomUUID } from 'node:crypto'; import { loadInstance } from '@kc/connectors'; -import { breakdown, checkAvailability, normalizeDomain, parsePriceList, sellPrice, splitDomain, type CostBasis, type Margin } from './logic.js'; +import { checkAvailability, domainOffer as offer, domainQuote as snapshot, domainSettings as settings, domainTaxBp as taxBp, normalizeDomain, parsePriceList, sellPrice, splitDomain, type Margin } from '@kc/platform/domains'; -const taxBp = async () => Number((await one("SELECT rate_bp FROM tax_rates WHERE name LIKE 'Regelsteuersatz%' LIMIT 1"))?.rate_bp ?? 1900); -/** Preis-Schnappschuss für eine Domain: Einkauf brutto/netto und errechneter Verkauf brutto/netto. Null-Preise, wenn Endung fehlt oder kein Aufschlag festgelegt ist. */ -async function snapshot(tld: string) { - const s = await settings(); const r = await one('SELECT * FROM domain_tlds WHERE tld = ?', [tld]); const tax = await taxBp(); - if (!r) return { termMonths: null, costNet: null, costGross: null, setup: 0, net: null, gross: null, tax }; - const o = offer(r, s.tier, s.margin, s.rounding, s.basis, tax); - return { termMonths: o.termMonths, costNet: o.costNetCents, costGross: o.costGrossCents, setup: o.setupGrossCents, net: o.priceNetCents, gross: o.priceGrossCents, tax }; -} const recView = (r: any) => ({ id: r.id, domain: r.domain, tld: r.tld, orgId: r.org_id, customer: r.org_name ?? null, customerNumber: r.customer_number ?? null, resourceId: r.resource_id, source: r.source, termMonths: r.term_months, costNetCents: r.cost_net_cents, costGrossCents: r.cost_gross_cents, setupCostCents: r.setup_cost_cents, sellNetCents: r.sell_net_cents, taxBp: r.tax_bp, sellGrossCents: r.sell_gross_cents, profitNetCents: r.sell_net_cents === null || r.cost_net_cents === null ? null : r.sell_net_cents - r.cost_net_cents, procurement: r.procurement, orderedAt: r.ordered_at, note: r.note, pricedAt: r.priced_at, createdAt: r.created_at }); const REC_SELECT = 'SELECT d.*, o.name AS org_name, o.customer_number FROM domain_records d LEFT JOIN organizations o ON o.id = d.org_id'; const SUGGEST = ['de', 'com', 'net', 'org', 'eu', 'info']; const marginIn = z.object({ type: z.enum(['percent', 'fixed']).nullable(), value: z.number().int().min(0).max(100_000_00).nullable() }).refine((m) => (m.type === null) === (m.value === null), 'Art und Wert gehören zusammen'); -async function settings() { const s = await one('SELECT tier, margin_type, margin_value, rounding, cost_basis FROM domain_settings WHERE id = 1'); return { tier: Number(s?.tier ?? 1), rounding: s ? !!s.rounding : true, basis: (s?.cost_basis ?? 'gross') as CostBasis, margin: { type: s?.margin_type ?? null, value: s?.margin_value ?? null } as Margin }; } -const offer = (r: any, tier: number, g: Margin, round: boolean, basis: CostBasis, tax: number) => { - const list = Number(r[`cost${tier}_cents`]); const own: Margin = { type: r.margin_type, value: r.margin_value }; const b = breakdown(list, own, g, round, basis, tax); - const setupGross = basis === 'gross' ? r.setup_cents : r.setup_cents + Math.round((r.setup_cents * tax) / 10000); - return { tld: r.tld, termMonths: r.term_months, ...b, setupGrossCents: setupGross as number, setupNetCents: Math.round((setupGross * 10000) / (10000 + tax)), taxBp: tax, margin: own, active: !!r.active }; -}; - export const domainsModule: KcModule = { name: 'domains', permissions: { staff: { support: ['domains.read'], accounting: ['domains.read'], admin: ['domains.read', 'domains.write'], superadmin: ['domains.read', 'domains.write'] } }, diff --git a/apps/api/src/modules/domains/logic.ts b/apps/api/src/modules/domains/logic.ts index 79de065..1f00dac 100644 --- a/apps/api/src/modules/domains/logic.ts +++ b/apps/api/src/modules/domains/logic.ts @@ -1,93 +1,2 @@ -import { domainToASCII } from 'node:url'; -import { promises as dns } from 'node:dns'; - -export type MarginType = 'percent' | 'fixed'; -export interface Margin { type: MarginType | null; value: number | null } -/** Kaufmännische Rundung nach oben: Cent-Anteil 00–50 → ,50; 51–99 → ,99 (z. B. 12,00 → 12,50; 12,51 → 12,99). */ -export function roundPrice(cents: number): number { const euro = Math.floor(cents / 100), c = cents % 100; return euro * 100 + (c <= 50 ? 50 : 99); } -/** Verkaufspreis (netto, Cent) = Einkauf + Gewinnaufschlag; null, wenn kein Aufschlag festgelegt ist. Prozent in Basispunkten. */ -export function sellPrice(costCents: number, own: Margin, global: Margin, round = false): number | null { - const m = own.type && own.value !== null ? own : global; if (!m.type || m.value === null) return null; - const p = costCents + (m.type === 'percent' ? Math.round((costCents * m.value) / 10000) : m.value); return round ? roundPrice(p) : p; -} - -export type CostBasis = 'gross' | 'net'; -export interface Breakdown { costGrossCents: number; costNetCents: number; priceGrossCents: number | null; priceNetCents: number | null; profitNetCents: number | null } -/** Preise aus dem Listenpreis: Ist die Liste brutto (inkl. USt), wird Netto herausgerechnet, nie erneut USt aufgeschlagen. Rundung und Aufschlag wirken auf die Listenbasis. */ -export function breakdown(listCost: number, own: Margin, global: Margin, round: boolean, basis: CostBasis, taxBp: number): Breakdown { - const toNet = (g: number) => Math.round((g * 10000) / (10000 + taxBp)); const vat = (n: number) => Math.round((n * taxBp) / 10000); - const p = sellPrice(listCost, own, global, round); - const costGross = basis === 'gross' ? listCost : listCost + vat(listCost); const costNet = basis === 'gross' ? toNet(listCost) : listCost; - if (p === null) return { costGrossCents: costGross, costNetCents: costNet, priceGrossCents: null, priceNetCents: null, profitNetCents: null }; - const g = basis === 'gross' ? p : p + vat(p); const n = basis === 'gross' ? toNet(p) : p; - return { costGrossCents: costGross, costNetCents: costNet, priceGrossCents: g, priceNetCents: n, profitNetCents: n - costNet }; -} -export interface ParsedRow { tld: string; termMonths: number; costs: [number, number, number, number]; setupCents: number } -const num = (s: string): number | null => { - const t = s.replace(/[€\s]/g, ''); if (!t) return null; - const n = t.includes(',') ? t.replace(/\./g, '').replace(',', '.') : t; // deutsches Format 1.380,00 oder 26.60 - return /^\d+(\.\d+)?$/.test(n) ? Math.round(Number(n) * 100) : null; -}; -/** Liest eine Preisliste (Tabulator/Leerzeichen getrennt): Endung, Laufzeit, 4 Staffelpreise, optional Setup. Kopf-/Fußzeilen werden übersprungen. */ -export function parsePriceList(text: string): { rows: ParsedRow[]; skipped: string[] } { - const rows: ParsedRow[] = []; const skipped: string[] = []; const seen = new Set(); - for (const raw of text.split(/\r?\n/)) { - const line = raw.trim(); if (!line || line.startsWith('#')) continue; - const c = line.split(/[\t ]+/).filter((x) => x !== '€'); - const tld = (c[0] ?? '').toLowerCase().replace(/^\./, ''); - if (!/^[a-z0-9]([a-z0-9.-]{0,60}[a-z0-9])?$/.test(tld) || !/^\d{1,3}$/.test(c[1] ?? '')) { if (!/^Domaintyp/i.test(line)) skipped.push(line.slice(0, 80)); continue; } - const p = [2, 3, 4, 5].map((i) => num(c[i] ?? '')); const setup = c[6] !== undefined ? num(c[6]) : 0; - if (p.some((x) => x === null) || setup === null) { skipped.push(line.slice(0, 80)); continue; } - if (seen.has(tld)) { skipped.push(`doppelt: ${tld}`); continue; } seen.add(tld); - rows.push({ tld, termMonths: Number(c[1]), costs: p as [number, number, number, number], setupCents: setup }); - } - return { rows, skipped }; -} - -/** Normalisiert Eingaben wie „https://www.Beispiel.de/x“ zu „beispiel.de“ (Punycode). */ -export function normalizeDomain(input: string): string | null { - let s = input.trim().toLowerCase().replace(/^[a-z]+:\/\//, '').replace(/[/?#].*$/, '').replace(/^www\./, '').replace(/\.$/, ''); - if (!s || s.length > 253) return null; s = domainToASCII(s); if (!s) return null; - return s.split('.').every((l) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(l)) ? s : null; -} -/** Trennt Name und Endung; bekannte mehrteilige Endungen (co.uk) werden bevorzugt. */ -export function splitDomain(name: string, known: Set): { label: string; tld: string } | null { - const parts = name.split('.'); if (parts.length < 2) return null; - for (let i = 1; i < parts.length; i++) { const tld = parts.slice(i).join('.'); if (known.has(tld) && parts.slice(0, i).length === 1) return { label: parts[0]!, tld }; } - for (let i = 1; i < parts.length; i++) { const tld = parts.slice(i).join('.'); if (known.has(tld)) return { label: parts.slice(0, i).join('.'), tld }; } - return { label: parts.slice(0, -1).join('.'), tld: parts[parts.length - 1]! }; -} - -export type Availability = { status: 'available' | 'registered' | 'unknown'; method: 'rdap' | 'dns'; note?: string }; -/** Ergänzung für Endungen, die nicht in der IANA-Liste stehen, aber eine RDAP-Auskunft anbieten. */ -const EXTRA_RDAP: Record = { de: 'https://rdap.denic.de/' }; -let boot: { at: number; map: Map } | null = null; -async function rdapBase(tld: string): Promise { - if (!boot || Date.now() - boot.at > 24 * 3600_000) { - const r = await fetch('https://data.iana.org/rdap/dns.json', { signal: AbortSignal.timeout(8000) }); if (!r.ok) throw new Error(`IANA ${r.status}`); - const j = (await r.json()) as { services: [string[], string[]][] }; const map = new Map(); - for (const [tlds, urls] of j.services) { const u = urls.find((x) => x.startsWith('https://')); if (u) for (const t of tlds) map.set(t.toLowerCase(), u.endsWith('/') ? u : `${u}/`); } - boot = { at: Date.now(), map }; - } - const last = tld.split('.').pop()!; return boot.map.get(last) ?? EXTRA_RDAP[last] ?? null; -} -async function viaDns(name: string): Promise { - try { await dns.resolveNs(name); return { status: 'registered', method: 'dns' }; } catch (e) { - const c = (e as { code?: string }).code; - if (c === 'ENOTFOUND') return { status: 'available', method: 'dns', note: 'Ermittelt über DNS, ohne Gewähr. Vor der Bestellung wird beim Registrar erneut geprüft.' }; - if (c === 'ENODATA') { try { await dns.resolveSoa(name); return { status: 'registered', method: 'dns' }; } catch { return { status: 'unknown', method: 'dns' }; } } - return { status: 'unknown', method: 'dns' }; - } -} -/** Prüft, ob eine Domain vergeben ist: bevorzugt per RDAP (Registry-Auskunft), sonst per DNS. */ -export async function checkAvailability(name: string): Promise { - try { - const base = await rdapBase(name.split('.').slice(1).join('.')); - if (base) { - const r = await fetch(`${base}domain/${encodeURIComponent(name)}`, { signal: AbortSignal.timeout(7000), headers: { accept: 'application/rdap+json, application/json' }, redirect: 'follow' }); - if (r.status === 200) return { status: 'registered', method: 'rdap' }; - if (r.status === 404) return { status: 'available', method: 'rdap' }; - } - } catch { /* Fallback auf DNS */ } - return viaDns(name); -} +// Domain-Preislogik und Prüfung liegen in @kc/platform/domains (gemeinsam mit Bestellungen, #80). +export * from '@kc/platform/domains'; diff --git a/apps/api/src/modules/orders/index.ts b/apps/api/src/modules/orders/index.ts index 978ad80..167c2f0 100644 --- a/apps/api/src/modules/orders/index.ts +++ b/apps/api/src/modules/orders/index.ts @@ -14,16 +14,18 @@ import { clientIp, requireAuth, requirePermission, type AuthContext } from '../. import { badRequest, conflict, forbidden, notFound } from '../../core/errors.js'; import { can, canInOrg } from '../../core/policy.js'; import type { KcModule } from '../../core/module.js'; +import { domainQuote, normalizeDomain, splitDomain } from '@kc/platform/domains'; const j = (v: unknown, d: unknown = null) => (v == null ? d : typeof v === 'string' ? JSON.parse(v) : v); async function nextNumber(c: PoolConnection, name: 'order' | 'contract', prefix: string): Promise { await run('UPDATE number_sequences SET next_value = LAST_INSERT_ID(next_value + 1) WHERE name = ?', [name], c); return `${prefix}-${(await one('SELECT LAST_INSERT_ID() AS n', [], c))!.n}`; } -const orderView = (o: any, items: any[] = []) => ({ +const orderView = (o: any, items: any[] = [], domains: any[] = []) => ({ id: o.id, number: o.number, orgId: o.org_id, orgName: o.org_name, status: o.status, placedVia: o.placed_via, approvalRequired: !!o.approval_required, note: o.note, failureNote: o.failure_note, failureAmbiguous: !!o.failure_ambiguous, createdAt: o.created_at, approvedAt: o.approved_at, items: items.map((i) => ({ id: i.id, quantity: i.quantity, discountBp: i.discount_bp, snapshot: j(i.snapshot_json), contractId: i.contract_id ?? null, contractNumber: i.contract_number ?? null })), + domains: domains.map((d) => ({ domain: d.domain, termMonths: d.term_months, setupGrossCents: d.setup_gross_cents, sellNetCents: d.sell_net_cents, sellGrossCents: d.sell_gross_cents, taxBp: d.tax_bp, recorded: !!d.domain_record_id })), }); const contractView = (c: any) => ({ id: c.id, number: c.number, orgId: c.org_id, orgName: c.org_name, status: c.status, productName: c.product_name, startedAt: c.started_at, termEnd: c.term_end, renewal: c.renewal, renewalTermMonths: c.renewal_term_months, @@ -34,7 +36,8 @@ async function loadOrder(id: string) { const o = await one(`${ORDER_SQL} WHERE o.id = ?`, [id]); if (!o) return null; const items = await query('SELECT oi.*, c.id AS contract_id, c.number AS contract_number FROM order_items oi LEFT JOIN contracts c ON c.order_item_id = oi.id WHERE oi.order_id = ?', [id]); - return { o, items }; + const domains = await query('SELECT * FROM order_domains WHERE order_id = ? ORDER BY domain', [id]); + return { o, items, domains }; } const CONTRACT_SQL = `SELECT c.*, g.name AS org_name, JSON_VALUE(c.price_snapshot_json, '$.name') AS product_name FROM contracts c JOIN organizations g ON g.id = c.org_id`; @@ -45,6 +48,18 @@ async function orderEvent(c: PoolConnection | undefined, id: string, from: strin if (!r.affectedRows) throw conflict('Die Bestellung wurde inzwischen geändert. Bitte neu laden.', 'STALE_STATE'); return to; } +/** Freigegebene Domain-Positionen in die Domain-Aufstellung übernehmen (Beschaffung offen, Preis aus dem Bestell-Snapshot). + * Ist die Domain inzwischen anderweitig erfasst, bricht die Freigabe ab (409) statt still zu doppeln. */ +async function materializeDomains(c: PoolConnection, orderId: string): Promise { + const o = await one('SELECT org_id, number FROM orders WHERE id = ?', [orderId], c); + for (const d of await query('SELECT * FROM order_domains WHERE order_id = ? AND domain_record_id IS NULL', [orderId], c)) { + if (await one('SELECT 1 AS x FROM domain_records WHERE domain = ?', [d.domain], c)) throw conflict(`${d.domain} ist inzwischen bereits erfasst – bitte prüfen`, 'DOMAIN_EXISTS'); + const q = j(d.snapshot_json); const rid = randomUUID(); + await run("INSERT INTO domain_records (id, domain, tld, org_id, source, term_months, cost_net_cents, cost_gross_cents, setup_cost_cents, sell_net_cents, tax_bp, sell_gross_cents, procurement, note, priced_at) VALUES (?,?,?,?, 'manual', ?,?,?,?,?,?,?, 'open', ?, UTC_TIMESTAMP(3))", + [rid, d.domain, d.tld, o!.org_id, d.term_months, q.costNet, q.costGross, d.setup_gross_cents, d.sell_net_cents, d.tax_bp, d.sell_gross_cents, `Bestellung ${o!.number}`], c); + await run('UPDATE order_domains SET domain_record_id = ? WHERE id = ?', [rid, d.id], c); + } +} const startProvisioning = (orderId: string, key: string, correlationId: string) => enqueue('order.provision', { orderId }, { idempotencyKey: key, correlationId }); const orderAccess = (a: AuthContext, orgId: string) => canInOrg(a.principal, orgId, 'orders.read', 'orders.read'); @@ -61,7 +76,7 @@ export const ordersModule: KcModule = { // ---- Bestellung anlegen ------------------------------------------------ app.post('/orders', async (req) => { const a = requireAuth(req); - const b = z.object({ orgId: z.string().uuid(), note: z.string().trim().max(500).optional(), items: z.array(z.object({ productId: z.string().uuid(), quantity: z.number().int().min(1).max(100).default(1), discountBp: z.number().int().min(0).max(10000).default(0), termMonths: z.number().int().min(1).max(120).optional() })).min(1).max(20) }).parse(req.body); + const b = z.object({ orgId: z.string().uuid(), note: z.string().trim().max(500).optional(), items: z.array(z.object({ productId: z.string().uuid(), quantity: z.number().int().min(1).max(100).default(1), discountBp: z.number().int().min(0).max(10000).default(0), termMonths: z.number().int().min(1).max(120).optional() })).min(1).max(20), domains: z.array(z.object({ name: z.string().trim().min(3).max(253) })).max(10).default([]) }).parse(req.body); const staff = can(a.principal, 'orders.write'); if (!canInOrg(a.principal, b.orgId, 'orders.create', 'orders.write')) { if (!canInOrg(a.principal, b.orgId, 'orders.read', 'orders.read')) throw notFound(); throw forbidden(); } const org = await one('SELECT id, status, customer_type FROM organizations WHERE id = ?', [b.orgId]); @@ -90,7 +105,22 @@ export const ordersModule: KcModule = { if (org.customer_type === 'private' && terms.renewal === 'auto') terms = { ...terms, ...consumerTerms(terms.renewalTermMonths, terms.noticeDays) }; // Verbraucherregel, rechtlich zu prüfen lines.push({ p, it, snapshot: { productId: p.id, sku: p.sku, productVersionId: p.vid, version: p.version, name: p.vname, category: p.category, customerType: org.customer_type, ...price, terms } }); } - const approvalRequired = !staff && lines.some((l) => !!l.p.requires_approval); // Personal bestellt = freigegeben + // Domains als eigene Positionen (#80): Preis und Laufzeit IMMER serverseitig aus der Domain-Preisliste; ohne + // Verkaufspreis (kein Aufschlag festgelegt) keine Bestellung – nie eine 0-Euro-Domain. + const domainLines: { name: string; tld: string; q: Awaited> }[] = []; + if (b.domains.length) { + const known = new Set((await query('SELECT tld FROM domain_tlds WHERE active = 1')).map((r) => String(r.tld))); + for (const d of b.domains) { + const name = normalizeDomain(d.name); const sp = name ? splitDomain(name, known) : null; + if (!name || !sp) throw badRequest(`„${d.name}“ ist keine gültige Domain mit angebotener Endung`, 'DOMAIN_INVALID'); + if (domainLines.some((x) => x.name === name)) throw badRequest(`${name} ist doppelt angegeben`, 'DOMAIN_DUPLICATE'); + if (await one('SELECT 1 AS x FROM domain_records WHERE domain = ?', [name])) throw conflict(`${name} ist bereits erfasst`, 'DOMAIN_EXISTS'); + const q = await domainQuote(sp.tld); + if (q.net === null || q.gross === null || !q.termMonths) throw badRequest(`Für .${sp.tld} gibt es derzeit keinen Verkaufspreis – bitte beim Support anfragen`, 'DOMAIN_NO_PRICE'); + domainLines.push({ name, tld: sp.tld, q }); + } + } + const approvalRequired = !staff && (lines.some((l) => !!l.p.requires_approval) || domainLines.length > 0); // Domains prüft immer das Personal (Verfügbarkeit erst beim Registrar sicher) const orderId = randomUUID(); const number = await tx(async (c) => { const n = await nextNumber(c, 'order', 'B'); @@ -102,10 +132,12 @@ export const ordersModule: KcModule = { await run("INSERT INTO contracts (id, number, org_id, order_item_id, product_version_id, status, renewal, renewal_term_months, notice_days, price_snapshot_json) VALUES (?,?,?,?,?,'pending',?,?,?,?)", [randomUUID(), await nextNumber(c, 'contract', 'V'), b.orgId, itemId, l.snapshot.productVersionId, l.snapshot.terms.renewal, l.snapshot.terms.renewalTermMonths, l.snapshot.terms.noticeDays, JSON.stringify(l.snapshot)], c); } - if (!approvalRequired) { await orderEvent(c, orderId, 'approved', 'start_provisioning'); await startProvisioning(orderId, `provision:${orderId}:1`, req.correlationId); } + for (const d of domainLines) await run('INSERT INTO order_domains (id, order_id, domain, tld, term_months, setup_gross_cents, sell_net_cents, sell_gross_cents, tax_bp, snapshot_json) VALUES (?,?,?,?,?,?,?,?,?,?)', + [randomUUID(), orderId, d.name, d.tld, d.q.termMonths, d.q.setup, d.q.net, d.q.gross, d.q.tax, JSON.stringify(d.q)], c); + if (!approvalRequired) { await materializeDomains(c, orderId); await orderEvent(c, orderId, 'approved', 'start_provisioning'); await startProvisioning(orderId, `provision:${orderId}:1`, req.correlationId); } return n; }); - await audit({ actorType: 'user', actorId: a.user.id, orgId: b.orgId, action: 'order.create', resourceType: 'order', resourceId: orderId, correlationId: req.correlationId, ip: clientIp(req), after: { number, approvalRequired, items: lines.map((l) => ({ sku: l.snapshot.sku, quantity: l.it.quantity, discountBp: l.it.discountBp })) } }); + await audit({ actorType: 'user', actorId: a.user.id, orgId: b.orgId, action: 'order.create', resourceType: 'order', resourceId: orderId, correlationId: req.correlationId, ip: clientIp(req), after: { number, approvalRequired, items: lines.map((l) => ({ sku: l.snapshot.sku, quantity: l.it.quantity, discountBp: l.it.discountBp })), domains: domainLines.map((d) => d.name) } }); return { id: orderId, number, status: approvalRequired ? 'pending_approval' : 'provisioning' }; }); @@ -126,7 +158,7 @@ export const ordersModule: KcModule = { const { id } = z.object({ id: z.string().uuid() }).parse(req.params); const r = await loadOrder(id); if (!r || !orderAccess(a, r.o.org_id)) throw notFound(); - return orderView(r.o, r.items); + return orderView(r.o, r.items, r.domains); }); // ---- Freigabe, Ablehnung, Storno, Wiederholung ------------------------- @@ -134,7 +166,7 @@ export const ordersModule: KcModule = { const a = requirePermission(req, 'orders.approve'); const { id } = z.object({ id: z.string().uuid() }).parse(req.params); const r = await loadOrder(id); if (!r) throw notFound(); - await tx(async (c) => { await orderEvent(c, id, r.o.status, 'approve', { sql: 'approved_by = ?, approved_at = ?', params: [a.user.id, new Date()] }); await orderEvent(c, id, 'approved', 'start_provisioning'); await startProvisioning(id, `provision:${id}:1`, req.correlationId); }); + await tx(async (c) => { await orderEvent(c, id, r.o.status, 'approve', { sql: 'approved_by = ?, approved_at = ?', params: [a.user.id, new Date()] }); await materializeDomains(c, id); await orderEvent(c, id, 'approved', 'start_provisioning'); await startProvisioning(id, `provision:${id}:1`, req.correlationId); }); await audit({ actorType: 'user', actorId: a.user.id, orgId: r.o.org_id, action: 'order.approve', resourceType: 'order', resourceId: id, correlationId: req.correlationId, ip: clientIp(req) }); return { status: 'provisioning' }; }); diff --git a/apps/api/test/order-domains.test.ts b/apps/api/test/order-domains.test.ts new file mode 100644 index 0000000..c866401 --- /dev/null +++ b/apps/api/test/order-domains.test.ts @@ -0,0 +1,59 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import type { FastifyInstance } from 'fastify'; +import { buildApp } from '../src/server.js'; +import { one, query, run } from '../src/core/db.js'; +import { call, code, login, makeUser } from './helpers.js'; + +let app: FastifyInstance; +beforeAll(async () => { app = await buildApp(); await app.ready(); }); +async function staff(email: string, role: string) { + await makeUser({ email, kind: 'staff', staffRole: role }); const { client } = await login(app, email); + const s = (await call(app, client, 'POST', '/auth/mfa/setup')).json(); await call(app, client, 'POST', '/auth/mfa/confirm', { code: code(s.secret) }); return client; +} +async function customer(admin: any, name: string, mail: string) { + const c = (await call(app, admin, 'POST', '/admin/customers', { type: 'business', name, owner: { email: mail, name } })).json(); + await app.inject({ method: 'POST', url: '/v1/auth/invite/accept', payload: { token: new URL(c.inviteLink).searchParams.get('token'), password: 'passwort-kunde-123', repeat: 'passwort-kunde-123' } }); + return { org: c.id as string, client: (await login(app, mail, 'passwort-kunde-123')).client }; +} + +describe('Bestellung: Hosting + Domain als getrennte Positionen (#80)', () => { + it('Preis/Laufzeit serverseitig aus der Domain-Preisliste, Freigabe durch Personal, Übernahme in die Domain-Aufstellung', async () => { + const admin = await staff('dom-admin@example.com', 'admin'); + const A = await customer(admin, 'Domain Kunde', 'dom-kunde@example.com'); + // Domain-Preisliste: .de mit Aufschlag, .xyz ohne Aufschlag (kein Verkaufspreis) + await run("INSERT INTO domain_tlds (tld, term_months, cost1_cents, cost2_cents, cost3_cents, cost4_cents, setup_cents, margin_type, margin_value) VALUES ('de', 12, 600, 550, 500, 450, 0, 'percent', 5000), ('xyz', 12, 1000, 1000, 1000, 1000, 0, NULL, NULL) ON DUPLICATE KEY UPDATE margin_type = VALUES(margin_type), margin_value = VALUES(margin_value)"); + const tax = (await call(app, admin, 'GET', '/admin/tax-rates')).json(); const t19 = tax.find((t: any) => t.rateBp === 1900).id; + const prod = (await call(app, admin, 'POST', '/admin/products', { sku: 'WEB-S', category: 'hosting', orderableByCustomer: true, requiresApproval: false, customerActions: [], status: 'active', + version: { name: 'Webhosting S', taxRateId: t19, setupCents: 0, recurringCents: 500, billingInterval: 'monthly', termMonths: 1, renewal: 'auto', renewalTermMonths: 1, noticeDays: 30, provisioning: {} } })).json(); + const order = (domains: object[]) => call(app, A.client, 'POST', '/orders', { orgId: A.org, items: [{ productId: prod.id, quantity: 1 }], domains, unitPrice: 1 }); + + expect((await order([{ name: 'kein domain' }])).json().error.code).toBe('DOMAIN_INVALID'); + expect((await order([{ name: 'test.xyz' }])).json().error.code).toBe('DOMAIN_NO_PRICE'); // nie eine 0-Euro-Domain + expect((await order([{ name: 'a.de' }, { name: 'A.DE' }])).json().error.code).toBe('DOMAIN_DUPLICATE'); + + const r = await order([{ name: 'Meine-Firma.de' }]); expect(r.statusCode).toBe(200); + expect(r.json().status).toBe('pending_approval'); // Produkt ohne Freigabepflicht, aber Domains prüft immer das Personal + const o = (await call(app, A.client, 'GET', `/orders/${r.json().id}`)).json(); + expect(o.domains).toHaveLength(1); + const d = o.domains[0]; expect(d.domain).toBe('meine-firma.de'); expect(d.termMonths).toBe(12); expect(d.recorded).toBe(false); + expect(d.sellGrossCents).toBeGreaterThan(600); expect(d.sellNetCents).toBeLessThan(d.sellGrossCents); // Aufschlag auf brutto-Einkauf, kein doppelter Steuerzuschlag + expect(await one("SELECT 1 AS x FROM domain_records WHERE domain = 'meine-firma.de'")).toBeUndefined(); // vor Freigabe nicht in Beschaffung + + expect((await call(app, admin, 'POST', `/admin/orders/${r.json().id}/approve`)).statusCode).toBe(200); + const rec = (await one("SELECT org_id, procurement, sell_gross_cents, term_months, note FROM domain_records WHERE domain = 'meine-firma.de'"))!; + expect(rec.org_id).toBe(A.org); expect(rec.procurement).toBe('open'); expect(rec.sell_gross_cents).toBe(d.sellGrossCents); expect(rec.term_months).toBe(12); expect(rec.note).toMatch(/^Bestellung B-/); + expect((await call(app, A.client, 'GET', `/orders/${r.json().id}`)).json().domains[0].recorded).toBe(true); + + expect((await order([{ name: 'meine-firma.de' }])).json().error.code).toBe('DOMAIN_EXISTS'); // bereits erfasst + }); + + it('abgelehnte Bestellung legt keine Domain an', async () => { + const admin = await staff('dom-admin2@example.com', 'admin'); + const A = await customer(admin, 'Domain Kunde 2', 'dom-kunde2@example.com'); + const prod = await one("SELECT id FROM products WHERE sku = 'WEB-S'"); + const r = await call(app, A.client, 'POST', '/orders', { orgId: A.org, items: [{ productId: prod!.id, quantity: 1 }], domains: [{ name: 'abgelehnt.de' }] }); + expect((await call(app, admin, 'POST', `/admin/orders/${r.json().id}/reject`, { reason: 'Test' })).statusCode).toBe(200); + expect(await one("SELECT 1 AS x FROM domain_records WHERE domain = 'abgelehnt.de'")).toBeUndefined(); + expect((await query("SELECT domain FROM order_domains WHERE domain = 'abgelehnt.de'"))).toHaveLength(1); // Position bleibt nachvollziehbar + }); +}); diff --git a/apps/web/src/app/(app)/bestellen/page.tsx b/apps/web/src/app/(app)/bestellen/page.tsx index 275ac56..84c0266 100644 --- a/apps/web/src/app/(app)/bestellen/page.tsx +++ b/apps/web/src/app/(app)/bestellen/page.tsx @@ -16,7 +16,7 @@ export default function Bestellen() { const selPrice: Price | null = sel && (term === '' ? sel.price : { ...sel.price, recurring: sel.termPrices.find((t) => t.termMonths === term)!.price }); async function order(e: FormEvent) { e.preventDefault(); if (!sel) return; setBusy(true); setErr(''); const f = new FormData(e.currentTarget); - try { const o = await api<{ status: string; number: string }>('POST', '/orders', { orgId: org, note: (f.get('note') as string) || undefined, items: [{ productId: sel.id, quantity: 1, ...(term !== '' ? { termMonths: term } : {}), ...(staff ? { discountBp: Math.round(Number(f.get('discount') || 0) * 100) } : {}) }] }); r.push(`/bestellungen?neu=${o.number}`); } + try { const o = await api<{ status: string; number: string }>('POST', '/orders', { orgId: org, note: (f.get('note') as string) || undefined, items: [{ productId: sel.id, quantity: 1, ...(term !== '' ? { termMonths: term } : {}), ...(staff ? { discountBp: Math.round(Number(f.get('discount') || 0) * 100) } : {}) }], domains: String(f.get('domain') ?? '').trim() ? [{ name: String(f.get('domain')).trim() }] : [] }); r.push(`/bestellungen?neu=${o.number}`); } catch (x) { setErr(errMsg(x)); } finally { setBusy(false); } } return (<> @@ -36,6 +36,7 @@ export default function Bestellen() { )} {staff && } +

{staff ? 'Die Bestellung wird sofort freigegeben und bereitgestellt.' : sel.requiresApproval ? 'Ihre Bestellung wird von uns geprüft und freigegeben. Sie sehen den Stand unter „Bestellungen“.' : 'Die Bereitstellung startet sofort.'}

} diff --git a/apps/web/src/app/(app)/bestellungen/page.tsx b/apps/web/src/app/(app)/bestellungen/page.tsx index 8dfc987..20da87d 100644 --- a/apps/web/src/app/(app)/bestellungen/page.tsx +++ b/apps/web/src/app/(app)/bestellungen/page.tsx @@ -3,9 +3,9 @@ import { useCallback, useEffect, useState } from 'react'; import Link from 'next/link'; import { api, errMsg } from '@/lib/api'; import { useSession } from '@/lib/session'; -import { Alert, Empty, fmt, OrderStatusBadge, type Price, PriceText } from '@/components/ui'; +import { Alert, Empty, fmt, OrderStatusBadge, type Price, PriceText, eur } from '@/components/ui'; -interface O { id: string; number: string; orgName: string; status: string; createdAt: string; failureNote: string | null; failureAmbiguous: boolean; note: string | null; items: { id: string; quantity: number; contractId: string | null; snapshot: Price & { name: string; customerType: string } }[] } +interface O { id: string; number: string; orgName: string; status: string; createdAt: string; failureNote: string | null; failureAmbiguous: boolean; note: string | null; items: { id: string; quantity: number; contractId: string | null; snapshot: Price & { name: string; customerType: string } }[]; domains?: { domain: string; termMonths: number; setupGrossCents: number; sellNetCents: number; sellGrossCents: number; recorded: boolean }[] } export default function Bestellungen() { const { can, me } = useSession(); const staff = can('orders.read'); const approver = can('orders.approve'); const [list, setList] = useState(null); const [msg, setMsg] = useState<{ k: 'ok' | 'err'; t: string } | null>(null); const [busy, setBusy] = useState(''); const [chk, setChk] = useState>({}); @@ -20,6 +20,7 @@ export default function Bestellungen() {

{o.number}{staff && · {o.orgName}}

Bestellt am {fmt(o.createdAt)}{o.note ? ` · „${o.note}“` : ''}

{o.items.map((i) =>
{i.quantity} × {i.snapshot.name}{i.contractId && <> · Vertrag}
)} + {(o.domains ?? []).map((d) =>
Domain {d.domain}
{d.termMonths} Monate: {eur(d.sellGrossCents)} inkl. USt. ({eur(d.sellNetCents)} netto){d.setupGrossCents > 0 ? `, Einrichtung ${eur(d.setupGrossCents)}` : ''}{d.recorded ? ' · in Beschaffung' : ''}
)} {o.status === 'failed' && o.failureNote && {o.failureNote}} {o.status === 'provisioning' &&

Die Bereitstellung läuft im Hintergrund. Diese Seite aktualisiert sich automatisch.

}
diff --git a/docs/domains.md b/docs/domains.md index b5a14f5..5581089 100644 --- a/docs/domains.md +++ b/docs/domains.md @@ -18,5 +18,8 @@ Preis-Schnappschuss je Domain (EK brutto/netto, VK brutto/netto, Gewinn netto) u ## Import der Preisliste Oberfläche „Preisliste einlesen“ oder `pnpm --filter @kc/api cli import-domains --file=` (Format siehe `data/domain-preise.txt`). Aufschläge und Aktiv-Status bleiben erhalten. +## Domain in der Bestellung (#80) +Zur Hosting-Bestellung können bis zu 10 Domains angegeben werden (`domains: [{ name }]`). Preis, Laufzeit und Einrichtung kommen **serverseitig** aus der Preisliste (Snapshot in `order_domains`); ohne Verkaufspreis (kein Aufschlag) wird die Bestellung abgelehnt – nie eine 0-Euro-Domain. Bestellungen mit Domains gibt immer das Personal frei. Bei der Freigabe entsteht der Eintrag in der Domain-Aufstellung (Beschaffung „bei KCS zu bestellen“, Vermerk „Bestellung B-…“); abgelehnte Bestellungen legen nichts an. Abgerechnet wird die Domain wie bisher über „Rechnungsposition aus der Domain-Aufstellung“. + ## Offen -Registrar-API von KCS (unbekannt, Anfrage nötig), Domain als Position in der Bestellung. +Registrar-API von KCS (unbekannt, Anfrage nötig, #78); automatische Verlängerung/Abrechnung von Domains (Regel noch zu bestätigen) – bis dahin manuell. diff --git a/migrations/043_order_domains.sql b/migrations/043_order_domains.sql new file mode 100644 index 0000000..8941d84 --- /dev/null +++ b/migrations/043_order_domains.sql @@ -0,0 +1,19 @@ +-- Domain als eigene Bestellposition (#80): serverseitiger Preis-Snapshot je Domain (Laufzeit aus der Preisliste). +-- Bei Freigabe entsteht der Eintrag in der Domain-Aufstellung (Beschaffung „bei KCS zu bestellen“, manuell bis #78). +CREATE TABLE order_domains ( + id CHAR(36) PRIMARY KEY, + order_id CHAR(36) NOT NULL, + domain VARCHAR(253) NOT NULL, + tld VARCHAR(63) NOT NULL, + term_months INT NOT NULL, + setup_gross_cents INT NOT NULL DEFAULT 0, + sell_net_cents INT NOT NULL, + sell_gross_cents INT NOT NULL, + tax_bp INT NOT NULL, + snapshot_json JSON NOT NULL, + domain_record_id CHAR(36) NULL, + created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + UNIQUE KEY uq_order_domain (order_id, domain), + FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE, + FOREIGN KEY (domain_record_id) REFERENCES domain_records(id) ON DELETE SET NULL +); diff --git a/packages/platform/src/domains.ts b/packages/platform/src/domains.ts new file mode 100644 index 0000000..5edfe7d --- /dev/null +++ b/packages/platform/src/domains.ts @@ -0,0 +1,111 @@ +import { one } from './db.js'; +import { domainToASCII } from 'node:url'; +import { promises as dns } from 'node:dns'; + +export type MarginType = 'percent' | 'fixed'; +export interface Margin { type: MarginType | null; value: number | null } +/** Kaufmännische Rundung nach oben: Cent-Anteil 00–50 → ,50; 51–99 → ,99 (z. B. 12,00 → 12,50; 12,51 → 12,99). */ +export function roundPrice(cents: number): number { const euro = Math.floor(cents / 100), c = cents % 100; return euro * 100 + (c <= 50 ? 50 : 99); } +/** Verkaufspreis (netto, Cent) = Einkauf + Gewinnaufschlag; null, wenn kein Aufschlag festgelegt ist. Prozent in Basispunkten. */ +export function sellPrice(costCents: number, own: Margin, global: Margin, round = false): number | null { + const m = own.type && own.value !== null ? own : global; if (!m.type || m.value === null) return null; + const p = costCents + (m.type === 'percent' ? Math.round((costCents * m.value) / 10000) : m.value); return round ? roundPrice(p) : p; +} + +export type CostBasis = 'gross' | 'net'; +export interface Breakdown { costGrossCents: number; costNetCents: number; priceGrossCents: number | null; priceNetCents: number | null; profitNetCents: number | null } +/** Preise aus dem Listenpreis: Ist die Liste brutto (inkl. USt), wird Netto herausgerechnet, nie erneut USt aufgeschlagen. Rundung und Aufschlag wirken auf die Listenbasis. */ +export function breakdown(listCost: number, own: Margin, global: Margin, round: boolean, basis: CostBasis, taxBp: number): Breakdown { + const toNet = (g: number) => Math.round((g * 10000) / (10000 + taxBp)); const vat = (n: number) => Math.round((n * taxBp) / 10000); + const p = sellPrice(listCost, own, global, round); + const costGross = basis === 'gross' ? listCost : listCost + vat(listCost); const costNet = basis === 'gross' ? toNet(listCost) : listCost; + if (p === null) return { costGrossCents: costGross, costNetCents: costNet, priceGrossCents: null, priceNetCents: null, profitNetCents: null }; + const g = basis === 'gross' ? p : p + vat(p); const n = basis === 'gross' ? toNet(p) : p; + return { costGrossCents: costGross, costNetCents: costNet, priceGrossCents: g, priceNetCents: n, profitNetCents: n - costNet }; +} +export interface ParsedRow { tld: string; termMonths: number; costs: [number, number, number, number]; setupCents: number } +const num = (s: string): number | null => { + const t = s.replace(/[€\s]/g, ''); if (!t) return null; + const n = t.includes(',') ? t.replace(/\./g, '').replace(',', '.') : t; // deutsches Format 1.380,00 oder 26.60 + return /^\d+(\.\d+)?$/.test(n) ? Math.round(Number(n) * 100) : null; +}; +/** Liest eine Preisliste (Tabulator/Leerzeichen getrennt): Endung, Laufzeit, 4 Staffelpreise, optional Setup. Kopf-/Fußzeilen werden übersprungen. */ +export function parsePriceList(text: string): { rows: ParsedRow[]; skipped: string[] } { + const rows: ParsedRow[] = []; const skipped: string[] = []; const seen = new Set(); + for (const raw of text.split(/\r?\n/)) { + const line = raw.trim(); if (!line || line.startsWith('#')) continue; + const c = line.split(/[\t ]+/).filter((x) => x !== '€'); + const tld = (c[0] ?? '').toLowerCase().replace(/^\./, ''); + if (!/^[a-z0-9]([a-z0-9.-]{0,60}[a-z0-9])?$/.test(tld) || !/^\d{1,3}$/.test(c[1] ?? '')) { if (!/^Domaintyp/i.test(line)) skipped.push(line.slice(0, 80)); continue; } + const p = [2, 3, 4, 5].map((i) => num(c[i] ?? '')); const setup = c[6] !== undefined ? num(c[6]) : 0; + if (p.some((x) => x === null) || setup === null) { skipped.push(line.slice(0, 80)); continue; } + if (seen.has(tld)) { skipped.push(`doppelt: ${tld}`); continue; } seen.add(tld); + rows.push({ tld, termMonths: Number(c[1]), costs: p as [number, number, number, number], setupCents: setup }); + } + return { rows, skipped }; +} + +/** Normalisiert Eingaben wie „https://www.Beispiel.de/x“ zu „beispiel.de“ (Punycode). */ +export function normalizeDomain(input: string): string | null { + let s = input.trim().toLowerCase().replace(/^[a-z]+:\/\//, '').replace(/[/?#].*$/, '').replace(/^www\./, '').replace(/\.$/, ''); + if (!s || s.length > 253) return null; s = domainToASCII(s); if (!s) return null; + return s.split('.').every((l) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(l)) ? s : null; +} +/** Trennt Name und Endung; bekannte mehrteilige Endungen (co.uk) werden bevorzugt. */ +export function splitDomain(name: string, known: Set): { label: string; tld: string } | null { + const parts = name.split('.'); if (parts.length < 2) return null; + for (let i = 1; i < parts.length; i++) { const tld = parts.slice(i).join('.'); if (known.has(tld) && parts.slice(0, i).length === 1) return { label: parts[0]!, tld }; } + for (let i = 1; i < parts.length; i++) { const tld = parts.slice(i).join('.'); if (known.has(tld)) return { label: parts.slice(0, i).join('.'), tld }; } + return { label: parts.slice(0, -1).join('.'), tld: parts[parts.length - 1]! }; +} + +export type Availability = { status: 'available' | 'registered' | 'unknown'; method: 'rdap' | 'dns'; note?: string }; +/** Ergänzung für Endungen, die nicht in der IANA-Liste stehen, aber eine RDAP-Auskunft anbieten. */ +const EXTRA_RDAP: Record = { de: 'https://rdap.denic.de/' }; +let boot: { at: number; map: Map } | null = null; +async function rdapBase(tld: string): Promise { + if (!boot || Date.now() - boot.at > 24 * 3600_000) { + const r = await fetch('https://data.iana.org/rdap/dns.json', { signal: AbortSignal.timeout(8000) }); if (!r.ok) throw new Error(`IANA ${r.status}`); + const j = (await r.json()) as { services: [string[], string[]][] }; const map = new Map(); + for (const [tlds, urls] of j.services) { const u = urls.find((x) => x.startsWith('https://')); if (u) for (const t of tlds) map.set(t.toLowerCase(), u.endsWith('/') ? u : `${u}/`); } + boot = { at: Date.now(), map }; + } + const last = tld.split('.').pop()!; return boot.map.get(last) ?? EXTRA_RDAP[last] ?? null; +} +async function viaDns(name: string): Promise { + try { await dns.resolveNs(name); return { status: 'registered', method: 'dns' }; } catch (e) { + const c = (e as { code?: string }).code; + if (c === 'ENOTFOUND') return { status: 'available', method: 'dns', note: 'Ermittelt über DNS, ohne Gewähr. Vor der Bestellung wird beim Registrar erneut geprüft.' }; + if (c === 'ENODATA') { try { await dns.resolveSoa(name); return { status: 'registered', method: 'dns' }; } catch { return { status: 'unknown', method: 'dns' }; } } + return { status: 'unknown', method: 'dns' }; + } +} +/** Prüft, ob eine Domain vergeben ist: bevorzugt per RDAP (Registry-Auskunft), sonst per DNS. */ +export async function checkAvailability(name: string): Promise { + try { + const base = await rdapBase(name.split('.').slice(1).join('.')); + if (base) { + const r = await fetch(`${base}domain/${encodeURIComponent(name)}`, { signal: AbortSignal.timeout(7000), headers: { accept: 'application/rdap+json, application/json' }, redirect: 'follow' }); + if (r.status === 200) return { status: 'registered', method: 'rdap' }; + if (r.status === 404) return { status: 'available', method: 'rdap' }; + } + } catch { /* Fallback auf DNS */ } + return viaDns(name); +} + +// ---- Preis aus Datenbank (Einkaufsliste + Aufschlag), gemeinsam für Domain-Modul und Bestellungen -------- +export async function domainSettings() { const s = await one('SELECT tier, margin_type, margin_value, rounding, cost_basis FROM domain_settings WHERE id = 1'); return { tier: Number(s?.tier ?? 1), rounding: s ? !!s.rounding : true, basis: (s?.cost_basis ?? 'gross') as CostBasis, margin: { type: s?.margin_type ?? null, value: s?.margin_value ?? null } as Margin }; } +export const domainOffer = (r: any, tier: number, g: Margin, round: boolean, basis: CostBasis, tax: number) => { + const list = Number(r[`cost${tier}_cents`]); const own: Margin = { type: r.margin_type, value: r.margin_value }; const b = breakdown(list, own, g, round, basis, tax); + const setupGross = basis === 'gross' ? r.setup_cents : r.setup_cents + Math.round((r.setup_cents * tax) / 10000); + return { tld: r.tld, termMonths: r.term_months, ...b, setupGrossCents: setupGross as number, setupNetCents: Math.round((setupGross * 10000) / (10000 + tax)), taxBp: tax, margin: own, active: !!r.active }; +}; + +export const domainTaxBp = async () => Number((await one("SELECT rate_bp FROM tax_rates WHERE name LIKE 'Regelsteuersatz%' LIMIT 1"))?.rate_bp ?? 1900); +/** Preis-Schnappschuss für eine Domain: Einkauf brutto/netto und errechneter Verkauf brutto/netto. Null-Preise, wenn Endung fehlt oder kein Aufschlag festgelegt ist. */ +export async function domainQuote(tld: string) { + const s = await domainSettings(); const r = await one('SELECT * FROM domain_tlds WHERE tld = ?', [tld]); const tax = await domainTaxBp(); + if (!r) return { termMonths: null, costNet: null, costGross: null, setup: 0, net: null, gross: null, tax }; + const o = domainOffer(r, s.tier, s.margin, s.rounding, s.basis, tax); + return { termMonths: o.termMonths, costNet: o.costNetCents, costGross: o.costGrossCents, setup: o.setupGrossCents, net: o.priceNetCents, gross: o.priceGrossCents, tax }; +}