new features
This commit is contained in:
607
backend/src/services/bestellung.service.ts
Normal file
607
backend/src/services/bestellung.service.ts
Normal file
@@ -0,0 +1,607 @@
|
||||
// =============================================================================
|
||||
// Bestellung (Order) Service
|
||||
// =============================================================================
|
||||
|
||||
import pool from '../config/database';
|
||||
import logger from '../utils/logger';
|
||||
import fs from 'fs';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vendors (Lieferanten)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function getVendors() {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT * FROM lieferanten ORDER BY name`
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getVendors failed', { error });
|
||||
throw new Error('Lieferanten konnten nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function getVendorById(id: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT * FROM lieferanten WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getVendorById failed', { error, id });
|
||||
throw new Error('Lieferant konnte nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function createVendor(data: { name: string; kontakt_person?: string; email?: string; telefon?: string; adresse?: string; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO lieferanten (name, kontakt_person, email, telefon, adresse, notizen, erstellt_von)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING *`,
|
||||
[data.name, data.kontakt_person || null, data.email || null, data.telefon || null, data.adresse || null, data.notizen || null, userId]
|
||||
);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.createVendor failed', { error });
|
||||
throw new Error('Lieferant konnte nicht erstellt werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateVendor(id: number, data: { name?: string; kontakt_person?: string; email?: string; telefon?: string; adresse?: string; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`UPDATE lieferanten
|
||||
SET name = COALESCE($1, name),
|
||||
kontakt_person = COALESCE($2, kontakt_person),
|
||||
email = COALESCE($3, email),
|
||||
telefon = COALESCE($4, telefon),
|
||||
adresse = COALESCE($5, adresse),
|
||||
notizen = COALESCE($6, notizen),
|
||||
aktualisiert_am = NOW()
|
||||
WHERE id = $7
|
||||
RETURNING *`,
|
||||
[data.name, data.kontakt_person, data.email, data.telefon, data.adresse, data.notizen, id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
await logAction(0, 'Lieferant aktualisiert', `Lieferant "${result.rows[0].name}" bearbeitet`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateVendor failed', { error, id });
|
||||
throw new Error('Lieferant konnte nicht aktualisiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteVendor(id: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`DELETE FROM lieferanten WHERE id = $1 RETURNING id`,
|
||||
[id]
|
||||
);
|
||||
return (result.rowCount ?? 0) > 0;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteVendor failed', { error, id });
|
||||
throw new Error('Lieferant konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Orders (Bestellungen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function getOrders(filters?: { status?: string; lieferant_id?: number; besteller_id?: string }) {
|
||||
try {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (filters?.status) {
|
||||
conditions.push(`b.status = $${paramIndex++}`);
|
||||
params.push(filters.status);
|
||||
}
|
||||
if (filters?.lieferant_id) {
|
||||
conditions.push(`b.lieferant_id = $${paramIndex++}`);
|
||||
params.push(filters.lieferant_id);
|
||||
}
|
||||
if (filters?.besteller_id) {
|
||||
conditions.push(`b.erstellt_von = $${paramIndex++}`);
|
||||
params.push(filters.besteller_id);
|
||||
}
|
||||
|
||||
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||
|
||||
const result = await pool.query(
|
||||
`SELECT b.*,
|
||||
l.name AS lieferant_name,
|
||||
u.display_name AS besteller_name,
|
||||
COALESCE(pos.total_cost, 0) AS total_cost,
|
||||
COALESCE(pos.items_count, 0) AS items_count
|
||||
FROM bestellungen b
|
||||
LEFT JOIN lieferanten l ON l.id = b.lieferant_id
|
||||
LEFT JOIN users u ON u.id = b.erstellt_von
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT SUM(einzelpreis * menge) AS total_cost,
|
||||
COUNT(*) AS items_count
|
||||
FROM bestellpositionen
|
||||
WHERE bestellung_id = b.id
|
||||
) pos ON true
|
||||
${whereClause}
|
||||
ORDER BY b.erstellt_am DESC`,
|
||||
params
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getOrders failed', { error });
|
||||
throw new Error('Bestellungen konnten nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrderById(id: number) {
|
||||
try {
|
||||
const orderResult = await pool.query(
|
||||
`SELECT b.*,
|
||||
l.name AS lieferant_name,
|
||||
u.display_name AS besteller_name
|
||||
FROM bestellungen b
|
||||
LEFT JOIN lieferanten l ON l.id = b.lieferant_id
|
||||
LEFT JOIN users u ON u.id = b.erstellt_von
|
||||
WHERE b.id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (orderResult.rows.length === 0) return null;
|
||||
|
||||
const [positionen, dateien, erinnerungen, historie] = await Promise.all([
|
||||
pool.query(`SELECT * FROM bestellpositionen WHERE bestellung_id = $1 ORDER BY id`, [id]),
|
||||
pool.query(`SELECT * FROM bestellung_dateien WHERE bestellung_id = $1 ORDER BY hochgeladen_am DESC`, [id]),
|
||||
pool.query(`SELECT * FROM bestellung_erinnerungen WHERE bestellung_id = $1 ORDER BY faellig_am`, [id]),
|
||||
pool.query(`SELECT h.*, u.display_name AS benutzer_name FROM bestellung_historie h LEFT JOIN users u ON u.id = h.benutzer_id WHERE h.bestellung_id = $1 ORDER BY h.erstellt_am DESC`, [id]),
|
||||
]);
|
||||
|
||||
return {
|
||||
...orderResult.rows[0],
|
||||
positionen: positionen.rows,
|
||||
dateien: dateien.rows,
|
||||
erinnerungen: erinnerungen.rows,
|
||||
historie: historie.rows,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getOrderById failed', { error, id });
|
||||
throw new Error('Bestellung konnte nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function createOrder(data: { titel: string; lieferant_id?: number; beschreibung?: string; prioritaet?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO bestellungen (titel, lieferant_id, beschreibung, prioritaet, erstellt_von)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *`,
|
||||
[data.titel, data.lieferant_id || null, data.beschreibung || null, data.prioritaet || 'normal', userId]
|
||||
);
|
||||
const order = result.rows[0];
|
||||
await logAction(order.id, 'Bestellung erstellt', `Bestellung "${data.titel}" erstellt`, userId);
|
||||
return order;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.createOrder failed', { error });
|
||||
throw new Error('Bestellung konnte nicht erstellt werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateOrder(id: number, data: { titel?: string; lieferant_id?: number; beschreibung?: string; prioritaet?: string; status?: string }, userId: string) {
|
||||
try {
|
||||
// Check current order for status change detection
|
||||
const current = await pool.query(`SELECT * FROM bestellungen WHERE id = $1`, [id]);
|
||||
if (current.rows.length === 0) return null;
|
||||
|
||||
const oldStatus = current.rows[0].status;
|
||||
const newStatus = data.status || oldStatus;
|
||||
|
||||
let bestellt_am = current.rows[0].bestellt_am;
|
||||
let abgeschlossen_am = current.rows[0].abgeschlossen_am;
|
||||
|
||||
if (newStatus !== oldStatus) {
|
||||
if (newStatus === 'bestellt' && !bestellt_am) {
|
||||
bestellt_am = new Date();
|
||||
}
|
||||
if (newStatus === 'abgeschlossen' && !abgeschlossen_am) {
|
||||
abgeschlossen_am = new Date();
|
||||
}
|
||||
}
|
||||
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellungen
|
||||
SET titel = COALESCE($1, titel),
|
||||
lieferant_id = COALESCE($2, lieferant_id),
|
||||
beschreibung = COALESCE($3, beschreibung),
|
||||
prioritaet = COALESCE($4, prioritaet),
|
||||
status = COALESCE($5, status),
|
||||
bestellt_am = $6,
|
||||
abgeschlossen_am = $7,
|
||||
aktualisiert_am = NOW()
|
||||
WHERE id = $8
|
||||
RETURNING *`,
|
||||
[data.titel, data.lieferant_id, data.beschreibung, data.prioritaet, data.status, bestellt_am, abgeschlossen_am, id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
const changes: string[] = [];
|
||||
if (data.titel) changes.push(`Titel geändert`);
|
||||
if (data.lieferant_id) changes.push(`Lieferant geändert`);
|
||||
if (data.status && data.status !== oldStatus) changes.push(`Status: ${oldStatus} → ${data.status}`);
|
||||
if (data.prioritaet) changes.push(`Priorität geändert`);
|
||||
|
||||
await logAction(id, 'Bestellung aktualisiert', changes.join(', ') || 'Bestellung bearbeitet', userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateOrder failed', { error, id });
|
||||
throw new Error('Bestellung konnte nicht aktualisiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteOrder(id: number, _userId: string) {
|
||||
try {
|
||||
// Get file paths before deleting
|
||||
const filesResult = await pool.query(
|
||||
`SELECT dateipfad FROM bestellung_dateien WHERE bestellung_id = $1`,
|
||||
[id]
|
||||
);
|
||||
const filePaths = filesResult.rows.map((r: { dateipfad: string }) => r.dateipfad);
|
||||
|
||||
const result = await pool.query(
|
||||
`DELETE FROM bestellungen WHERE id = $1 RETURNING id`,
|
||||
[id]
|
||||
);
|
||||
if ((result.rowCount ?? 0) === 0) return false;
|
||||
|
||||
// Remove files from disk
|
||||
for (const filePath of filePaths) {
|
||||
try {
|
||||
if (filePath && fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('Failed to delete file from disk', { filePath, error: err });
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteOrder failed', { error, id });
|
||||
throw new Error('Bestellung konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
const VALID_STATUS_TRANSITIONS: Record<string, string[]> = {
|
||||
entwurf: ['bestellt', 'storniert'],
|
||||
bestellt: ['teillieferung', 'vollstaendig', 'storniert'],
|
||||
teillieferung: ['vollstaendig', 'storniert'],
|
||||
vollstaendig: ['abgeschlossen'],
|
||||
abgeschlossen: [],
|
||||
storniert: ['entwurf'],
|
||||
};
|
||||
|
||||
async function updateOrderStatus(id: number, status: string, userId: string) {
|
||||
try {
|
||||
const current = await pool.query(`SELECT status FROM bestellungen WHERE id = $1`, [id]);
|
||||
if (current.rows.length === 0) return null;
|
||||
|
||||
const oldStatus = current.rows[0].status;
|
||||
const allowed = VALID_STATUS_TRANSITIONS[oldStatus] || [];
|
||||
if (!allowed.includes(status)) {
|
||||
throw new Error(`Ungültiger Statusübergang: ${oldStatus} → ${status}`);
|
||||
}
|
||||
|
||||
const updates: string[] = ['status = $1', 'aktualisiert_am = NOW()'];
|
||||
const params: unknown[] = [status];
|
||||
let paramIndex = 2;
|
||||
|
||||
if (status === 'bestellt') {
|
||||
updates.push(`bestellt_am = COALESCE(bestellt_am, NOW())`);
|
||||
}
|
||||
if (status === 'abgeschlossen') {
|
||||
updates.push(`abgeschlossen_am = COALESCE(abgeschlossen_am, NOW())`);
|
||||
}
|
||||
|
||||
params.push(id);
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellungen SET ${updates.join(', ')} WHERE id = $${paramIndex} RETURNING *`,
|
||||
params
|
||||
);
|
||||
|
||||
await logAction(id, 'Status geändert', `${oldStatus} → ${status}`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateOrderStatus failed', { error, id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Line Items (Bestellpositionen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function addLineItem(bestellungId: number, data: { artikel: string; menge: number; einheit?: string; einzelpreis?: number; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO bestellpositionen (bestellung_id, artikel, menge, einheit, einzelpreis, notizen)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING *`,
|
||||
[bestellungId, data.artikel, data.menge, data.einheit || 'Stück', data.einzelpreis || 0, data.notizen || null]
|
||||
);
|
||||
await logAction(bestellungId, 'Position hinzugefügt', `"${data.artikel}" x${data.menge}`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.addLineItem failed', { error, bestellungId });
|
||||
throw new Error('Position konnte nicht hinzugefügt werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateLineItem(id: number, data: { artikel?: string; menge?: number; einheit?: string; einzelpreis?: number; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellpositionen
|
||||
SET artikel = COALESCE($1, artikel),
|
||||
menge = COALESCE($2, menge),
|
||||
einheit = COALESCE($3, einheit),
|
||||
einzelpreis = COALESCE($4, einzelpreis),
|
||||
notizen = COALESCE($5, notizen)
|
||||
WHERE id = $6
|
||||
RETURNING *`,
|
||||
[data.artikel, data.menge, data.einheit, data.einzelpreis, data.notizen, id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
const item = result.rows[0];
|
||||
await logAction(item.bestellung_id, 'Position aktualisiert', `"${item.artikel}" bearbeitet`, userId);
|
||||
return item;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateLineItem failed', { error, id });
|
||||
throw new Error('Position konnte nicht aktualisiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLineItem(id: number, userId: string) {
|
||||
try {
|
||||
const item = await pool.query(`SELECT * FROM bestellpositionen WHERE id = $1`, [id]);
|
||||
if (item.rows.length === 0) return false;
|
||||
|
||||
await pool.query(`DELETE FROM bestellpositionen WHERE id = $1`, [id]);
|
||||
await logAction(item.rows[0].bestellung_id, 'Position entfernt', `"${item.rows[0].artikel}" entfernt`, userId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteLineItem failed', { error, id });
|
||||
throw new Error('Position konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateReceivedQuantity(id: number, menge: number, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellpositionen SET erhalten_menge = $1 WHERE id = $2 RETURNING *`,
|
||||
[menge, id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
const item = result.rows[0];
|
||||
await logAction(item.bestellung_id, 'Liefermenge aktualisiert', `"${item.artikel}": ${menge} von ${item.menge} erhalten`, userId);
|
||||
|
||||
// Check if all items for this order are fully received
|
||||
const allItems = await pool.query(
|
||||
`SELECT menge, erhalten_menge FROM bestellpositionen WHERE bestellung_id = $1`,
|
||||
[item.bestellung_id]
|
||||
);
|
||||
const allReceived = allItems.rows.every((r: { menge: number; erhalten_menge: number }) => r.erhalten_menge >= r.menge);
|
||||
const someReceived = allItems.rows.some((r: { menge: number; erhalten_menge: number }) => (r.erhalten_menge ?? 0) > 0);
|
||||
|
||||
// Auto-update order status if currently 'bestellt'
|
||||
const order = await pool.query(`SELECT status FROM bestellungen WHERE id = $1`, [item.bestellung_id]);
|
||||
if (order.rows.length > 0 && (order.rows[0].status === 'bestellt' || order.rows[0].status === 'teillieferung')) {
|
||||
if (allReceived) {
|
||||
await pool.query(
|
||||
`UPDATE bestellungen SET status = 'vollstaendig', aktualisiert_am = NOW() WHERE id = $1`,
|
||||
[item.bestellung_id]
|
||||
);
|
||||
await logAction(item.bestellung_id, 'Status geändert', 'Alle Positionen vollständig erhalten → vollstaendig', userId);
|
||||
} else if (someReceived && order.rows[0].status === 'bestellt') {
|
||||
await pool.query(
|
||||
`UPDATE bestellungen SET status = 'teillieferung', aktualisiert_am = NOW() WHERE id = $1`,
|
||||
[item.bestellung_id]
|
||||
);
|
||||
await logAction(item.bestellung_id, 'Status geändert', 'Teillieferung eingegangen → teillieferung', userId);
|
||||
}
|
||||
}
|
||||
|
||||
return item;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.updateReceivedQuantity failed', { error, id });
|
||||
throw new Error('Liefermenge konnte nicht aktualisiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Files (Bestellung Dateien)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function addFile(bestellungId: number, fileData: { dateiname: string; dateipfad: string; dateityp: string; dateigroesse: number }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO bestellung_dateien (bestellung_id, dateiname, dateipfad, dateityp, dateigroesse, hochgeladen_von)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING *`,
|
||||
[bestellungId, fileData.dateiname, fileData.dateipfad, fileData.dateityp, fileData.dateigroesse, userId]
|
||||
);
|
||||
await logAction(bestellungId, 'Datei hochgeladen', `"${fileData.dateiname}"`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.addFile failed', { error, bestellungId });
|
||||
throw new Error('Datei konnte nicht gespeichert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFile(id: number, userId: string) {
|
||||
try {
|
||||
const fileResult = await pool.query(
|
||||
`SELECT * FROM bestellung_dateien WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (fileResult.rows.length === 0) return null;
|
||||
|
||||
const file = fileResult.rows[0];
|
||||
await pool.query(`DELETE FROM bestellung_dateien WHERE id = $1`, [id]);
|
||||
await logAction(file.bestellung_id, 'Datei gelöscht', `"${file.dateiname}"`, userId);
|
||||
|
||||
return { dateipfad: file.dateipfad, dateiname: file.dateiname };
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteFile failed', { error, id });
|
||||
throw new Error('Datei konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function getFilesByOrder(bestellungId: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT * FROM bestellung_dateien WHERE bestellung_id = $1 ORDER BY hochgeladen_am DESC`,
|
||||
[bestellungId]
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getFilesByOrder failed', { error, bestellungId });
|
||||
throw new Error('Dateien konnten nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reminders (Bestellung Erinnerungen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function addReminder(bestellungId: number, data: { titel: string; faellig_am: string; notizen?: string }, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO bestellung_erinnerungen (bestellung_id, titel, faellig_am, notizen, erstellt_von)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *`,
|
||||
[bestellungId, data.titel, data.faellig_am, data.notizen || null, userId]
|
||||
);
|
||||
await logAction(bestellungId, 'Erinnerung erstellt', `"${data.titel}" fällig am ${data.faellig_am}`, userId);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.addReminder failed', { error, bestellungId });
|
||||
throw new Error('Erinnerung konnte nicht erstellt werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function markReminderDone(id: number, userId: string) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`UPDATE bestellung_erinnerungen SET erledigt = TRUE WHERE id = $1 RETURNING *`,
|
||||
[id]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
|
||||
const reminder = result.rows[0];
|
||||
await logAction(reminder.bestellung_id, 'Erinnerung erledigt', `"${reminder.titel}"`, userId);
|
||||
return reminder;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.markReminderDone failed', { error, id });
|
||||
throw new Error('Erinnerung konnte nicht als erledigt markiert werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteReminder(id: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`DELETE FROM bestellung_erinnerungen WHERE id = $1 RETURNING id`,
|
||||
[id]
|
||||
);
|
||||
return (result.rowCount ?? 0) > 0;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.deleteReminder failed', { error, id });
|
||||
throw new Error('Erinnerung konnte nicht gelöscht werden');
|
||||
}
|
||||
}
|
||||
|
||||
async function getDueReminders() {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT e.*, b.titel AS bestellung_titel, b.erstellt_von AS besteller_id
|
||||
FROM bestellung_erinnerungen e
|
||||
JOIN bestellungen b ON b.id = e.bestellung_id
|
||||
WHERE e.faellig_am <= NOW() AND e.erledigt = FALSE
|
||||
ORDER BY e.faellig_am`
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getDueReminders failed', { error });
|
||||
throw new Error('Fällige Erinnerungen konnten nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Audit History (Bestellung Historie)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function logAction(bestellungId: number, aktion: string, details: string, userId: string) {
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO bestellung_historie (bestellung_id, benutzer_id, aktion, details)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[bestellungId, userId, aktion, details]
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.logAction failed', { error, bestellungId, aktion });
|
||||
// Non-fatal — don't propagate
|
||||
}
|
||||
}
|
||||
|
||||
async function getHistory(bestellungId: number) {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
`SELECT h.*, u.display_name AS benutzer_name
|
||||
FROM bestellung_historie h
|
||||
LEFT JOIN users u ON u.id = h.benutzer_id
|
||||
WHERE h.bestellung_id = $1
|
||||
ORDER BY h.erstellt_am DESC`,
|
||||
[bestellungId]
|
||||
);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
logger.error('BestellungService.getHistory failed', { error, bestellungId });
|
||||
throw new Error('Historie konnte nicht geladen werden');
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
// Vendors
|
||||
getVendors,
|
||||
getVendorById,
|
||||
createVendor,
|
||||
updateVendor,
|
||||
deleteVendor,
|
||||
// Orders
|
||||
getOrders,
|
||||
getOrderById,
|
||||
createOrder,
|
||||
updateOrder,
|
||||
deleteOrder,
|
||||
updateOrderStatus,
|
||||
// Line Items
|
||||
addLineItem,
|
||||
updateLineItem,
|
||||
deleteLineItem,
|
||||
updateReceivedQuantity,
|
||||
// Files
|
||||
addFile,
|
||||
deleteFile,
|
||||
getFilesByOrder,
|
||||
// Reminders
|
||||
addReminder,
|
||||
markReminderDone,
|
||||
deleteReminder,
|
||||
getDueReminders,
|
||||
// Audit
|
||||
logAction,
|
||||
getHistory,
|
||||
};
|
||||
323
backend/src/services/shop.service.ts
Normal file
323
backend/src/services/shop.service.ts
Normal file
@@ -0,0 +1,323 @@
|
||||
import pool from '../config/database';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Catalog Items (shop_artikel)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function getItems(filters?: { kategorie?: string; aktiv?: boolean }) {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (filters?.kategorie) {
|
||||
params.push(filters.kategorie);
|
||||
conditions.push(`kategorie = $${params.length}`);
|
||||
}
|
||||
if (filters?.aktiv !== undefined) {
|
||||
params.push(filters.aktiv);
|
||||
conditions.push(`aktiv = $${params.length}`);
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||
const result = await pool.query(
|
||||
`SELECT * FROM shop_artikel ${where} ORDER BY kategorie, bezeichnung`,
|
||||
params,
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async function getItemById(id: number) {
|
||||
const result = await pool.query('SELECT * FROM shop_artikel WHERE id = $1', [id]);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async function createItem(
|
||||
data: {
|
||||
bezeichnung: string;
|
||||
beschreibung?: string;
|
||||
kategorie?: string;
|
||||
geschaetzte_kosten?: number;
|
||||
url?: string;
|
||||
aktiv?: boolean;
|
||||
},
|
||||
userId: string,
|
||||
) {
|
||||
const result = await pool.query(
|
||||
`INSERT INTO shop_artikel (bezeichnung, beschreibung, kategorie, geschaetzte_kosten, url, aktiv, erstellt_von)
|
||||
VALUES ($1, $2, $3, $4, $5, COALESCE($6, true), $7)
|
||||
RETURNING *`,
|
||||
[data.bezeichnung, data.beschreibung || null, data.kategorie || null, data.geschaetzte_kosten || null, data.url || null, data.aktiv ?? true, userId],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async function updateItem(
|
||||
id: number,
|
||||
data: {
|
||||
bezeichnung?: string;
|
||||
beschreibung?: string;
|
||||
kategorie?: string;
|
||||
geschaetzte_kosten?: number;
|
||||
url?: string;
|
||||
aktiv?: boolean;
|
||||
},
|
||||
userId: string,
|
||||
) {
|
||||
const fields: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (data.bezeichnung !== undefined) {
|
||||
params.push(data.bezeichnung);
|
||||
fields.push(`bezeichnung = $${params.length}`);
|
||||
}
|
||||
if (data.beschreibung !== undefined) {
|
||||
params.push(data.beschreibung);
|
||||
fields.push(`beschreibung = $${params.length}`);
|
||||
}
|
||||
if (data.kategorie !== undefined) {
|
||||
params.push(data.kategorie);
|
||||
fields.push(`kategorie = $${params.length}`);
|
||||
}
|
||||
if (data.geschaetzte_kosten !== undefined) {
|
||||
params.push(data.geschaetzte_kosten);
|
||||
fields.push(`geschaetzte_kosten = $${params.length}`);
|
||||
}
|
||||
if (data.url !== undefined) {
|
||||
params.push(data.url);
|
||||
fields.push(`url = $${params.length}`);
|
||||
}
|
||||
if (data.aktiv !== undefined) {
|
||||
params.push(data.aktiv);
|
||||
fields.push(`aktiv = $${params.length}`);
|
||||
}
|
||||
|
||||
if (fields.length === 0) {
|
||||
return getItemById(id);
|
||||
}
|
||||
|
||||
params.push(userId);
|
||||
fields.push(`aktualisiert_von = $${params.length}`);
|
||||
params.push(new Date());
|
||||
fields.push(`aktualisiert_am = $${params.length}`);
|
||||
|
||||
params.push(id);
|
||||
const result = await pool.query(
|
||||
`UPDATE shop_artikel SET ${fields.join(', ')} WHERE id = $${params.length} RETURNING *`,
|
||||
params,
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async function deleteItem(id: number) {
|
||||
await pool.query('DELETE FROM shop_artikel WHERE id = $1', [id]);
|
||||
}
|
||||
|
||||
async function getCategories() {
|
||||
const result = await pool.query(
|
||||
'SELECT DISTINCT kategorie FROM shop_artikel WHERE kategorie IS NOT NULL ORDER BY kategorie',
|
||||
);
|
||||
return result.rows.map((r: { kategorie: string }) => r.kategorie);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Requests (shop_anfragen)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function getRequests(filters?: { status?: string; anfrager_id?: string }) {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (filters?.status) {
|
||||
params.push(filters.status);
|
||||
conditions.push(`a.status = $${params.length}`);
|
||||
}
|
||||
if (filters?.anfrager_id) {
|
||||
params.push(filters.anfrager_id);
|
||||
conditions.push(`a.anfrager_id = $${params.length}`);
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||
const result = await pool.query(
|
||||
`SELECT a.*,
|
||||
u.vorname || ' ' || u.nachname AS anfrager_name,
|
||||
u2.vorname || ' ' || u2.nachname AS bearbeitet_von_name,
|
||||
(SELECT COUNT(*)::int FROM shop_anfrage_positionen p WHERE p.anfrage_id = a.id) AS positionen_count
|
||||
FROM shop_anfragen a
|
||||
LEFT JOIN users u ON u.id = a.anfrager_id
|
||||
LEFT JOIN users u2 ON u2.id = a.bearbeitet_von
|
||||
${where}
|
||||
ORDER BY a.erstellt_am DESC`,
|
||||
params,
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async function getMyRequests(userId: string) {
|
||||
const result = await pool.query(
|
||||
`SELECT a.*,
|
||||
(SELECT COUNT(*)::int FROM shop_anfrage_positionen p WHERE p.anfrage_id = a.id) AS positionen_count
|
||||
FROM shop_anfragen a
|
||||
WHERE a.anfrager_id = $1
|
||||
ORDER BY a.erstellt_am DESC`,
|
||||
[userId],
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async function getRequestById(id: number) {
|
||||
const reqResult = await pool.query(
|
||||
`SELECT a.*,
|
||||
u.vorname || ' ' || u.nachname AS anfrager_name,
|
||||
u2.vorname || ' ' || u2.nachname AS bearbeitet_von_name
|
||||
FROM shop_anfragen a
|
||||
LEFT JOIN users u ON u.id = a.anfrager_id
|
||||
LEFT JOIN users u2 ON u2.id = a.bearbeitet_von
|
||||
WHERE a.id = $1`,
|
||||
[id],
|
||||
);
|
||||
if (reqResult.rows.length === 0) return null;
|
||||
|
||||
const positionen = await pool.query(
|
||||
`SELECT p.*, sa.bezeichnung AS artikel_bezeichnung, sa.kategorie AS artikel_kategorie
|
||||
FROM shop_anfrage_positionen p
|
||||
LEFT JOIN shop_artikel sa ON sa.id = p.artikel_id
|
||||
WHERE p.anfrage_id = $1
|
||||
ORDER BY p.id`,
|
||||
[id],
|
||||
);
|
||||
|
||||
const bestellungen = await pool.query(
|
||||
`SELECT b.*
|
||||
FROM shop_anfrage_bestellung ab
|
||||
JOIN bestellungen b ON b.id = ab.bestellung_id
|
||||
WHERE ab.anfrage_id = $1`,
|
||||
[id],
|
||||
);
|
||||
|
||||
return {
|
||||
...reqResult.rows[0],
|
||||
positionen: positionen.rows,
|
||||
bestellungen: bestellungen.rows,
|
||||
};
|
||||
}
|
||||
|
||||
async function createRequest(
|
||||
userId: string,
|
||||
items: { artikel_id?: number; bezeichnung: string; menge: number; notizen?: string }[],
|
||||
notizen?: string,
|
||||
) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
const anfrageResult = await client.query(
|
||||
`INSERT INTO shop_anfragen (anfrager_id, notizen)
|
||||
VALUES ($1, $2)
|
||||
RETURNING *`,
|
||||
[userId, notizen || null],
|
||||
);
|
||||
const anfrage = anfrageResult.rows[0];
|
||||
|
||||
for (const item of items) {
|
||||
let bezeichnung = item.bezeichnung;
|
||||
|
||||
// If artikel_id is provided, copy bezeichnung from catalog
|
||||
if (item.artikel_id) {
|
||||
const artikelResult = await client.query(
|
||||
'SELECT bezeichnung FROM shop_artikel WHERE id = $1',
|
||||
[item.artikel_id],
|
||||
);
|
||||
if (artikelResult.rows.length > 0) {
|
||||
bezeichnung = artikelResult.rows[0].bezeichnung;
|
||||
}
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`INSERT INTO shop_anfrage_positionen (anfrage_id, artikel_id, bezeichnung, menge, notizen)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
[anfrage.id, item.artikel_id || null, bezeichnung, item.menge, item.notizen || null],
|
||||
);
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
return getRequestById(anfrage.id);
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
logger.error('shopService.createRequest failed', { error });
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function updateRequestStatus(
|
||||
id: number,
|
||||
status: string,
|
||||
adminNotizen?: string,
|
||||
bearbeitetVon?: string,
|
||||
) {
|
||||
const result = await pool.query(
|
||||
`UPDATE shop_anfragen
|
||||
SET status = $1,
|
||||
admin_notizen = COALESCE($2, admin_notizen),
|
||||
bearbeitet_von = COALESCE($3, bearbeitet_von),
|
||||
bearbeitet_am = NOW()
|
||||
WHERE id = $4
|
||||
RETURNING *`,
|
||||
[status, adminNotizen || null, bearbeitetVon || null, id],
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async function deleteRequest(id: number) {
|
||||
await pool.query('DELETE FROM shop_anfragen WHERE id = $1', [id]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Linking (shop_anfrage_bestellung)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function linkToOrder(anfrageId: number, bestellungId: number) {
|
||||
await pool.query(
|
||||
`INSERT INTO shop_anfrage_bestellung (anfrage_id, bestellung_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT DO NOTHING`,
|
||||
[anfrageId, bestellungId],
|
||||
);
|
||||
}
|
||||
|
||||
async function unlinkFromOrder(anfrageId: number, bestellungId: number) {
|
||||
await pool.query(
|
||||
'DELETE FROM shop_anfrage_bestellung WHERE anfrage_id = $1 AND bestellung_id = $2',
|
||||
[anfrageId, bestellungId],
|
||||
);
|
||||
}
|
||||
|
||||
async function getLinkedOrders(anfrageId: number) {
|
||||
const result = await pool.query(
|
||||
`SELECT b.*
|
||||
FROM shop_anfrage_bestellung ab
|
||||
JOIN bestellungen b ON b.id = ab.bestellung_id
|
||||
WHERE ab.anfrage_id = $1`,
|
||||
[anfrageId],
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
export default {
|
||||
getItems,
|
||||
getItemById,
|
||||
createItem,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
getCategories,
|
||||
getRequests,
|
||||
getMyRequests,
|
||||
getRequestById,
|
||||
createRequest,
|
||||
updateRequestStatus,
|
||||
deleteRequest,
|
||||
linkToOrder,
|
||||
unlinkFromOrder,
|
||||
getLinkedOrders,
|
||||
};
|
||||
44
backend/src/services/upload.service.ts
Normal file
44
backend/src/services/upload.service.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import logger from '../utils/logger';
|
||||
import { THUMBNAIL_DIR } from '../middleware/upload';
|
||||
|
||||
let sharp: any = null;
|
||||
try {
|
||||
sharp = require('sharp');
|
||||
} catch {
|
||||
logger.warn('sharp not installed — thumbnail generation disabled');
|
||||
}
|
||||
|
||||
async function generateThumbnail(filePath: string, mimeType: string): Promise<string | null> {
|
||||
if (!sharp) return null;
|
||||
if (!mimeType.startsWith('image/')) return null;
|
||||
|
||||
try {
|
||||
const ext = path.extname(filePath);
|
||||
const baseName = path.basename(filePath, ext);
|
||||
const thumbPath = path.join(THUMBNAIL_DIR, `${baseName}_thumb.webp`);
|
||||
|
||||
await sharp(filePath)
|
||||
.resize(200, 200, { fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 70 })
|
||||
.toFile(thumbPath);
|
||||
|
||||
return thumbPath;
|
||||
} catch (error) {
|
||||
logger.error('Thumbnail generation failed', { filePath, error });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function deleteFile(filePath: string): void {
|
||||
try {
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('File deletion failed', { filePath, error });
|
||||
}
|
||||
}
|
||||
|
||||
export default { generateThumbnail, deleteFile };
|
||||
Reference in New Issue
Block a user