Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

9.4 KB
Raw Blame
-- A one-time snapshot. SQLx commits the copy and its migration record together.
-- Keep legacy records/properties intact; subsequent pipeline edits are independent.
SELECT pg_advisory_xact_lock(1413824845, 1);
LOCK TABLE team, team_crm_settings, crm_companies, property_definitions,
    property_options, entity_properties IN SHARE ROW EXCLUSIVE MODE;

-- Migration-local UUIDv7 generation for PostgreSQL 16 (uuidv7() needs PG18).
-- Runtime identities continue to be generated by the application.
CREATE FUNCTION pg_temp.sales_uuid() RETURNS UUID LANGUAGE SQL VOLATILE AS $$
    SELECT encode(set_byte(set_byte(bytes, 6, (get_byte(bytes, 6) & 15) | 112),
        8, (get_byte(bytes, 8) & 63) | 128), 'hex')::uuid
    FROM (SELECT overlay(gen_random_bytes(16) placing
        decode(lpad(to_hex((extract(epoch FROM clock_timestamp()) * 1000)::bigint), 12, '0'), 'hex')
        FROM 1 FOR 6) AS bytes) random;
$$;

CREATE TEMP TABLE sales_teams ON COMMIT DROP AS
SELECT t.id AS team_id, t.owner_id, s.legacy_stage_ids,
    pg_temp.sales_uuid() AS pipeline_id, pg_temp.sales_uuid() AS database_id,
    pg_temp.sales_uuid() AS table_id, d.id AS stage_definition
FROM team t JOIN team_crm_settings s ON s.team_id = t.id AND s.crm_enabled
LEFT JOIN property_definitions d ON d.team_id = t.id AND d.display_name = 'Deal Stage'
WHERE EXISTS (SELECT 1 FROM crm_companies c WHERE c.team_id = t.id AND NOT c.hidden);
ALTER TABLE sales_teams ADD PRIMARY KEY (team_id);

DO $$ BEGIN
    IF EXISTS (SELECT 1 FROM sales_teams t JOIN property_definitions d ON d.id = t.stage_definition
               WHERE d.data_type <> 'SELECT_STRING' OR d.is_multi_select) THEN
        RAISE EXCEPTION 'Sales migration requires a single-select Deal Stage definition';
    END IF;
END $$;

CREATE TEMP TABLE sales_columns ON COMMIT DROP AS
SELECT t.team_id, t.database_id, t.table_id, pg_temp.sales_uuid() AS column_id,
    pg_temp.sales_uuid() AS definition_id, c.*
FROM sales_teams t CROSS JOIN (VALUES
    ('Company', 'ENTITY', 'COMPANY', '20', false),
    ('Stage', 'SELECT_STRING', NULL, '40', true),
    ('Owner', 'ENTITY', 'USER', '60', true),
    ('Revenue', 'NUMBER', NULL, '80', true)
) c(name, data_type, entity_type, position, nullable);

CREATE TEMP TABLE sales_system_stages ON COMMIT DROP AS
SELECT ('00000001-0000-0000-0010-' || lpad(n::text, 12, '0'))::uuid AS id, label, n - 1 AS position
FROM (VALUES (1, 'Lead'), (2, 'Qualified'), (3, 'Demo'), (4, 'Trial'),
    (5, 'Negotiation'), (6, 'Customer'), (7, 'Churned')) s(n, label);

CREATE TEMP TABLE sales_options ON COMMIT DROP AS
SELECT t.team_id, s.id AS source_id, pg_temp.sales_uuid() AS id, s.label, s.position::int
FROM sales_teams t CROSS JOIN sales_system_stages s WHERE t.stage_definition IS NULL
UNION ALL
SELECT t.team_id, o.id, pg_temp.sales_uuid(), o.string_value,
    (row_number() OVER (PARTITION BY t.team_id ORDER BY o.display_order, o.id) - 1)::int
FROM sales_teams t JOIN property_options o ON o.property_definition_id = t.stage_definition;
ALTER TABLE sales_options ALTER COLUMN label SET NOT NULL;

CREATE TEMP TABLE sales_rows ON COMMIT DROP AS
SELECT c.id AS company_id, t.team_id, t.table_id, t.owner_id, pg_temp.sales_uuid() AS row_id,
    lpad(to_hex(row_number() OVER (PARTITION BY t.team_id ORDER BY c.id)), 16, '0') || '80' AS position,
    direct.values AS stage, legacy.values AS legacy_stage, owner.values AS owner, revenue.values AS revenue
FROM sales_teams t JOIN crm_companies c ON c.team_id = t.team_id AND NOT c.hidden
LEFT JOIN entity_properties direct ON direct.entity_type = 'COMPANY' AND direct.entity_id = c.id::text
    AND direct.property_definition_id = coalesce(t.stage_definition, '00000001-0000-0000-0000-000000000010'::uuid)
LEFT JOIN entity_properties legacy ON legacy.entity_type = 'COMPANY' AND legacy.entity_id = c.id::text
    AND legacy.property_definition_id = '00000001-0000-0000-0000-000000000010'
LEFT JOIN entity_properties owner ON owner.entity_type = 'COMPANY' AND owner.entity_id = c.id::text
    AND owner.property_definition_id = '00000001-0000-0000-0000-000000000011'
LEFT JOIN entity_properties revenue ON revenue.entity_type = 'COMPANY' AND revenue.entity_id = c.id::text
    AND revenue.property_definition_id = '00000001-0000-0000-0000-000000000012';

-- Validate before copying so malformed legacy values cannot silently disappear.
DO $$ BEGIN
    IF EXISTS (SELECT 1 FROM sales_rows r CROSS JOIN LATERAL (VALUES (r.stage), (r.legacy_stage)) s(value)
        WHERE value IS NOT NULL AND value <> 'null'::jsonb AND CASE
            WHEN value ->> 'type' IS DISTINCT FROM 'SelectOption'
              OR jsonb_typeof(value -> 'value') IS DISTINCT FROM 'array' THEN true
            ELSE jsonb_array_length(value -> 'value') > 1
              OR (jsonb_array_length(value -> 'value') = 1 AND jsonb_typeof(value -> 'value' -> 0) <> 'string') END) THEN
        RAISE EXCEPTION 'Sales migration found an invalid single-select stage';
    END IF;
    IF EXISTS (SELECT 1 FROM sales_rows WHERE owner IS NOT NULL AND owner <> 'null'::jsonb AND CASE
        WHEN owner ->> 'type' IS DISTINCT FROM 'EntityReference'
          OR jsonb_typeof(owner -> 'value') IS DISTINCT FROM 'array' THEN true
        ELSE jsonb_array_length(owner -> 'value') > 1 OR EXISTS (
            SELECT 1 FROM jsonb_array_elements(owner -> 'value') ref
            WHERE ref ->> 'entity_type' IS DISTINCT FROM 'USER'
               OR coalesce(ref ->> 'entity_id', '') = '') END) THEN
        RAISE EXCEPTION 'Sales migration found an invalid owner';
    END IF;
    IF EXISTS (SELECT 1 FROM sales_rows WHERE revenue IS NOT NULL AND revenue <> 'null'::jsonb
        AND (revenue ->> 'type' IS DISTINCT FROM 'Number'
             OR jsonb_typeof(revenue -> 'value') IS DISTINCT FROM 'number')) THEN
        RAISE EXCEPTION 'Sales migration found invalid revenue';
    END IF;
END $$;

ALTER TABLE sales_rows ADD COLUMN stage_option UUID;
UPDATE sales_rows r SET stage_option = coalesce(
    (SELECT o.id FROM sales_options o WHERE o.team_id = r.team_id AND o.source_id::text = r.stage -> 'value' ->> 0),
    (SELECT o.id FROM sales_options o WHERE o.team_id = r.team_id
        AND o.source_id::text = t.legacy_stage_ids ->> (r.legacy_stage -> 'value' ->> 0)),
    (SELECT o.id FROM sales_options o JOIN sales_system_stages s ON lower(s.label) = lower(o.label)
        WHERE o.team_id = r.team_id AND s.id::text = r.legacy_stage -> 'value' ->> 0
        ORDER BY o.position LIMIT 1)
) FROM sales_teams t WHERE t.team_id = r.team_id;
DO $$ BEGIN
    IF EXISTS (SELECT 1 FROM sales_rows WHERE stage_option IS NULL
               AND (stage -> 'value' ->> 0 IS NOT NULL OR legacy_stage -> 'value' ->> 0 IS NOT NULL)) THEN
        RAISE EXCEPTION 'Sales migration found an unmapped stage; repair the CRM stage mapping and retry';
    END IF;
END $$;

INSERT INTO databases (id) SELECT database_id FROM sales_teams;
INSERT INTO database_tables (id, database_id, name, position)
SELECT table_id, database_id, 'Records', '80' FROM sales_teams;
INSERT INTO property_definitions (id, database_id, display_name, data_type, is_multi_select, specific_entity_type)
SELECT definition_id, database_id, name, data_type::property_data_type, false, entity_type::property_entity_type
FROM sales_columns;
INSERT INTO database_columns (id, table_id, property_definition_id, position, nullable)
SELECT column_id, table_id, definition_id, position, nullable FROM sales_columns;
INSERT INTO database_column_protections (column_id, capability)
SELECT column_id, capability FROM sales_columns
CROSS JOIN (VALUES ('delete'), ('change_type')) p(capability) WHERE name = 'Company';
INSERT INTO property_options (id, property_definition_id, string_value, display_order, color)
SELECT o.id, c.definition_id, o.label, o.position,
    (ARRAY['#0091FF', '#46A758', '#8E4EC6', '#F76B15', '#E93D82', '#12A594',
           '#FFB224', '#3E63DD', '#E5484D', '#F5D90A', '#889096', '#E54D2E'])[o.position % 12 + 1]
FROM sales_options o JOIN sales_columns c ON c.team_id = o.team_id AND c.name = 'Stage';
INSERT INTO crm_pipeline_entities (id, team_id, database_id, name, user_id, table_id, primary_column_id, record_type)
SELECT t.pipeline_id, t.team_id, t.database_id, 'Sales', t.owner_id, t.table_id, c.column_id, 'company'
FROM sales_teams t JOIN sales_columns c ON c.team_id = t.team_id AND c.name = 'Company';
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
SELECT pipeline_id, 'crm_pipeline', owner_id, 'user'::entity_access_source_type, 'owner'::"AccessLevel" FROM sales_teams
UNION ALL
SELECT pipeline_id, 'crm_pipeline', team_id::text, 'team', 'edit' FROM sales_teams;
INSERT INTO database_rows (id, table_id, position, created_by)
SELECT row_id, table_id, position, owner_id FROM sales_rows;
INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
SELECT pg_temp.sales_uuid(), r.row_id::text, 'DATABASE_ROW', c.definition_id, v.value
FROM sales_rows r JOIN sales_columns c ON c.team_id = r.team_id
CROSS JOIN LATERAL (VALUES
    ('Company', jsonb_build_object('type', 'EntityReference', 'value', jsonb_build_array(
        jsonb_build_object('entity_type', 'COMPANY', 'entity_id', r.company_id::text, 'specific_message_id', NULL)))),
    ('Stage', CASE WHEN r.stage_option IS NOT NULL THEN
        jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array(r.stage_option)) END),
    ('Owner', r.owner), ('Revenue', r.revenue)
) v(name, value)
WHERE c.name = v.name AND v.value IS NOT NULL AND v.value <> 'null'::jsonb;
DROP FUNCTION pg_temp.sales_uuid();