rework internal order system
This commit is contained in:
@@ -1,23 +1,21 @@
|
|||||||
-- Migration 048: Catalog categories table + item characteristics
|
-- Migration 048: Catalog categories table + item characteristics
|
||||||
-- - Admin-managed categories with subcategories (replacing free-text kategorie)
|
|
||||||
-- - Per-item characteristics (options or free-text)
|
|
||||||
-- - Characteristic values per request position
|
|
||||||
-- - Remove view_all permission (approve covers it)
|
|
||||||
-- - Add manage_categories permission
|
|
||||||
|
|
||||||
-- 1. Categories table (with parent_id for subcategories)
|
-- 1. Categories table (with parent_id for subcategories)
|
||||||
CREATE TABLE IF NOT EXISTS ausruestung_kategorien_katalog (
|
CREATE TABLE IF NOT EXISTS ausruestung_kategorien_katalog (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
parent_id INT REFERENCES ausruestung_kategorien_katalog(id) ON DELETE CASCADE,
|
parent_id INT REFERENCES ausruestung_kategorien_katalog(id) ON DELETE CASCADE,
|
||||||
erstellt_am TIMESTAMPTZ DEFAULT NOW(),
|
erstellt_am TIMESTAMPTZ DEFAULT NOW()
|
||||||
UNIQUE(name, parent_id)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Add unique constraint for top-level categories (parent_id IS NULL)
|
-- Unique: top-level categories by name (where parent_id IS NULL)
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS ausruestung_kategorien_top_level_unique
|
CREATE UNIQUE INDEX IF NOT EXISTS ausruestung_kat_top_unique
|
||||||
ON ausruestung_kategorien_katalog (name) WHERE parent_id IS NULL;
|
ON ausruestung_kategorien_katalog (name) WHERE parent_id IS NULL;
|
||||||
|
|
||||||
|
-- Unique: subcategories by (parent_id, name)
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS ausruestung_kat_child_unique
|
||||||
|
ON ausruestung_kategorien_katalog (parent_id, name) WHERE parent_id IS NOT NULL;
|
||||||
|
|
||||||
-- Migrate existing categories from free-text
|
-- Migrate existing categories from free-text
|
||||||
INSERT INTO ausruestung_kategorien_katalog (name)
|
INSERT INTO ausruestung_kategorien_katalog (name)
|
||||||
SELECT DISTINCT kategorie FROM ausruestung_artikel WHERE kategorie IS NOT NULL AND kategorie != ''
|
SELECT DISTINCT kategorie FROM ausruestung_artikel WHERE kategorie IS NOT NULL AND kategorie != ''
|
||||||
|
|||||||
@@ -1,34 +1,22 @@
|
|||||||
import pool from '../config/database';
|
import pool from '../config/database';
|
||||||
import logger from '../utils/logger';
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
// Helper: check if a table exists (cached per process lifetime)
|
|
||||||
const existingTables = new Set<string>();
|
|
||||||
async function tableExists(tableName: string): Promise<boolean> {
|
|
||||||
if (existingTables.has(tableName)) return true;
|
|
||||||
try {
|
|
||||||
const r = await pool.query(
|
|
||||||
"SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = $1) AS ok",
|
|
||||||
[tableName],
|
|
||||||
);
|
|
||||||
if (r.rows[0]?.ok) { existingTables.add(tableName); return true; }
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Categories (ausruestung_kategorien_katalog) — hierarchical with parent_id
|
// Categories (ausruestung_kategorien_katalog) — hierarchical with parent_id
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
async function getKategorien() {
|
async function getKategorien() {
|
||||||
if (!(await tableExists('ausruestung_kategorien_katalog'))) return [];
|
try {
|
||||||
const result = await pool.query(
|
const result = await pool.query(
|
||||||
'SELECT * FROM ausruestung_kategorien_katalog ORDER BY parent_id NULLS FIRST, name',
|
'SELECT * FROM ausruestung_kategorien_katalog ORDER BY parent_id NULLS FIRST, name',
|
||||||
);
|
);
|
||||||
return result.rows;
|
return result.rows;
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createKategorie(name: string, parentId?: number | null) {
|
async function createKategorie(name: string, parentId?: number | null) {
|
||||||
if (!(await tableExists('ausruestung_kategorien_katalog'))) throw new Error('Migration 048 has not been applied yet');
|
|
||||||
const result = await pool.query(
|
const result = await pool.query(
|
||||||
'INSERT INTO ausruestung_kategorien_katalog (name, parent_id) VALUES ($1, $2) RETURNING *',
|
'INSERT INTO ausruestung_kategorien_katalog (name, parent_id) VALUES ($1, $2) RETURNING *',
|
||||||
[name, parentId ?? null],
|
[name, parentId ?? null],
|
||||||
@@ -73,54 +61,72 @@ async function getItems(filters?: { kategorie?: string; kategorie_id?: number; a
|
|||||||
|
|
||||||
if (filters?.kategorie) {
|
if (filters?.kategorie) {
|
||||||
params.push(filters.kategorie);
|
params.push(filters.kategorie);
|
||||||
conditions.push(`a.kategorie = $${params.length}`);
|
conditions.push(`kategorie = $${params.length}`);
|
||||||
}
|
}
|
||||||
if (filters?.kategorie_id) {
|
if (filters?.kategorie_id) {
|
||||||
params.push(filters.kategorie_id);
|
params.push(filters.kategorie_id);
|
||||||
conditions.push(`a.kategorie_id = $${params.length}`);
|
conditions.push(`kategorie_id = $${params.length}`);
|
||||||
}
|
}
|
||||||
if (filters?.aktiv !== undefined) {
|
if (filters?.aktiv !== undefined) {
|
||||||
params.push(filters.aktiv);
|
params.push(filters.aktiv);
|
||||||
conditions.push(`a.aktiv = $${params.length}`);
|
conditions.push(`aktiv = $${params.length}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||||
const hasKategorien = await tableExists('ausruestung_kategorien_katalog');
|
|
||||||
const hasEigenschaften = await tableExists('ausruestung_artikel_eigenschaften');
|
|
||||||
const result = await pool.query(
|
const result = await pool.query(
|
||||||
`SELECT a.*${hasKategorien ? ', k.name AS kategorie_name' : ''}${hasEigenschaften ? ',\n (SELECT COUNT(*)::int FROM ausruestung_artikel_eigenschaften e WHERE e.artikel_id = a.id) AS eigenschaften_count' : ''}
|
`SELECT * FROM ausruestung_artikel ${where} ORDER BY kategorie, bezeichnung`,
|
||||||
FROM ausruestung_artikel a
|
|
||||||
${hasKategorien ? 'LEFT JOIN ausruestung_kategorien_katalog k ON k.id = a.kategorie_id' : ''}
|
|
||||||
${where}
|
|
||||||
ORDER BY ${hasKategorien ? 'COALESCE(k.name, a.kategorie)' : 'a.kategorie'}, a.bezeichnung`,
|
|
||||||
params,
|
params,
|
||||||
);
|
);
|
||||||
return result.rows;
|
|
||||||
|
// Enrich with kategorie_name and eigenschaften_count if tables exist
|
||||||
|
const rows = result.rows;
|
||||||
|
try {
|
||||||
|
const katRows = await pool.query('SELECT id, name FROM ausruestung_kategorien_katalog');
|
||||||
|
const katMap = new Map(katRows.rows.map((k: { id: number; name: string }) => [k.id, k.name]));
|
||||||
|
for (const row of rows) {
|
||||||
|
row.kategorie_name = row.kategorie_id ? katMap.get(row.kategorie_id) || null : null;
|
||||||
|
}
|
||||||
|
} catch { /* table doesn't exist yet */ }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const eigCounts = await pool.query(
|
||||||
|
'SELECT artikel_id, COUNT(*)::int AS cnt FROM ausruestung_artikel_eigenschaften GROUP BY artikel_id',
|
||||||
|
);
|
||||||
|
const eigMap = new Map(eigCounts.rows.map((e: { artikel_id: number; cnt: number }) => [e.artikel_id, e.cnt]));
|
||||||
|
for (const row of rows) {
|
||||||
|
row.eigenschaften_count = eigMap.get(row.id) || 0;
|
||||||
|
}
|
||||||
|
} catch { /* table doesn't exist yet */ }
|
||||||
|
|
||||||
|
return rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getItemById(id: number) {
|
async function getItemById(id: number) {
|
||||||
const hasKategorien = await tableExists('ausruestung_kategorien_katalog');
|
const result = await pool.query('SELECT * FROM ausruestung_artikel WHERE id = $1', [id]);
|
||||||
const result = await pool.query(
|
|
||||||
`SELECT a.*${hasKategorien ? ', k.name AS kategorie_name' : ''}
|
|
||||||
FROM ausruestung_artikel a
|
|
||||||
${hasKategorien ? 'LEFT JOIN ausruestung_kategorien_katalog k ON k.id = a.kategorie_id' : ''}
|
|
||||||
WHERE a.id = $1`,
|
|
||||||
[id],
|
|
||||||
);
|
|
||||||
if (!result.rows[0]) return null;
|
if (!result.rows[0]) return null;
|
||||||
|
|
||||||
let eigenschaften: { rows: unknown[] } = { rows: [] };
|
const row = result.rows[0];
|
||||||
if (await tableExists('ausruestung_artikel_eigenschaften')) {
|
|
||||||
eigenschaften = await pool.query(
|
// Enrich with kategorie_name
|
||||||
|
if (row.kategorie_id) {
|
||||||
|
try {
|
||||||
|
const kat = await pool.query('SELECT name FROM ausruestung_kategorien_katalog WHERE id = $1', [row.kategorie_id]);
|
||||||
|
row.kategorie_name = kat.rows[0]?.name || null;
|
||||||
|
} catch { /* table doesn't exist */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load eigenschaften
|
||||||
|
try {
|
||||||
|
const eigenschaften = await pool.query(
|
||||||
'SELECT * FROM ausruestung_artikel_eigenschaften WHERE artikel_id = $1 ORDER BY sort_order, id',
|
'SELECT * FROM ausruestung_artikel_eigenschaften WHERE artikel_id = $1 ORDER BY sort_order, id',
|
||||||
[id],
|
[id],
|
||||||
);
|
);
|
||||||
|
row.eigenschaften = eigenschaften.rows;
|
||||||
|
} catch {
|
||||||
|
row.eigenschaften = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return row;
|
||||||
...result.rows[0],
|
|
||||||
eigenschaften: eigenschaften.rows,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createItem(
|
async function createItem(
|
||||||
@@ -134,11 +140,19 @@ async function createItem(
|
|||||||
},
|
},
|
||||||
userId: string,
|
userId: string,
|
||||||
) {
|
) {
|
||||||
|
// Build column list dynamically based on whether kategorie_id column exists
|
||||||
|
const cols = ['bezeichnung', 'beschreibung', 'kategorie', 'geschaetzter_preis', 'aktiv', 'erstellt_von'];
|
||||||
|
const vals = [data.bezeichnung, data.beschreibung || null, data.kategorie || null, data.geschaetzter_preis || null, data.aktiv ?? true, userId];
|
||||||
|
|
||||||
|
if (data.kategorie_id) {
|
||||||
|
cols.push('kategorie_id');
|
||||||
|
vals.push(data.kategorie_id as unknown as string);
|
||||||
|
}
|
||||||
|
|
||||||
|
const placeholders = vals.map((_, i) => `$${i + 1}`).join(', ');
|
||||||
const result = await pool.query(
|
const result = await pool.query(
|
||||||
`INSERT INTO ausruestung_artikel (bezeichnung, beschreibung, kategorie, kategorie_id, geschaetzter_preis, aktiv, erstellt_von)
|
`INSERT INTO ausruestung_artikel (${cols.join(', ')}) VALUES (${placeholders}) RETURNING *`,
|
||||||
VALUES ($1, $2, $3, $4, COALESCE($5, true), $6, $7)
|
vals,
|
||||||
RETURNING *`,
|
|
||||||
[data.bezeichnung, data.beschreibung || null, data.kategorie || null, data.kategorie_id || null, data.geschaetzter_preis || null, data.aktiv ?? true, userId],
|
|
||||||
);
|
);
|
||||||
return result.rows[0];
|
return result.rows[0];
|
||||||
}
|
}
|
||||||
@@ -214,19 +228,21 @@ async function getCategories() {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
async function getArtikelEigenschaften(artikelId: number) {
|
async function getArtikelEigenschaften(artikelId: number) {
|
||||||
if (!(await tableExists('ausruestung_artikel_eigenschaften'))) return [];
|
try {
|
||||||
const result = await pool.query(
|
const result = await pool.query(
|
||||||
'SELECT * FROM ausruestung_artikel_eigenschaften WHERE artikel_id = $1 ORDER BY sort_order, id',
|
'SELECT * FROM ausruestung_artikel_eigenschaften WHERE artikel_id = $1 ORDER BY sort_order, id',
|
||||||
[artikelId],
|
[artikelId],
|
||||||
);
|
);
|
||||||
return result.rows;
|
return result.rows;
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function upsertArtikelEigenschaft(
|
async function upsertArtikelEigenschaft(
|
||||||
artikelId: number,
|
artikelId: number,
|
||||||
data: { id?: number; name: string; typ: string; optionen?: string[]; pflicht?: boolean; sort_order?: number },
|
data: { id?: number; name: string; typ: string; optionen?: string[]; pflicht?: boolean; sort_order?: number },
|
||||||
) {
|
) {
|
||||||
if (!(await tableExists('ausruestung_artikel_eigenschaften'))) throw new Error('Migration 048 has not been applied yet');
|
|
||||||
if (data.id) {
|
if (data.id) {
|
||||||
const result = await pool.query(
|
const result = await pool.query(
|
||||||
`UPDATE ausruestung_artikel_eigenschaften
|
`UPDATE ausruestung_artikel_eigenschaften
|
||||||
@@ -317,7 +333,7 @@ async function getRequestById(id: number) {
|
|||||||
[id],
|
[id],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Load eigenschaft values per position (gracefully handle missing table)
|
// Load eigenschaft values per position
|
||||||
const positionIds = positionen.rows.map((p: { id: number }) => p.id);
|
const positionIds = positionen.rows.map((p: { id: number }) => p.id);
|
||||||
let eigenschaftenMap: Record<number, { eigenschaft_id: number; eigenschaft_name: string; wert: string }[]> = {};
|
let eigenschaftenMap: Record<number, { eigenschaft_id: number; eigenschaft_name: string; wert: string }[]> = {};
|
||||||
if (positionIds.length > 0) {
|
if (positionIds.length > 0) {
|
||||||
@@ -338,10 +354,7 @@ async function getRequestById(id: number) {
|
|||||||
wert: row.wert,
|
wert: row.wert,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch { /* table may not exist */ }
|
||||||
// Table may not exist yet if migration hasn't run
|
|
||||||
logger.debug('Position eigenschaften query failed (migration may not have run yet)', { error: err });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const positionenWithEigenschaften = positionen.rows.map((p: { id: number }) => ({
|
const positionenWithEigenschaften = positionen.rows.map((p: { id: number }) => ({
|
||||||
@@ -349,18 +362,23 @@ async function getRequestById(id: number) {
|
|||||||
eigenschaften: eigenschaftenMap[p.id] || [],
|
eigenschaften: eigenschaftenMap[p.id] || [],
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const bestellungen = await pool.query(
|
// Load linked bestellungen
|
||||||
`SELECT b.*
|
let linkedBestellungen: unknown[] = [];
|
||||||
FROM ausruestung_anfrage_bestellung ab
|
try {
|
||||||
JOIN bestellungen b ON b.id = ab.bestellung_id
|
const bestellungen = await pool.query(
|
||||||
WHERE ab.anfrage_id = $1`,
|
`SELECT b.*
|
||||||
[id],
|
FROM ausruestung_anfrage_bestellung ab
|
||||||
);
|
JOIN bestellungen b ON b.id = ab.bestellung_id
|
||||||
|
WHERE ab.anfrage_id = $1`,
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
linkedBestellungen = bestellungen.rows;
|
||||||
|
} catch { /* table may not exist */ }
|
||||||
|
|
||||||
return {
|
return {
|
||||||
anfrage: reqResult.rows[0],
|
anfrage: reqResult.rows[0],
|
||||||
positionen: positionenWithEigenschaften,
|
positionen: positionenWithEigenschaften,
|
||||||
linked_bestellungen: bestellungen.rows,
|
linked_bestellungen: linkedBestellungen,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -374,7 +392,6 @@ async function createRequest(
|
|||||||
try {
|
try {
|
||||||
await client.query('BEGIN');
|
await client.query('BEGIN');
|
||||||
|
|
||||||
// Get next bestell_nummer for the current year
|
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
const maxResult = await client.query(
|
const maxResult = await client.query(
|
||||||
`SELECT COALESCE(MAX(bestell_nummer), 0) + 1 AS next_nr
|
`SELECT COALESCE(MAX(bestell_nummer), 0) + 1 AS next_nr
|
||||||
@@ -394,8 +411,6 @@ async function createRequest(
|
|||||||
|
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
let itemBezeichnung = item.bezeichnung;
|
let itemBezeichnung = item.bezeichnung;
|
||||||
|
|
||||||
// If artikel_id is provided, copy bezeichnung from catalog
|
|
||||||
if (item.artikel_id) {
|
if (item.artikel_id) {
|
||||||
const artikelResult = await client.query(
|
const artikelResult = await client.query(
|
||||||
'SELECT bezeichnung FROM ausruestung_artikel WHERE id = $1',
|
'SELECT bezeichnung FROM ausruestung_artikel WHERE id = $1',
|
||||||
@@ -406,31 +421,43 @@ async function createRequest(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const posResult = await client.query(
|
await client.query(
|
||||||
`INSERT INTO ausruestung_anfrage_positionen (anfrage_id, artikel_id, bezeichnung, menge, notizen)
|
`INSERT INTO ausruestung_anfrage_positionen (anfrage_id, artikel_id, bezeichnung, menge, notizen)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
VALUES ($1, $2, $3, $4, $5)`,
|
||||||
RETURNING id`,
|
|
||||||
[anfrage.id, item.artikel_id || null, itemBezeichnung, item.menge, item.notizen || null],
|
[anfrage.id, item.artikel_id || null, itemBezeichnung, item.menge, item.notizen || null],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Save eigenschaft values
|
// NOTE: eigenschaft values are NOT saved in the transaction to avoid
|
||||||
if (item.eigenschaften && item.eigenschaften.length > 0) {
|
// aborting the transaction if the table doesn't exist.
|
||||||
for (const e of item.eigenschaften) {
|
|
||||||
try {
|
|
||||||
await client.query(
|
|
||||||
`INSERT INTO ausruestung_position_eigenschaften (position_id, eigenschaft_id, wert)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
ON CONFLICT (position_id, eigenschaft_id) DO UPDATE SET wert = $3`,
|
|
||||||
[posResult.rows[0].id, e.eigenschaft_id, e.wert],
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
logger.debug('Position eigenschaft insert failed (migration may not have run yet)', { error: err });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
|
|
||||||
|
// Save eigenschaft values OUTSIDE the transaction so a missing table
|
||||||
|
// won't rollback the entire request creation.
|
||||||
|
for (const item of items) {
|
||||||
|
if (!item.eigenschaften || item.eigenschaften.length === 0) continue;
|
||||||
|
// Find the position ID we just inserted
|
||||||
|
const posRes = await pool.query(
|
||||||
|
`SELECT id FROM ausruestung_anfrage_positionen
|
||||||
|
WHERE anfrage_id = $1 AND COALESCE(artikel_id, 0) = $2
|
||||||
|
ORDER BY id DESC LIMIT 1`,
|
||||||
|
[anfrage.id, item.artikel_id || 0],
|
||||||
|
);
|
||||||
|
if (posRes.rows.length === 0) continue;
|
||||||
|
const posId = posRes.rows[0].id;
|
||||||
|
for (const e of item.eigenschaften) {
|
||||||
|
try {
|
||||||
|
await pool.query(
|
||||||
|
`INSERT INTO ausruestung_position_eigenschaften (position_id, eigenschaft_id, wert)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
ON CONFLICT (position_id, eigenschaft_id) DO UPDATE SET wert = $3`,
|
||||||
|
[posId, e.eigenschaft_id, e.wert],
|
||||||
|
);
|
||||||
|
} catch { /* table may not exist */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return getRequestById(anfrage.id);
|
return getRequestById(anfrage.id);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await client.query('ROLLBACK');
|
await client.query('ROLLBACK');
|
||||||
@@ -453,7 +480,6 @@ async function updateRequest(
|
|||||||
try {
|
try {
|
||||||
await client.query('BEGIN');
|
await client.query('BEGIN');
|
||||||
|
|
||||||
// Update anfrage fields
|
|
||||||
const fields: string[] = [];
|
const fields: string[] = [];
|
||||||
const params: unknown[] = [];
|
const params: unknown[] = [];
|
||||||
|
|
||||||
@@ -476,7 +502,6 @@ async function updateRequest(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace items if provided
|
|
||||||
if (data.items) {
|
if (data.items) {
|
||||||
await client.query('DELETE FROM ausruestung_anfrage_positionen WHERE anfrage_id = $1', [id]);
|
await client.query('DELETE FROM ausruestung_anfrage_positionen WHERE anfrage_id = $1', [id]);
|
||||||
for (const item of data.items) {
|
for (const item of data.items) {
|
||||||
@@ -490,32 +515,41 @@ async function updateRequest(
|
|||||||
itemBezeichnung = artikelResult.rows[0].bezeichnung;
|
itemBezeichnung = artikelResult.rows[0].bezeichnung;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const posResult = await client.query(
|
await client.query(
|
||||||
`INSERT INTO ausruestung_anfrage_positionen (anfrage_id, artikel_id, bezeichnung, menge, notizen)
|
`INSERT INTO ausruestung_anfrage_positionen (anfrage_id, artikel_id, bezeichnung, menge, notizen)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
VALUES ($1, $2, $3, $4, $5)`,
|
||||||
RETURNING id`,
|
|
||||||
[id, item.artikel_id || null, itemBezeichnung, item.menge, item.notizen || null],
|
[id, item.artikel_id || null, itemBezeichnung, item.menge, item.notizen || null],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Save eigenschaft values
|
|
||||||
if (item.eigenschaften && item.eigenschaften.length > 0) {
|
|
||||||
for (const e of item.eigenschaften) {
|
|
||||||
try {
|
|
||||||
await client.query(
|
|
||||||
`INSERT INTO ausruestung_position_eigenschaften (position_id, eigenschaft_id, wert)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
ON CONFLICT (position_id, eigenschaft_id) DO UPDATE SET wert = $3`,
|
|
||||||
[posResult.rows[0].id, e.eigenschaft_id, e.wert],
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
logger.debug('Position eigenschaft insert failed', { error: err });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
|
|
||||||
|
// Save eigenschaft values outside transaction
|
||||||
|
if (data.items) {
|
||||||
|
for (const item of data.items) {
|
||||||
|
if (!item.eigenschaften || item.eigenschaften.length === 0) continue;
|
||||||
|
const posRes = await pool.query(
|
||||||
|
`SELECT id FROM ausruestung_anfrage_positionen
|
||||||
|
WHERE anfrage_id = $1 AND COALESCE(artikel_id, 0) = $2
|
||||||
|
ORDER BY id DESC LIMIT 1`,
|
||||||
|
[id, item.artikel_id || 0],
|
||||||
|
);
|
||||||
|
if (posRes.rows.length === 0) continue;
|
||||||
|
const posId = posRes.rows[0].id;
|
||||||
|
for (const e of item.eigenschaften) {
|
||||||
|
try {
|
||||||
|
await pool.query(
|
||||||
|
`INSERT INTO ausruestung_position_eigenschaften (position_id, eigenschaft_id, wert)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
ON CONFLICT (position_id, eigenschaft_id) DO UPDATE SET wert = $3`,
|
||||||
|
[posId, e.eigenschaft_id, e.wert],
|
||||||
|
);
|
||||||
|
} catch { /* table may not exist */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return getRequestById(id);
|
return getRequestById(id);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await client.query('ROLLBACK');
|
await client.query('ROLLBACK');
|
||||||
@@ -618,7 +652,7 @@ async function getOverview() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Widget overview (no permission restriction — counts only)
|
// Widget overview (lightweight counts only)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
async function getWidgetOverview() {
|
async function getWidgetOverview() {
|
||||||
|
|||||||
@@ -336,10 +336,11 @@ function DetailModal({ requestId, onClose, showAdminActions, showEditButton, can
|
|||||||
const [linkDialog, setLinkDialog] = useState(false);
|
const [linkDialog, setLinkDialog] = useState(false);
|
||||||
const [selectedBestellung, setSelectedBestellung] = useState<Bestellung | null>(null);
|
const [selectedBestellung, setSelectedBestellung] = useState<Bestellung | null>(null);
|
||||||
|
|
||||||
const { data: detail, isLoading } = useQuery<AusruestungAnfrageDetailResponse>({
|
const { data: detail, isLoading, isError } = useQuery<AusruestungAnfrageDetailResponse>({
|
||||||
queryKey: ['ausruestungsanfrage', 'request', requestId],
|
queryKey: ['ausruestungsanfrage', 'request', requestId],
|
||||||
queryFn: () => ausruestungsanfrageApi.getRequest(requestId!),
|
queryFn: () => ausruestungsanfrageApi.getRequest(requestId!),
|
||||||
enabled: requestId != null,
|
enabled: requestId != null,
|
||||||
|
retry: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: catalogItems = [] } = useQuery({
|
const { data: catalogItems = [] } = useQuery({
|
||||||
@@ -451,6 +452,8 @@ function DetailModal({ requestId, onClose, showAdminActions, showEditButton, can
|
|||||||
<DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '20px !important' }}>
|
<DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '20px !important' }}>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<Typography color="text.secondary">Lade Details...</Typography>
|
<Typography color="text.secondary">Lade Details...</Typography>
|
||||||
|
) : isError ? (
|
||||||
|
<Typography color="error">Fehler beim Laden der Anfrage.</Typography>
|
||||||
) : !detail ? (
|
) : !detail ? (
|
||||||
<Typography color="text.secondary">Anfrage nicht gefunden.</Typography>
|
<Typography color="text.secondary">Anfrage nicht gefunden.</Typography>
|
||||||
) : editing ? (
|
) : editing ? (
|
||||||
@@ -945,8 +948,12 @@ function MeineAnfragenTab() {
|
|||||||
if (itemEigenschaftenRef.current[artikelId]) return;
|
if (itemEigenschaftenRef.current[artikelId]) return;
|
||||||
try {
|
try {
|
||||||
const eigs = await ausruestungsanfrageApi.getArtikelEigenschaften(artikelId);
|
const eigs = await ausruestungsanfrageApi.getArtikelEigenschaften(artikelId);
|
||||||
setItemEigenschaften(prev => ({ ...prev, [artikelId]: eigs }));
|
if (eigs && eigs.length > 0) {
|
||||||
} catch { /* ignore */ }
|
setItemEigenschaften(prev => ({ ...prev, [artikelId]: eigs }));
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Failed to load eigenschaften for artikel', artikelId, err);
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleCreateSubmit = () => {
|
const handleCreateSubmit = () => {
|
||||||
@@ -1212,21 +1219,19 @@ function AlleAnfragenTab() {
|
|||||||
|
|
||||||
const canEditAny = hasPermission('ausruestungsanfrage:edit');
|
const canEditAny = hasPermission('ausruestungsanfrage:edit');
|
||||||
|
|
||||||
const { data: requests = [], isLoading } = useQuery({
|
const { data: requests = [], isLoading: requestsLoading, isError: requestsError } = useQuery({
|
||||||
queryKey: ['ausruestungsanfrage', 'requests', statusFilter],
|
queryKey: ['ausruestungsanfrage', 'allRequests', statusFilter],
|
||||||
queryFn: () => ausruestungsanfrageApi.getRequests(statusFilter ? { status: statusFilter } : undefined),
|
queryFn: () => ausruestungsanfrageApi.getRequests(statusFilter ? { status: statusFilter } : undefined),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: overview } = useQuery<AusruestungOverview>({
|
const { data: overview } = useQuery<AusruestungOverview>({
|
||||||
queryKey: ['ausruestungsanfrage', 'overview'],
|
queryKey: ['ausruestungsanfrage', 'overview-cards'],
|
||||||
queryFn: () => ausruestungsanfrageApi.getOverview(),
|
queryFn: () => ausruestungsanfrageApi.getOverview(),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (isLoading) return <Typography color="text.secondary">Lade Anfragen...</Typography>;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box>
|
<Box>
|
||||||
{/* Summary cards */}
|
{/* Summary cards — always visible */}
|
||||||
<Grid container spacing={2} sx={{ mb: 3 }}>
|
<Grid container spacing={2} sx={{ mb: 3 }}>
|
||||||
<Grid item xs={6} sm={3}>
|
<Grid item xs={6} sm={3}>
|
||||||
<Paper variant="outlined" sx={{ p: 2, textAlign: 'center' }}>
|
<Paper variant="outlined" sx={{ p: 2, textAlign: 'center' }}>
|
||||||
@@ -1268,7 +1273,11 @@ function AlleAnfragenTab() {
|
|||||||
))}
|
))}
|
||||||
</TextField>
|
</TextField>
|
||||||
|
|
||||||
{requests.length === 0 ? (
|
{requestsLoading ? (
|
||||||
|
<Typography color="text.secondary">Lade Anfragen...</Typography>
|
||||||
|
) : requestsError ? (
|
||||||
|
<Typography color="error">Fehler beim Laden der Anfragen.</Typography>
|
||||||
|
) : requests.length === 0 ? (
|
||||||
<Typography color="text.secondary">Keine Anfragen vorhanden.</Typography>
|
<Typography color="text.secondary">Keine Anfragen vorhanden.</Typography>
|
||||||
) : (
|
) : (
|
||||||
<TableContainer component={Paper} variant="outlined">
|
<TableContainer component={Paper} variant="outlined">
|
||||||
@@ -1299,7 +1308,6 @@ function AlleAnfragenTab() {
|
|||||||
</TableContainer>
|
</TableContainer>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Detail Modal with admin actions */}
|
|
||||||
<DetailModal
|
<DetailModal
|
||||||
requestId={detailId}
|
requestId={detailId}
|
||||||
onClose={() => setDetailId(null)}
|
onClose={() => setDetailId(null)}
|
||||||
|
|||||||
Reference in New Issue
Block a user