-- Four-eyes approval for updates of existing e-conomic customers and products. BEGIN; CREATE TABLE IF NOT EXISTS economic_change_requests ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), connection_id INTEGER NOT NULL REFERENCES economic_catalog_connections(id), target_type TEXT NOT NULL CHECK (target_type IN ('customer', 'product')), target_number VARCHAR(25) NOT NULL, requested_changes JSONB NOT NULL, before_snapshot JSONB NOT NULL, proposed_snapshot JSONB NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'applying', 'approved', 'rejected', 'failed', 'cancelled')), reason TEXT NOT NULL, requested_by_user_id INTEGER NOT NULL REFERENCES users(user_id), requested_at TIMESTAMPTZ NOT NULL DEFAULT now(), reviewed_by_user_id INTEGER REFERENCES users(user_id), reviewed_at TIMESTAMPTZ, review_note TEXT, applied_at TIMESTAMPTZ, response_snapshot JSONB, error TEXT, CHECK (char_length(trim(reason)) >= 10) ); CREATE INDEX IF NOT EXISTS idx_economic_change_requests_status ON economic_change_requests(status, requested_at DESC); CREATE UNIQUE INDEX IF NOT EXISTS idx_economic_change_requests_one_pending_target ON economic_change_requests(connection_id, target_type, target_number) WHERE status IN ('pending', 'applying'); INSERT INTO permissions(code, description, category) VALUES ('economic.changes.request', 'Anmode om ændring af eksisterende e-conomic-kunder og varer', 'economic'), ('economic.changes.approve', 'Godkende en anden brugers e-conomic-ændringer', 'economic') ON CONFLICT(code) DO NOTHING; COMMIT;