@fayz-ai/db 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,8 +31,9 @@ DECLARE
31
31
  -- 004 archetypes (self-governed via 004/006 policies)
32
32
  'people', 'categories', 'products', 'services', 'orders', 'order_items',
33
33
  'transactions', 'appointments', 'appointment_items', 'schedules',
34
- -- core, non-API helper tables
35
- 'sequences', 'documents', 'fayz_migration_ledger'
34
+ -- core, non-API helper tables (both ledger names kept for pre/post-rename compat;
35
+ -- `_migrations` is also covered by the NOT LIKE '\_%' filter below)
36
+ 'sequences', 'documents', 'fayz_migration_ledger', '_migrations'
36
37
  ];
37
38
  BEGIN
38
39
  FOR t IN
@@ -8,9 +8,15 @@
8
8
  -- service_role only: no anon/authenticated grants, RLS enabled with NO
9
9
  -- policies, so PostgREST (anon/authenticated) is deny-all. Only the service
10
10
  -- role (which bypasses RLS) — i.e. the runner — can read/write it.
11
+ --
12
+ -- Naming: the ledger is an internal, non-API table, so it uses the `_`-prefixed
13
+ -- `public._migrations` name (excluded from the project_rls auto-policy pass by
14
+ -- the `NOT LIKE '\_%'` filter). Legacy pools provisioned as `fayz_migration_ledger`
15
+ -- are migrated by 012_rename_migration_ledger.sql (and by the runner's
16
+ -- ensureLedger guard); fresh installs are born as `_migrations` here.
11
17
  -- ============================================================================
12
18
 
13
- CREATE TABLE IF NOT EXISTS public.fayz_migration_ledger (
19
+ CREATE TABLE IF NOT EXISTS public._migrations (
14
20
  id bigserial PRIMARY KEY,
15
21
  plugin_id text NOT NULL,
16
22
  file_name text NOT NULL,
@@ -21,10 +27,10 @@ CREATE TABLE IF NOT EXISTS public.fayz_migration_ledger (
21
27
  UNIQUE(plugin_id, file_name)
22
28
  );
23
29
 
24
- ALTER TABLE public.fayz_migration_ledger ENABLE ROW LEVEL SECURITY;
30
+ ALTER TABLE public._migrations ENABLE ROW LEVEL SECURITY;
25
31
 
26
32
  -- Deny-all through PostgREST: revoke any inherited grants, grant to nobody but
27
33
  -- service_role (which bypasses RLS anyway). No policies = no anon/authenticated access.
28
- REVOKE ALL ON public.fayz_migration_ledger FROM anon, authenticated;
29
- GRANT ALL ON public.fayz_migration_ledger TO service_role;
30
- GRANT USAGE, SELECT ON SEQUENCE public.fayz_migration_ledger_id_seq TO service_role;
34
+ REVOKE ALL ON public._migrations FROM anon, authenticated;
35
+ GRANT ALL ON public._migrations TO service_role;
36
+ GRANT USAGE, SELECT ON SEQUENCE public._migrations_id_seq TO service_role;
@@ -0,0 +1,61 @@
1
+ -- ============================================================================
2
+ -- 012_rename_migration_ledger.sql — rename the migration ledger onto the
3
+ -- internal `_`-prefixed baseline name:
4
+ --
5
+ -- public.fayz_migration_ledger → public._migrations
6
+ --
7
+ -- Legacy-pool remediation ONLY: 010_migration_ledger.sql now creates `_migrations`
8
+ -- directly, so fresh installs never reach a rename branch. The runner's
9
+ -- ensureLedger (cli/src/lib/ledger.ts) performs the same guarded rename at the
10
+ -- START of every apply, so on a real pool the ledger is already `_migrations`
11
+ -- by the time this migration runs — this file is the declarative backstop.
12
+ --
13
+ -- Fully idempotent + guarded: each RENAME fires only when the old object exists
14
+ -- and the new one does not. A table RENAME preserves the rows (the applied-file
15
+ -- history MUST survive), plus RLS state, grants and constraints; re-assert the
16
+ -- deny-all grants afterwards to keep the baseline explicit.
17
+ -- ============================================================================
18
+
19
+ DO $$
20
+ BEGIN
21
+ -- Table (carries the applied-migration history — never drop + recreate).
22
+ IF to_regclass('public.fayz_migration_ledger') IS NOT NULL
23
+ AND to_regclass('public._migrations') IS NULL THEN
24
+ ALTER TABLE public.fayz_migration_ledger RENAME TO _migrations;
25
+ END IF;
26
+
27
+ -- bigserial owns fayz_migration_ledger_id_seq — a table rename does not move it.
28
+ IF to_regclass('public.fayz_migration_ledger_id_seq') IS NOT NULL
29
+ AND to_regclass('public._migrations_id_seq') IS NULL THEN
30
+ ALTER SEQUENCE public.fayz_migration_ledger_id_seq RENAME TO _migrations_id_seq;
31
+ END IF;
32
+
33
+ -- Named constraints are auto-named after the old table; rename for parity with
34
+ -- a fresh install. Guard on the new table existing so this is safe pre-rename.
35
+ IF to_regclass('public._migrations') IS NOT NULL THEN
36
+ IF EXISTS (SELECT 1 FROM pg_constraint
37
+ WHERE conname = 'fayz_migration_ledger_pkey'
38
+ AND conrelid = 'public._migrations'::regclass) THEN
39
+ ALTER TABLE public._migrations RENAME CONSTRAINT fayz_migration_ledger_pkey TO _migrations_pkey;
40
+ END IF;
41
+ IF EXISTS (SELECT 1 FROM pg_constraint
42
+ WHERE conname = 'fayz_migration_ledger_plugin_id_file_name_key'
43
+ AND conrelid = 'public._migrations'::regclass) THEN
44
+ ALTER TABLE public._migrations
45
+ RENAME CONSTRAINT fayz_migration_ledger_plugin_id_file_name_key
46
+ TO _migrations_plugin_id_file_name_key;
47
+ END IF;
48
+ END IF;
49
+ END $$;
50
+
51
+ -- Re-assert the deny-all posture (idempotent; RLS/grants survive a rename but the
52
+ -- baseline keeps this explicit so a manually-created ledger converges too).
53
+ DO $$
54
+ BEGIN
55
+ IF to_regclass('public._migrations') IS NOT NULL THEN
56
+ EXECUTE 'ALTER TABLE public._migrations ENABLE ROW LEVEL SECURITY';
57
+ EXECUTE 'REVOKE ALL ON public._migrations FROM anon, authenticated';
58
+ EXECUTE 'GRANT ALL ON public._migrations TO service_role';
59
+ EXECUTE 'GRANT USAGE, SELECT ON SEQUENCE public._migrations_id_seq TO service_role';
60
+ END IF;
61
+ END $$;
@@ -0,0 +1,22 @@
1
+ -- ============================================================================
2
+ -- 013_sequences_rls.sql — close the RLS drift on public.sequences.
3
+ --
4
+ -- public.sequences (the REC-/PAG- numbering counter, created by the financial
5
+ -- plugin's 004_order_to_cash.sql) shipped WITHOUT row-level security on a set of
6
+ -- pools. Baseline = RLS ON, deny-all (no policies), exactly like the salon pool:
7
+ -- the table is written ONLY through the SECURITY DEFINER function
8
+ -- public.next_sequence(), which runs as the table owner and so bypasses RLS.
9
+ -- With RLS on and no policy, the PostgREST anon/authenticated surface is deny-all,
10
+ -- so the counter can never be read or tampered with directly by a tenant.
11
+ --
12
+ -- Legacy-pool remediation: guarded so it is a no-op on pools that never enabled
13
+ -- Payments (sequences absent) and idempotent on pools already at RLS ON. Fresh
14
+ -- installs are born with RLS via the financial plugin's own 004_order_to_cash.sql.
15
+ --
16
+ -- NOTE: next_sequence() MUST be SECURITY DEFINER for the deny-all baseline to
17
+ -- keep working — it is called directly via PostgREST RPC by authenticated users
18
+ -- (plugins/plugin-financial/src/data/supabase.ts → createInvoice). That fix ships
19
+ -- in the financial plugin migration alongside this one.
20
+ -- ============================================================================
21
+
22
+ ALTER TABLE IF EXISTS public.sequences ENABLE ROW LEVEL SECURITY;
@@ -0,0 +1,28 @@
1
+ -- ============================================================================
2
+ -- 014_plan_entitlements.sql — plans carry machine-readable entitlements.
3
+ --
4
+ -- public.plans shipped with `features jsonb` as DISPLAY BULLETS only — nothing
5
+ -- in the pool encodes what a plan actually gates. Server-side enforcement (the
6
+ -- agent RPCs' role→plan→limit guard, and eventually RLS defense-in-depth)
7
+ -- needs the SAME `{features: {id: bool}, limits: {key: number}}` structure the
8
+ -- client resolves from `config.billing` (@fayz-ai/core PlanEntitlements; -1 =
9
+ -- unlimited, absent feature = allowed).
10
+ --
11
+ -- Writer: the app's plan catalog is code (billing.ts) → synced into this table
12
+ -- (transitionally by the app seed, then by the Fayz platform on
13
+ -- `fayz manifest sync` — the manifest carries billing.plans verbatim).
14
+ --
15
+ -- `hidden` retires the "qa-free-test plans visible on SubscriptionPage" debt:
16
+ -- QA/internal plans stay selectable by id but are never rendered.
17
+ --
18
+ -- Guarded + idempotent: no-op when the pool predates public.plans (legacy
19
+ -- saas_core pools run their app-local mirror of this ALTER instead).
20
+ -- ============================================================================
21
+
22
+ DO $$
23
+ BEGIN
24
+ IF to_regclass('public.plans') IS NOT NULL THEN
25
+ ALTER TABLE public.plans ADD COLUMN IF NOT EXISTS entitlements jsonb NOT NULL DEFAULT '{}'::jsonb;
26
+ ALTER TABLE public.plans ADD COLUMN IF NOT EXISTS hidden boolean NOT NULL DEFAULT false;
27
+ END IF;
28
+ END $$;
@@ -0,0 +1,108 @@
1
+ -- ============================================================================
2
+ -- 015_agent_guard.sql — the role→plan→limit gate for agent_* RPCs.
3
+ --
4
+ -- Every server-plane agent write RPC (agent_<domain>_<verb>) calls this FIRST.
5
+ -- It is the SQL mirror of the shared TS engine (@fayz-ai/core/access
6
+ -- resolveAccess/resolveLimit): role first (owner bypasses role, NOT plan;
7
+ -- `manage` satisfies any action; tenant_role_overrides win over role grants),
8
+ -- then plan feature gate (only explicit false denies), then the plan cap for
9
+ -- p_limit_key (absent / -1 = unlimited). The RPC counts its own domain rows
10
+ -- and passes p_used — the guard never runs dynamic SQL.
11
+ --
12
+ -- Returns NULL when allowed, or the AgentDenial jsonb mirror when denied:
13
+ -- {"allowed":false,"reason":"role"|"plan"|"limit",
14
+ -- "limit":{"key":..,"max":..,"used":..},"upgradeUrl":"/settings/subscription"}
15
+ -- A parity test on the app side runs the same scenarios through the TS engine
16
+ -- and through this function — divergence is a bug.
17
+ --
18
+ -- Permission ids use the `category.action` catalog form; grants live in
19
+ -- role_permissions (+ per-tenant tenant_role_overrides with granted boolean).
20
+ -- ============================================================================
21
+
22
+ CREATE OR REPLACE FUNCTION public.agent_guard(
23
+ p_tenant_id uuid,
24
+ p_actor_user_id uuid,
25
+ p_feature text,
26
+ p_action text,
27
+ p_limit_key text DEFAULT NULL,
28
+ p_used integer DEFAULT NULL,
29
+ p_n integer DEFAULT 1
30
+ ) RETURNS jsonb
31
+ LANGUAGE plpgsql STABLE SECURITY DEFINER
32
+ SET search_path = public
33
+ AS $$
34
+ DECLARE
35
+ v_role text;
36
+ v_has boolean;
37
+ v_override boolean;
38
+ v_plan_id text;
39
+ v_ent jsonb;
40
+ v_feature_flag jsonb;
41
+ v_cap numeric;
42
+ BEGIN
43
+ -- ── membership + role ────────────────────────────────────────────────────
44
+ SELECT tm.role INTO v_role
45
+ FROM tenant_members tm
46
+ WHERE tm.tenant_id = p_tenant_id AND tm.user_id = p_actor_user_id;
47
+ IF v_role IS NULL THEN
48
+ RETURN jsonb_build_object('allowed', false, 'reason', 'role',
49
+ 'upgradeUrl', '/settings/subscription');
50
+ END IF;
51
+
52
+ IF v_role <> 'owner' THEN
53
+ -- per-tenant override wins in BOTH directions (grant or deny)
54
+ SELECT tro.granted INTO v_override
55
+ FROM tenant_role_overrides tro
56
+ WHERE tro.tenant_id = p_tenant_id AND tro.role = v_role
57
+ AND tro.permission_id IN (p_feature || '.' || p_action, p_feature || '.manage')
58
+ ORDER BY (tro.permission_id = p_feature || '.' || p_action) DESC
59
+ LIMIT 1;
60
+
61
+ IF v_override IS NOT NULL THEN
62
+ v_has := v_override;
63
+ ELSE
64
+ SELECT EXISTS (
65
+ SELECT 1 FROM role_permissions rp
66
+ WHERE rp.role = v_role
67
+ AND rp.permission_id IN (p_feature || '.' || p_action, p_feature || '.manage')
68
+ ) INTO v_has;
69
+ END IF;
70
+
71
+ IF NOT v_has THEN
72
+ RETURN jsonb_build_object('allowed', false, 'reason', 'role',
73
+ 'upgradeUrl', '/settings/subscription');
74
+ END IF;
75
+ END IF;
76
+
77
+ -- ── plan feature gate (owner does NOT bypass) ────────────────────────────
78
+ SELECT t.plan INTO v_plan_id FROM tenants t WHERE t.id = p_tenant_id;
79
+ SELECT p.entitlements INTO v_ent FROM plans p WHERE p.id = v_plan_id;
80
+
81
+ IF v_ent IS NOT NULL THEN
82
+ v_feature_flag := v_ent->'features'->p_feature;
83
+ -- only an EXPLICIT false denies (additive plans — mirror isEntitledByPlan)
84
+ IF v_feature_flag IS NOT NULL AND v_feature_flag = to_jsonb(false) THEN
85
+ RETURN jsonb_build_object('allowed', false, 'reason', 'plan',
86
+ 'upgradeUrl', '/settings/subscription');
87
+ END IF;
88
+
89
+ -- ── plan cap (mirror resolveLimit: absent / -1 = unlimited) ────────────
90
+ IF p_limit_key IS NOT NULL AND p_used IS NOT NULL THEN
91
+ v_cap := (v_ent->'limits'->>p_limit_key)::numeric;
92
+ IF v_cap IS NOT NULL AND v_cap <> -1 AND (p_used + COALESCE(p_n, 1)) > v_cap THEN
93
+ RETURN jsonb_build_object('allowed', false, 'reason', 'limit',
94
+ 'limit', jsonb_build_object('key', p_limit_key,
95
+ 'max', v_cap,
96
+ 'used', p_used),
97
+ 'upgradeUrl', '/settings/subscription');
98
+ END IF;
99
+ END IF;
100
+ END IF;
101
+
102
+ RETURN NULL; -- allowed
103
+ END;
104
+ $$;
105
+
106
+ REVOKE ALL ON FUNCTION public.agent_guard(uuid, uuid, text, text, text, integer, integer) FROM public;
107
+ GRANT EXECUTE ON FUNCTION public.agent_guard(uuid, uuid, text, text, text, integer, integer)
108
+ TO authenticated, service_role;
@@ -0,0 +1,102 @@
1
+ -- ============================================================================
2
+ -- 016_agent_guard_actor.sql — the actor cannot be spoofed by a signed-in caller.
3
+ --
4
+ -- agent_* RPCs receive p_actor_user_id explicitly because the Fayz broker
5
+ -- (service_role, no JWT) injects the verified actor server-side. But the same
6
+ -- functions are EXECUTE-granted to `authenticated` so the surface can call
7
+ -- them client-plane before S4 — and there, p_actor comes from the client. A
8
+ -- signed-in user passing SOMEONE ELSE's id would borrow their role.
9
+ --
10
+ -- Rule added at the top of agent_guard (every write RPC's first call): when
11
+ -- the caller carries a JWT identity (auth.uid() not null), p_actor MUST be
12
+ -- that identity. Service-role/broker calls (auth.uid() null) are unaffected.
13
+ -- New file rather than editing 015 — applied migrations are never edited
14
+ -- (ledger rule); CREATE OR REPLACE supersedes the body.
15
+ -- ============================================================================
16
+
17
+ CREATE OR REPLACE FUNCTION public.agent_guard(
18
+ p_tenant_id uuid,
19
+ p_actor_user_id uuid,
20
+ p_feature text,
21
+ p_action text,
22
+ p_limit_key text DEFAULT NULL,
23
+ p_used integer DEFAULT NULL,
24
+ p_n integer DEFAULT 1
25
+ ) RETURNS jsonb
26
+ LANGUAGE plpgsql STABLE SECURITY DEFINER
27
+ SET search_path = public
28
+ AS $$
29
+ DECLARE
30
+ v_role text;
31
+ v_has boolean;
32
+ v_override boolean;
33
+ v_plan_id text;
34
+ v_ent jsonb;
35
+ v_feature_flag jsonb;
36
+ v_cap numeric;
37
+ BEGIN
38
+ -- ── actor integrity: a JWT caller can only act as themselves ─────────────
39
+ IF auth.uid() IS NOT NULL AND auth.uid() IS DISTINCT FROM p_actor_user_id THEN
40
+ RETURN jsonb_build_object('allowed', false, 'reason', 'role',
41
+ 'upgradeUrl', '/settings/subscription');
42
+ END IF;
43
+
44
+ -- ── membership + role ────────────────────────────────────────────────────
45
+ SELECT tm.role INTO v_role
46
+ FROM tenant_members tm
47
+ WHERE tm.tenant_id = p_tenant_id AND tm.user_id = p_actor_user_id;
48
+ IF v_role IS NULL THEN
49
+ RETURN jsonb_build_object('allowed', false, 'reason', 'role',
50
+ 'upgradeUrl', '/settings/subscription');
51
+ END IF;
52
+
53
+ IF v_role <> 'owner' THEN
54
+ SELECT tro.granted INTO v_override
55
+ FROM tenant_role_overrides tro
56
+ WHERE tro.tenant_id = p_tenant_id AND tro.role = v_role
57
+ AND tro.permission_id IN (p_feature || '.' || p_action, p_feature || '.manage')
58
+ ORDER BY (tro.permission_id = p_feature || '.' || p_action) DESC
59
+ LIMIT 1;
60
+
61
+ IF v_override IS NOT NULL THEN
62
+ v_has := v_override;
63
+ ELSE
64
+ SELECT EXISTS (
65
+ SELECT 1 FROM role_permissions rp
66
+ WHERE rp.role = v_role
67
+ AND rp.permission_id IN (p_feature || '.' || p_action, p_feature || '.manage')
68
+ ) INTO v_has;
69
+ END IF;
70
+
71
+ IF NOT v_has THEN
72
+ RETURN jsonb_build_object('allowed', false, 'reason', 'role',
73
+ 'upgradeUrl', '/settings/subscription');
74
+ END IF;
75
+ END IF;
76
+
77
+ -- ── plan feature gate (owner does NOT bypass) ────────────────────────────
78
+ SELECT t.plan INTO v_plan_id FROM tenants t WHERE t.id = p_tenant_id;
79
+ SELECT p.entitlements INTO v_ent FROM plans p WHERE p.id = v_plan_id;
80
+
81
+ IF v_ent IS NOT NULL THEN
82
+ v_feature_flag := v_ent->'features'->p_feature;
83
+ IF v_feature_flag IS NOT NULL AND v_feature_flag = to_jsonb(false) THEN
84
+ RETURN jsonb_build_object('allowed', false, 'reason', 'plan',
85
+ 'upgradeUrl', '/settings/subscription');
86
+ END IF;
87
+
88
+ IF p_limit_key IS NOT NULL AND p_used IS NOT NULL THEN
89
+ v_cap := (v_ent->'limits'->>p_limit_key)::numeric;
90
+ IF v_cap IS NOT NULL AND v_cap <> -1 AND (p_used + COALESCE(p_n, 1)) > v_cap THEN
91
+ RETURN jsonb_build_object('allowed', false, 'reason', 'limit',
92
+ 'limit', jsonb_build_object('key', p_limit_key,
93
+ 'max', v_cap,
94
+ 'used', p_used),
95
+ 'upgradeUrl', '/settings/subscription');
96
+ END IF;
97
+ END IF;
98
+ END IF;
99
+
100
+ RETURN NULL;
101
+ END;
102
+ $$;
@@ -0,0 +1,115 @@
1
+ -- ============================================================================
2
+ -- 017_core_addresses.sql — public.addresses becomes part of the SPINE.
3
+ -- ----------------------------------------------------------------------------
4
+ -- The address book was already declared "core" by @fayz-ai/shop's 0012
5
+ -- ("move address/payment concepts OUT of the plugin, into core"), but the SQL
6
+ -- physically shipped inside the shop package. Consequence, live today: any app
7
+ -- that does not install @fayz-ai/shop has no addresses table, while the person
8
+ -- archetype's "Endereços" tab (packages/saas AddressesTab) queries it
9
+ -- unconditionally — beauty-saas, dentist-saas, agency-os and every other
10
+ -- non-shop vertical render "Could not find the table 'public.addresses'".
11
+ --
12
+ -- An address is not e-commerce. It is where a client is delivered to, where a
13
+ -- supplier is collected from, where a staff member lives, where a unit of the
14
+ -- business sits. It belongs beside `people` and `locations`, in the spine.
15
+ --
16
+ -- Replay safety (this file runs on pools that already have the table, via shop
17
+ -- 0012, AND on pools that have never seen it):
18
+ -- • CREATE TABLE IF NOT EXISTS + ADD COLUMN IF NOT EXISTS — additive only
19
+ -- • the owner_type CHECK is dropped and rebuilt WIDER, never narrower, so a
20
+ -- pool holding 'shop_customer' rows keeps them valid
21
+ -- • no DROP of data, no DROP of the shop's own policies
22
+ -- Ordering: the spine runs BEFORE plugin migrations (cli buildMigrationPlan
23
+ -- ① spine → ④ plugin), so on a fresh shop pool this file creates the table and
24
+ -- shop 0012's own CREATE ... IF NOT EXISTS degrades to a no-op.
25
+ --
26
+ -- `owner_type` stays text rather than a FK because the owner is polymorphic:
27
+ -- a core `people` row, a `locations` row, the tenant itself, or — until the
28
+ -- shop's customer table is folded into `people` — a plg_shop_customers row.
29
+ -- ============================================================================
30
+
31
+ -- ----------------------------------------------------------------------------
32
+ -- 1. The table
33
+ -- ----------------------------------------------------------------------------
34
+ CREATE TABLE IF NOT EXISTS public.addresses (
35
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
36
+ tenant_id uuid NOT NULL,
37
+ owner_type text NOT NULL DEFAULT 'person',
38
+ owner_id uuid,
39
+ kind text NOT NULL DEFAULT 'both',
40
+ label text, -- "Casa", "Trabalho", "Depósito"
41
+ recipient text, -- quem recebe, se não for o próprio dono
42
+ phone text,
43
+ postal_code text NOT NULL, -- CEP
44
+ street text NOT NULL,
45
+ number text,
46
+ complement text,
47
+ district text, -- bairro
48
+ city text NOT NULL,
49
+ state text NOT NULL, -- UF
50
+ country text NOT NULL DEFAULT 'BR',
51
+ is_default boolean NOT NULL DEFAULT false,
52
+ metadata jsonb NOT NULL DEFAULT '{}',
53
+ created_at timestamptz NOT NULL DEFAULT now(),
54
+ updated_at timestamptz NOT NULL DEFAULT now()
55
+ );
56
+
57
+ COMMENT ON TABLE public.addresses IS
58
+ 'Core address book. N addresses per owner (person, location, tenant), tenant-scoped. Owned by @fayz-ai/db — plugins read it, none of them own it.';
59
+
60
+ -- Pools provisioned by shop 0012 predate `metadata`/'both' defaults; add what
61
+ -- is missing rather than assuming the 0012 shape.
62
+ ALTER TABLE public.addresses
63
+ ADD COLUMN IF NOT EXISTS owner_type text NOT NULL DEFAULT 'person',
64
+ ADD COLUMN IF NOT EXISTS owner_id uuid,
65
+ ADD COLUMN IF NOT EXISTS kind text NOT NULL DEFAULT 'both',
66
+ ADD COLUMN IF NOT EXISTS label text,
67
+ ADD COLUMN IF NOT EXISTS recipient text,
68
+ ADD COLUMN IF NOT EXISTS phone text,
69
+ ADD COLUMN IF NOT EXISTS number text,
70
+ ADD COLUMN IF NOT EXISTS complement text,
71
+ ADD COLUMN IF NOT EXISTS district text,
72
+ ADD COLUMN IF NOT EXISTS metadata jsonb NOT NULL DEFAULT '{}';
73
+
74
+ -- ----------------------------------------------------------------------------
75
+ -- 2. Constraints — rebuilt WIDER than shop 0012's.
76
+ -- 'staff' and 'partner' are person kinds and already covered by 'person';
77
+ -- what 0012 lacked is nothing — this only re-asserts the same set so a pool
78
+ -- that never ran 0012 gets it, and a pool that did is left unchanged.
79
+ -- ----------------------------------------------------------------------------
80
+ ALTER TABLE public.addresses DROP CONSTRAINT IF EXISTS addresses_owner_type_check;
81
+ ALTER TABLE public.addresses
82
+ ADD CONSTRAINT addresses_owner_type_check
83
+ CHECK (owner_type IN ('person', 'shop_customer', 'location', 'tenant'));
84
+
85
+ ALTER TABLE public.addresses DROP CONSTRAINT IF EXISTS addresses_kind_check;
86
+ ALTER TABLE public.addresses
87
+ ADD CONSTRAINT addresses_kind_check
88
+ CHECK (kind IN ('shipping', 'billing', 'both'));
89
+
90
+ CREATE INDEX IF NOT EXISTS addresses_tenant_idx ON public.addresses (tenant_id);
91
+ CREATE INDEX IF NOT EXISTS addresses_owner_idx ON public.addresses (owner_type, owner_id);
92
+ -- One default per owner per kind, enforced here rather than trusting every
93
+ -- caller to clear the previous one.
94
+ CREATE UNIQUE INDEX IF NOT EXISTS addresses_one_default_idx
95
+ ON public.addresses (owner_type, owner_id, kind) WHERE is_default;
96
+
97
+ DROP TRIGGER IF EXISTS addresses_updated_at ON public.addresses;
98
+ CREATE TRIGGER addresses_updated_at BEFORE UPDATE ON public.addresses
99
+ FOR EACH ROW EXECUTE FUNCTION public.handle_updated_at();
100
+
101
+ -- ----------------------------------------------------------------------------
102
+ -- 3. RLS — tenant members manage their tenant's rows. Anon gets nothing.
103
+ -- The shop's extra `addresses_self_read` policy (a signed-in storefront
104
+ -- customer reading their own rows) is left untouched: it is additive, and
105
+ -- shop 0012 runs after this file.
106
+ -- ----------------------------------------------------------------------------
107
+ ALTER TABLE public.addresses ENABLE ROW LEVEL SECURITY;
108
+
109
+ DROP POLICY IF EXISTS "addresses_member_all" ON public.addresses;
110
+ CREATE POLICY "addresses_member_all" ON public.addresses FOR ALL TO authenticated
111
+ USING (tenant_id IN (SELECT public.user_tenant_ids()))
112
+ WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()));
113
+
114
+ GRANT ALL ON public.addresses TO authenticated, service_role;
115
+ REVOKE ALL ON public.addresses FROM anon;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "fayz": {
4
4
  "status": "beta"
5
5
  },
6
- "version": "0.8.0",
6
+ "version": "0.8.1",
7
7
  "description": "Fayz SDK database layer — Drizzle schema primitives, spine references, and migration helpers shared across plugins.",
8
8
  "type": "module",
9
9
  "main": "./dist/index.cjs",