feat(akquise): mehrere Berater je Eintrag, je Berater eine Opportunity

Ein gefundenes Projekt passt oft zu mehr als einem Berater, und fuer
jeden geht eine eigene Bewerbung heraus. Das Feld "Berater" liess bisher
nur einen Namen zu.

Gespeichert wird eine kommagetrennte Liste in crm_acquisitions.consultant
(auf VARCHAR(500) erweitert, Migration in db.js) und keine eigene
Zuordnungstabelle: die Namen sind reiner Text, die Auswahlliste in
crm_acquisition_options ist eine Pflegehilfe und kein Fremdschluessel.
Suche, Sortierung und Anzeige der Liste arbeiten damit weiter auf einem
Feld. Die Funktionen zum Zerlegen stehen in acquisitionRules.js, das
Gegenstueck fuer das Frontend in src/types.ts, geprueft von
server/test/acquisition.test.mjs.

Zerlegt wird an vier Stellen:

- Uebernahme: je Berater eine Opportunity, alle in einer Transaktion.
  Ihre Titel tragen den Namen in Klammern, weil die Opportunity kein
  eigenes Feld fuer den Berater hat und in Pipeline und Liste sonst
  identische Zeilen stehen; bei einem einzigen Berater bleibt der Titel
  unveraendert. In den Notizen steht neben dem eigenen Berater auch, mit
  wem er sich das Projekt teilt. Der Eintrag merkt sich die erste
  Opportunity - sie entscheidet nur darueber, ob er wieder im Eingang
  auftaucht.
- Verlauf (crm_acquisition_history): ein Berater je Zeile. Ein Eintrag
  mit drei Beratern sind drei Bewerbungen, "Nico, Lisa" waere sonst ein
  eigener Schluessel neben "Nico" und "Lisa".
- Dashboard: dieselbe Zaehlung. Die Summe der Balken liegt damit ueber
  der Gesamtzahl "Bewerbungen", die weiter die Eintraege zaehlt.
- Auswahlliste pflegen: Umbenennen ersetzt den Namen innerhalb der
  Liste, Loeschen zaehlt auch, wer nur einer von mehreren ist. Ein
  Gleichheitsvergleich uebersah beides.

In der Oberflaeche haengt das Auswahlfeld jeweils einen Namen an, die
Gewaehlten stehen als Plaketten darunter und lassen sich einzeln
entfernen; ein bereits gewaehlter Berater verschwindet aus der Liste.
Bewusst kein <select multiple>: Strg-Klick ist mit der Maus unauffindbar
und mit einer Beruehrung gar nicht bedienbar.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sascha Wolf
2026-09-09 10:35:43 +02:00
co-authored by Claude Opus 5
parent a866cd9a52
commit 62dce64739
18 changed files with 684 additions and 91 deletions
+1 -1
View File
@@ -13,7 +13,7 @@
"dev": "node --watch src/server.js",
"migrate": "node src/migrate.js",
"scanner:import": "node src/scanner/importLegacy.js",
"test": "node test/mail.test.mjs"
"test": "node test/mail.test.mjs && node test/acquisition.test.mjs"
},
"dependencies": {
"bcryptjs": "^2.4.3",
+52
View File
@@ -59,3 +59,55 @@ export const IN_ARCHIVE = '(a.converted_at IS NOT NULL OR a.found_at < DATE_SUB(
/** Untere Grenze: was schon faellig ist, wird nicht mehr gezeigt. */
export const NOT_DUE = 'a.found_at >= DATE_SUB(CURDATE(), INTERVAL ? DAY)';
/*
* Mehrere Berater in einem Feld.
*
* Ein Fund passt oft zu mehr als einem Berater - fuer jeden davon geht eine
* Bewerbung heraus. Die Namen stehen kommagetrennt in `crm_acquisitions.consultant`
* und nicht in einer eigenen Tabelle: sie sind reiner Text (die Auswahlliste in
* crm_acquisition_options ist eine Pflegehilfe, kein Fremdschluessel), und Suche,
* Sortierung und Anzeige der Liste arbeiten weiter auf einem Feld.
*
* Der Verlauf (crm_acquisition_history) und die Auswertung zerlegen die Liste
* dagegen wieder: dort steht ein Berater je Zeile, sonst waere "Nico, Lisa" ein
* eigener Balken neben "Nico" und "Lisa".
*/
/** Trennzeichen der gespeicherten Liste - mit Leerzeichen, das ist auch die Anzeige. */
export const CONSULTANT_SEPARATOR = ', ';
/** Grenze der Spalte `consultant`; die Liste wird als Ganzes geprueft. */
export const CONSULTANT_MAX_LENGTH = 500;
/**
* Zerlegt das gespeicherte Feld in einzelne Namen. Leere Stuecke fallen weg
* (ein Komma zu viel ist kein Berater), Dubletten ebenso - beim Vergleich ohne
* Ruecksicht auf Gross- und Kleinschreibung, damit "nico" und "Nico" nicht
* zwei Balken werden. Erhalten bleibt die erste Schreibweise.
*/
export function splitConsultants(value) {
if (value === null || value === undefined) return [];
const seen = new Set();
const names = [];
for (const part of String(value).split(',')) {
const name = part.trim();
if (name === '') continue;
const key = name.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
names.push(name);
}
return names;
}
/** Setzt die Namen wieder zur gespeicherten Form zusammen; leer wird zu null. */
export function joinConsultants(names) {
const list = names.filter((name) => String(name).trim() !== '');
return list.length === 0 ? null : list.join(CONSULTANT_SEPARATOR);
}
/** Vereinheitlicht, was aus dem Formular kommt: getrimmt, ohne Dubletten, ohne Leere. */
export function normalizeConsultants(value) {
return joinConsultants(splitConsultants(value));
}
+23
View File
@@ -51,6 +51,7 @@ export async function initDatabase() {
await migrateLeadKind();
await migrateOpportunityStages();
await migrateMailPool();
await widenAcquisitionConsultant();
await seedAcquisitionOptions();
await dropProviderOptions();
await ensureAdminUser();
@@ -243,6 +244,28 @@ async function dropProviderOptions() {
);
}
/*
* Das Feld "Berater" nimmt mehrere Namen auf, kommagetrennt (siehe
* acquisitionRules.js). VARCHAR(190) reichte fuer einen Namen; drei bis vier
* volle Namen sprengen die Grenze, und MariaDB wuerde sie abschneiden.
*
* `CREATE TABLE IF NOT EXISTS` in schema.sql aendert eine bestehende Tabelle
* nicht - deshalb hier der ALTER. Er laeuft nur, solange die Spalte noch zu
* kurz ist, und ist damit bei jedem weiteren Start ein Blick in
* INFORMATION_SCHEMA und sonst nichts.
*/
async function widenAcquisitionConsultant() {
const [rows] = await pool.query(
`SELECT CHARACTER_MAXIMUM_LENGTH AS length FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'crm_acquisitions'
AND COLUMN_NAME = 'consultant' LIMIT 1`
);
if (!rows[0] || Number(rows[0].length) >= 500) return;
await pool.query('ALTER TABLE crm_acquisitions MODIFY consultant VARCHAR(500) NULL');
console.log('[Akquise] Feld "Berater" auf 500 Zeichen erweitert - mehrere Berater je Eintrag.');
}
async function ensureAdminUser() {
const [rows] = await pool.query('SELECT COUNT(*) AS count FROM crm_users');
if (rows[0].count > 0) return;
+211 -58
View File
@@ -3,6 +3,8 @@ import { pool } from '../db.js';
import { requireAuth } from '../middleware/auth.js';
import {
ARCHIVE_AFTER_DAYS,
CONSULTANT_MAX_LENGTH,
CONSULTANT_SEPARATOR,
DELETE_AFTER_DAYS,
IN_ARCHIVE,
IN_TRASH,
@@ -11,6 +13,8 @@ import {
NOT_DUE,
OPPORTUNITY_GONE,
TRASH_DELETE_AFTER_DAYS,
normalizeConsultants,
splitConsultants,
} from '../acquisitionRules.js';
const router = express.Router();
@@ -70,7 +74,8 @@ const MAX_LENGTH = {
sender: 190,
provider: 190,
title: 190,
consultant: 190,
// Liste mehrerer Berater, deshalb weiter als die uebrigen Namensfelder.
consultant: CONSULTANT_MAX_LENGTH,
link: 1024,
company: 190,
next_step: 500,
@@ -206,20 +211,62 @@ async function purgeOldEntries() {
const conn = await pool.getConnection();
try {
await conn.beginTransaction();
await conn.query(
`INSERT INTO crm_acquisition_history (found_on, consultant, applications)
SELECT a.found_at, COALESCE(a.consultant, ''), COUNT(*)
/*
* Gezaehlt wird je Berater: ein Eintrag mit drei Beratern sind drei
* Bewerbungen. Deshalb wird die Liste vor dem Sichern zerlegt, statt
* "Nico, Lisa" als eigenen Schluessel abzulegen - der waere in der
* Auswertung ein eigener Balken neben "Nico" und "Lisa".
*
* Das Zerlegen passiert in JavaScript und nicht in SQL: MariaDB kann eine
* kommagetrennte Liste nur mit einer Hilfstabelle aufspalten, und die
* Datenmenge ist klein - der Lauf betrifft hoechstens die Eintraege eines
* Tages, die gerade 90 Tage alt geworden sind.
*/
const [dueRows] = await conn.query(
`SELECT a.found_at, a.consultant, COUNT(*) AS count
FROM crm_acquisitions a
LEFT JOIN crm_opportunities opp ON opp.id = a.opportunity_id
WHERE ${IS_OPEN}
AND ${NOT_DELETED}
AND a.found_at < DATE_SUB(CURDATE(), INTERVAL ? DAY)
GROUP BY a.found_at, COALESCE(a.consultant, '')
ON DUPLICATE KEY UPDATE
applications = crm_acquisition_history.applications + VALUES(applications)`,
GROUP BY a.found_at, a.consultant`,
[DELETE_AFTER_DAYS]
);
/*
* Zusammengefasst wird auf Tag und Berater. Der leere Name steht fuer "ohne
* Berater", weil der Primaerschluessel des Verlaufs kein NULL erlaubt; auf
* 190 Zeichen gekuerzt, so weit reicht dort die Spalte.
*/
const perConsultant = new Map();
for (const row of dueRows) {
const names = splitConsultants(row.consultant);
for (const name of names.length > 0 ? names : ['']) {
const consultant = name.slice(0, 190);
const key = `${row.found_at}|${consultant}`;
const seen = perConsultant.get(key);
if (seen) {
seen.count += Number(row.count);
} else {
perConsultant.set(key, { foundOn: row.found_at, consultant, count: Number(row.count) });
}
}
}
if (perConsultant.size > 0) {
const values = [];
for (const entry of perConsultant.values()) {
values.push(entry.foundOn, entry.consultant, entry.count);
}
await conn.query(
`INSERT INTO crm_acquisition_history (found_on, consultant, applications)
VALUES ${Array.from(perConsultant, () => '(?, ?, ?)').join(', ')}
ON DUPLICATE KEY UPDATE
applications = crm_acquisition_history.applications + VALUES(applications)`,
values
);
}
/*
* Geloescht wird ueber dieselbe Regel: was in Eingang oder Archiv steht,
* altert nach 90 Tagen heraus - auch ein Rueckfaeller. Eintraege mit
@@ -321,7 +368,13 @@ function readFields(body, { partial }) {
for (const field of TEXT_FIELDS) {
if (partial && body?.[field] === undefined) continue;
const value = emptyToNull(body?.[field]);
/*
* "Berater" ist eine Liste mehrerer Namen: erst vereinheitlichen (getrimmt,
* ohne Dubletten), dann messen - sonst wuerde eine Auswahl abgewiesen, die
* nach dem Aufraeumen in die Spalte passt.
*/
const value =
field === 'consultant' ? normalizeConsultants(body?.[field]) : emptyToNull(body?.[field]);
if (MAX_LENGTH[field] && value !== null && value.length > MAX_LENGTH[field]) {
return { error: `Der Wert für "${field}" ist zu lang (max. ${MAX_LENGTH[field]} Zeichen).` };
}
@@ -370,6 +423,29 @@ function readFields(body, { partial }) {
return { columns };
}
/**
* Eintraege, in deren Berater-Liste `name` als eigener Name steht.
*
* Beim Feld "Berater" reicht ein `WHERE consultant = ?` nicht: der Name kann
* einer von mehreren in einem Feld sein, und ein "Nico" in "Nico, Lisa" wuerde
* beim Umbenennen und beim Zaehlen durchfallen. Ein `LIKE '%Nico%'` waere zu
* grob - es traefe auch "Nicole".
*
* Deshalb wird verglichen, nachdem die Liste zerlegt ist. Alle Zeilen zu holen
* ist vertretbar: die Tabelle haelt nur 90 Tage plus die uebernommenen
* Eintraege, und der Weg wird nur beim Pflegen der Auswahlliste gegangen.
*/
async function acquisitionsWithConsultant(db, name, { onlyOpen = false } = {}) {
const [rows] = await db.query(
`SELECT id, consultant FROM crm_acquisitions
WHERE consultant IS NOT NULL${onlyOpen ? ' AND converted_at IS NULL' : ''}`
);
const needle = name.toLowerCase();
return rows.filter((row) =>
splitConsultants(row.consultant).some((entry) => entry.toLowerCase() === needle)
);
}
// ---------------------------------------------------------------------------
// Auswahllisten (Einstellungen -> Akquise)
//
@@ -444,13 +520,37 @@ router.patch('/options/:id', async (req, res, next) => {
await conn.beginTransaction();
await conn.query('UPDATE crm_acquisition_options SET value = ? WHERE id = ?', [value, id]);
const [updated] = await conn.query(
`UPDATE crm_acquisitions SET ${existing.field} = ? WHERE ${existing.field} = ?`,
[value, existing.value]
);
let touched;
if (existing.field === 'consultant') {
/*
* "Berater" ist eine Liste: der alte Name wird darin ersetzt, der Rest
* bleibt stehen. `normalizeConsultants` faengt dabei den Fall ab, dass
* durch das Umbenennen ein Name doppelt in derselben Liste landet.
*/
const affected = await acquisitionsWithConsultant(conn, existing.value);
for (const row of affected) {
const renamed = normalizeConsultants(
splitConsultants(row.consultant)
.map((entry) => (entry.toLowerCase() === existing.value.toLowerCase() ? value : entry))
.join(CONSULTANT_SEPARATOR)
);
await conn.query('UPDATE crm_acquisitions SET consultant = ? WHERE id = ?', [
renamed,
row.id,
]);
}
touched = affected.length;
} else {
const [updated] = await conn.query(
`UPDATE crm_acquisitions SET ${existing.field} = ? WHERE ${existing.field} = ?`,
[value, existing.value]
);
touched = updated.affectedRows;
}
await conn.commit();
res.json({ id, field: existing.field, value, updated: updated.affectedRows });
res.json({ id, field: existing.field, value, updated: touched });
} catch (err) {
await conn.rollback().catch(() => {});
if (err?.code === 'ER_DUP_ENTRY') {
@@ -481,14 +581,23 @@ router.delete('/options/:id', async (req, res, next) => {
const existing = rows[0];
if (!existing) return res.status(404).json({ error: 'Eintrag der Liste nicht gefunden.' });
const [[used]] = await pool.query(
`SELECT COUNT(*) AS count FROM crm_acquisitions
WHERE converted_at IS NULL AND ${existing.field} = ?`,
[existing.value]
);
let stillInUse;
if (existing.field === 'consultant') {
// Mitgezaehlt wird auch, wer nur einer von mehreren Beratern eines
// Eintrags ist - ein Gleichheitsvergleich uebersaehe ihn.
const affected = await acquisitionsWithConsultant(pool, existing.value, { onlyOpen: true });
stillInUse = affected.length;
} else {
const [[used]] = await pool.query(
`SELECT COUNT(*) AS count FROM crm_acquisitions
WHERE converted_at IS NULL AND ${existing.field} = ?`,
[existing.value]
);
stillInUse = Number(used.count);
}
await pool.query('DELETE FROM crm_acquisition_options WHERE id = ?', [id]);
res.json({ ok: true, still_in_use: Number(used.count) });
res.json({ ok: true, still_in_use: stillInUse });
} catch (err) {
next(err);
}
@@ -862,6 +971,11 @@ router.post('/:id/restore', async (req, res, next) => {
* Transaktion: entweder die Opportunity steht und der Eintrag ist als
* uebernommen vermerkt, oder es bleibt alles wie es war. Sonst koennte eine
* Opportunity entstehen, die der Eingang weiterhin anbietet.
*
* Stehen mehrere Berater im Eintrag, wird je Berater eine Opportunity angelegt:
* jeder durchlaeuft seinen eigenen Verkaufsvorgang, einer kann gewonnen werden
* und ein anderer verloren. Alle in einer Transaktion - ein halb uebernommener
* Eintrag waere schlimmer als ein fehlgeschlagener.
*/
router.post('/:id/opportunity', async (req, res, next) => {
const id = Number(req.params.id);
@@ -885,58 +999,97 @@ router.post('/:id/opportunity', async (req, res, next) => {
});
}
/*
* Ohne Berater bleibt es bei einer Opportunity - `null` steht hier fuer
* "kein Berater hinterlegt" und laeuft durch dieselbe Schleife.
*/
const consultants = splitConsultants(entry.consultant);
const targets = consultants.length > 0 ? consultants : [null];
/*
* Was in der Liste steht, aber in der Opportunity kein Feld hat (Anbieter,
* Kanal, Absender, Link, Berater), wandert in die Notizen. Sonst wuesste
* hinterher niemand mehr, woher das Projekt kam.
* hinterher niemand mehr, woher das Projekt kam. In den Notizen steht der
* Berater dieser Opportunity, nicht die ganze Liste - und dazu, mit wem er
* sich das Projekt teilt.
*/
const origin = [
['Anbieter', entry.provider],
['Von', entry.sender],
['Kanal', entry.channel],
['Berater', entry.consultant],
['Link', entry.link],
]
.filter(([, value]) => value)
.map(([label, value]) => `${label}: ${value}`);
const buildNotes = (consultant) => {
const others = targets.filter((name) => name !== null && name !== consultant);
const origin = [
['Anbieter', entry.provider],
['Von', entry.sender],
['Kanal', entry.channel],
['Berater', consultant],
['Auch beworben', others.length > 0 ? others.join(', ') : null],
['Link', entry.link],
]
.filter(([, value]) => value)
.map(([label, value]) => `${label}: ${value}`);
const notes = [
entry.notes,
origin.length > 0 ? `Aus der Akquise vom ${entry.found_at}\n${origin.join('\n')}` : null,
]
.filter(Boolean)
.join('\n\n');
return (
[
entry.notes,
origin.length > 0 ? `Aus der Akquise vom ${entry.found_at}\n${origin.join('\n')}` : null,
]
.filter(Boolean)
.join('\n\n') || null
);
};
/*
* Bei mehreren Beratern kommt der Name in den Titel: in Pipeline und Liste
* standen sonst drei Zeilen mit identischem Text, und die Opportunity hat
* kein eigenes Feld fuer den Berater. Bei einem einzigen Berater bleibt der
* Titel unveraendert - das ist der Normalfall und braucht keinen Zusatz.
*/
const titleFor = (consultant) =>
targets.length > 1 && consultant ? `${entry.title} (${consultant})`.slice(0, 190) : entry.title;
await conn.beginTransaction();
const [created] = await conn.query(
`INSERT INTO crm_opportunities
(title, company, description, stage, probability, daily_rate, duration_days,
fixed_price, start_date, end_date, next_step, tags, notes, owner_id, created_by)
VALUES (?, ?, ?, 'Erstgespraech Berater', 10, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
entry.title,
entry.company,
entry.description,
entry.daily_rate,
entry.duration_days,
entry.fixed_price,
entry.start_date,
entry.end_date,
entry.next_step,
entry.tags ?? '[]',
notes || null,
req.user.id,
req.user.id,
]
);
const opportunityIds = [];
for (const consultant of targets) {
const [created] = await conn.query(
`INSERT INTO crm_opportunities
(title, company, description, stage, probability, daily_rate, duration_days,
fixed_price, start_date, end_date, next_step, tags, notes, owner_id, created_by)
VALUES (?, ?, ?, 'Erstgespraech Berater', 10, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
titleFor(consultant),
entry.company,
entry.description,
entry.daily_rate,
entry.duration_days,
entry.fixed_price,
entry.start_date,
entry.end_date,
entry.next_step,
entry.tags ?? '[]',
buildNotes(consultant),
req.user.id,
req.user.id,
]
);
opportunityIds.push(created.insertId);
}
/*
* `opportunity_id` ist eine Spalte, also merkt sich der Eintrag die erste.
* Sie entscheidet nur darueber, ob er wieder im Eingang auftaucht: wird sie
* geloescht, laesst sich erneut uebernehmen. Die uebrigen bleiben davon
* unberuehrt - dafuer steht ihre Herkunft in den Notizen.
*/
await conn.query(
'UPDATE crm_acquisitions SET opportunity_id = ?, converted_at = UTC_TIMESTAMP() WHERE id = ?',
[created.insertId, id]
[opportunityIds[0], id]
);
await conn.commit();
res.status(201).json({ ok: true, opportunity_id: created.insertId });
res.status(201).json({
ok: true,
opportunity_id: opportunityIds[0],
opportunity_ids: opportunityIds,
consultants,
});
} catch (err) {
await conn.rollback().catch(() => {});
next(err);
+34 -6
View File
@@ -1,6 +1,7 @@
import express from 'express';
import { pool } from '../db.js';
import { requireAuth } from '../middleware/auth.js';
import { splitConsultants } from '../acquisitionRules.js';
const router = express.Router();
router.use(requireAuth);
@@ -99,10 +100,21 @@ router.get('/', async (req, res, next) => {
[from, toExclusive]
);
// Bewerbungen je Berater - lebende Eintraege und Verlauf zusammen.
/*
* Bewerbungen je Berater - lebende Eintraege und Verlauf zusammen.
*
* Ein Eintrag kann mehrere Berater tragen (kommagetrennt, siehe
* acquisitionRules.js); jeder davon ist eine eigene Bewerbung und wird
* einzeln gezaehlt. Die Summe dieser Balken liegt damit ueber der Gesamtzahl
* "Bewerbungen" oben, die weiter die Eintraege zaehlt - beides ist
* beabsichtigt: ein Fund, drei verschickte Profile.
*
* Zusammengefasst wird in JavaScript, weil SQL die Liste nicht ohne
* Hilfstabelle aufspalten kann. Der Verlauf liegt schon je Berater vor.
*/
const [consultantRows] = await pool.query(
`SELECT consultant, SUM(count) AS count FROM (
SELECT COALESCE(NULLIF(TRIM(consultant), ''), '') AS consultant, COUNT(*) AS count
SELECT COALESCE(consultant, '') AS consultant, COUNT(*) AS count
FROM crm_acquisitions
WHERE deleted_at IS NULL
AND found_at BETWEEN ? AND ?
@@ -113,11 +125,27 @@ router.get('/', async (req, res, next) => {
WHERE found_on BETWEEN ? AND ?
GROUP BY 1
) AS beide
GROUP BY consultant
ORDER BY count DESC, consultant ASC`,
GROUP BY consultant`,
[from, to, from, to]
);
// Leerer Text heisst "kein Berater hinterlegt" und bleibt ein eigener Balken.
const perConsultant = new Map();
for (const row of consultantRows) {
const names = splitConsultants(row.consultant);
for (const name of names.length > 0 ? names : ['']) {
perConsultant.set(name, (perConsultant.get(name) ?? 0) + Number(row.count));
}
}
const byConsultant = [...perConsultant.entries()]
.map(([consultant, applications]) => ({ consultant, applications }))
.sort(
(left, right) =>
right.applications - left.applications ||
left.consultant.localeCompare(right.consultant, 'de')
);
const live = toMap(applicationRows);
const history = toMap(historyRows);
const applications = { ...live };
@@ -139,11 +167,11 @@ router.get('/', async (req, res, next) => {
converted: sum(converted),
won: sum(won),
},
by_consultant: consultantRows.map((row) => ({
by_consultant: byConsultant.map((row) => ({
// Leerer Text heisst "kein Berater hinterlegt" - das Frontend
// beschriftet es, damit hier kein Anzeigetext entsteht.
consultant: row.consultant === '' ? null : row.consultant,
applications: Number(row.count),
applications: row.applications,
})),
});
} catch (err) {
+1 -1
View File
@@ -408,7 +408,7 @@ CREATE TABLE IF NOT EXISTS crm_acquisitions (
provider VARCHAR(190) NULL, -- "Anbieter": Vermittler, Portal
channel VARCHAR(60) NULL, -- "Kanal": Mail, Telefon, Portal, ...
title VARCHAR(190) NOT NULL, -- Projekttitel
consultant VARCHAR(190) NULL, -- "Berater", fuer den es passt
consultant VARCHAR(500) NULL, -- "Berater": ein Name oder mehrere, kommagetrennt
link VARCHAR(1024) NULL, -- Ausschreibung; macht den Titel klickbar
-- Ab hier: steht nicht in der Liste, wandert aber in die Opportunity.
company VARCHAR(190) NULL, -- Endkunde
+92
View File
@@ -0,0 +1,92 @@
/*
* Pruefungen der Berater-Liste: laeuft mit `npm test` im Verzeichnis server/.
*
* Ohne Test-Framework, wie mail.test.mjs - reines Node.
*
* Geprueft wird das Zerlegen und Zusammensetzen des Feldes "Berater". Es steckt
* an vier Stellen (Speichern, Verlauf, Auswertung, Uebernahme in Opportunities),
* und ein Fehler darin faellt nicht auf: die Liste zeigt weiter Namen, nur die
* Zahlen im Dashboard oder die Anzahl der Opportunities waeren falsch.
*
* Das Gegenstueck im Frontend (src/types.ts) ist dieselbe Logik in TypeScript;
* wer hier etwas aendert, muss dort mitziehen.
*/
const { splitConsultants, joinConsultants, normalizeConsultants, CONSULTANT_SEPARATOR } =
await import('../src/acquisitionRules.js');
let failures = 0;
function check(name, condition, detail = '') {
if (condition) {
console.log(` ok ${name}${detail ? ` - ${detail}` : ''}`);
} else {
console.log(` FAIL ${name}${detail ? ` - ${detail}` : ''}`);
failures += 1;
}
}
const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
console.log('\nZerlegen');
check('Einzelner Name', same(splitConsultants('Nico'), ['Nico']));
check('Mehrere Namen', same(splitConsultants('Nico, Lisa'), ['Nico', 'Lisa']));
check(
'Ohne Leerzeichen hinter dem Komma',
same(splitConsultants('Nico,Lisa,Gunther'), ['Nico', 'Lisa', 'Gunther'])
);
check(
'Umlaute und zusammengesetzte Namen bleiben ganz',
same(splitConsultants('Niklas Mülln, Luisa Sauerwald'), ['Niklas Mülln', 'Luisa Sauerwald'])
);
check('Leeres Feld', same(splitConsultants(''), []));
check('null', same(splitConsultants(null), []));
check('Nur Kommas', same(splitConsultants(' , , '), []));
check('Leeres Stueck faellt weg', same(splitConsultants('Nico, , Lisa'), ['Nico', 'Lisa']));
check(
'Dublette faellt weg, erste Schreibweise bleibt',
same(splitConsultants('Nico, nico, NICO'), ['Nico'])
);
console.log('\nZusammensetzen');
check('Mehrere Namen', joinConsultants(['Nico', 'Lisa']) === `Nico${CONSULTANT_SEPARATOR}Lisa`);
check('Leere Liste wird null', joinConsultants([]) === null);
check('Nur Leerzeichen wird null', joinConsultants([' ', '']) === null);
console.log('\nVereinheitlichen (so kommt es aus dem Formular)');
check('Getrimmt und normiert', normalizeConsultants(' Nico ,Lisa ') === 'Nico, Lisa');
check('Dubletten weg', normalizeConsultants('Nico, Nico') === 'Nico');
check('Leer wird null', normalizeConsultants(' ') === null);
check(
'Zweimal vereinheitlichen aendert nichts',
normalizeConsultants(normalizeConsultants('Nico,Lisa, nico')) === 'Nico, Lisa'
);
/*
* Das Zaehlen je Berater, wie es der Verlauf und das Dashboard machen: ein
* Eintrag mit drei Beratern sind drei Bewerbungen.
*/
console.log('\nZaehlen je Berater');
const rows = [
{ consultant: 'Nico, Lisa', count: 1 },
{ consultant: 'Nico', count: 2 },
{ consultant: null, count: 4 },
];
const perConsultant = new Map();
for (const row of rows) {
const names = splitConsultants(row.consultant);
for (const name of names.length > 0 ? names : ['']) {
perConsultant.set(name, (perConsultant.get(name) ?? 0) + row.count);
}
}
check('Berater in zwei Eintraegen', perConsultant.get('Nico') === 3);
check('Berater in einem Eintrag', perConsultant.get('Lisa') === 1);
check('Ohne Berater bleibt eine eigene Gruppe', perConsultant.get('') === 4);
check(
'Summe liegt ueber der Zahl der Eintraege',
[...perConsultant.values()].reduce((total, value) => total + value, 0) === 8
);
console.log(
failures === 0 ? '\nAlle Pruefungen bestanden.' : `\n${failures} Pruefung(en) fehlgeschlagen.`
);
process.exit(failures === 0 ? 0 : 1);