50 lines
1.2 KiB
SQL
50 lines
1.2 KiB
SQL
-- 1. Aktive Kunden laden
|
|
SELECT *
|
|
FROM report_customer_config
|
|
WHERE active = TRUE
|
|
ORDER BY customer_id;
|
|
|
|
-- 2. Noch nicht erzeugte Reports eines Monats finden
|
|
SELECT c.*
|
|
FROM report_customer_config c
|
|
WHERE c.active = TRUE
|
|
AND NOT EXISTS (
|
|
SELECT 1
|
|
FROM monthly_report_runs r
|
|
WHERE r.customer_id = c.customer_id
|
|
AND r.report_year = $1
|
|
AND r.report_month = $2
|
|
AND r.report_version = '1.0'
|
|
AND r.status = 'completed'
|
|
);
|
|
|
|
-- 3. Reportlauf reservieren
|
|
INSERT INTO monthly_report_runs (
|
|
customer_id, report_year, report_month, status,
|
|
report_version, prompt_version, template_version
|
|
)
|
|
VALUES ($1, $2, $3, 'processing', '1.0', '1.0', '1.0')
|
|
ON CONFLICT (customer_id, report_year, report_month, report_version)
|
|
DO UPDATE SET
|
|
status = 'processing',
|
|
error_message = NULL,
|
|
started_at = NOW(),
|
|
completed_at = NULL
|
|
RETURNING id;
|
|
|
|
-- 4. Erfolgreich abschliessen
|
|
UPDATE monthly_report_runs
|
|
SET status = 'completed',
|
|
storage_path = $2,
|
|
checksum_sha256 = $3,
|
|
claude_model = $4,
|
|
completed_at = NOW()
|
|
WHERE id = $1;
|
|
|
|
-- 5. Fehler protokollieren
|
|
UPDATE monthly_report_runs
|
|
SET status = 'failed',
|
|
error_message = LEFT($2, 5000),
|
|
completed_at = NOW()
|
|
WHERE id = $1;
|