36 lines
1.2 KiB
SQL
36 lines
1.2 KiB
SQL
-- +goose Up
|
|||
|
|
-- Company owner is the billing representative (distinct from membership admin|member).
|
||
|
|
-- Platform staff remain above all tenants.
|
||
|
|
|
||
|
|
ALTER TABLE companies
|
||
|
|
ADD COLUMN IF NOT EXISTS owner_user_id UUID REFERENCES users(id) ON DELETE SET NULL;
|
||
|
|
|
||
|
|
CREATE INDEX IF NOT EXISTS companies_owner_user_id_idx ON companies(owner_user_id);
|
||
|
|
|
||
|
|
-- Backfill: prefer earliest active admin, else earliest active member.
|
||
|
|
UPDATE companies c
|
||
|
|
SET owner_user_id = sub.user_id
|
||
|
|
FROM (
|
||
|
|
SELECT DISTINCT ON (m.company_id) m.company_id, m.user_id
|
||
|
|
FROM memberships m
|
||
|
|
WHERE m.status = 'active'
|
||
|
|
ORDER BY m.company_id,
|
||
|
|
CASE WHEN m.role = 'admin' THEN 0 ELSE 1 END,
|
||
|
|
m.created_at ASC,
|
||
|
|
m.user_id ASC
|
||
|
|
) sub
|
||
|
|
WHERE c.id = sub.company_id
|
||
|
|
AND c.owner_user_id IS NULL;
|
||
|
|
|
||
|
|
-- Prefer a1-primary as owner on the A1 cohort tenant when present.
|
||
|
|
UPDATE companies c
|
||
|
|
SET owner_user_id = u.id
|
||
|
|
FROM users u
|
||
|
|
JOIN memberships m ON m.user_id = u.id AND m.company_id = c.id AND m.status = 'active'
|
||
|
|
WHERE c.legacy_company_id = '97e1a309-3d23-4aa2-b518-8e8d7afdfec7'
|
||
|
|
AND lower(u.email) = 'a1-primary@descrybe.local';
|
||
|
|
|
||
|
|
-- +goose Down
|
||
|
|
DROP INDEX IF EXISTS companies_owner_user_id_idx;
|
||
|
|
ALTER TABLE companies DROP COLUMN IF EXISTS owner_user_id;
|