@fayz-ai/plugin-support 0.2.12 → 0.2.14

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.
@@ -0,0 +1,529 @@
1
+ // src/migrations/index.ts
2
+ var MIGRATION_000_BASELINE = `-- plugin-support \u2014 Central de Suporte do Dico: the solicita\xE7\xF5es a tenant files
3
+ -- (problem / improvement / other), their conversation, history, attachments and
4
+ -- the "esperando voc\xEA" notifications. Port of the V1 support_* family.
5
+ --
6
+ -- Idempotent. Canonical RLS form: tenant_id IN (SELECT public.user_tenant_ids()).
7
+ -- "Minhas vs Toda a empresa" is a query-layer filter on created_by, gated by the
8
+ -- support.all feature \u2014 not an RLS distinction (the fleet has no SQL permission
9
+ -- helper, and the cross-member triage read is the 2nd wave with the platform bridge).
10
+
11
+ SET check_function_bodies = false;
12
+
13
+ -- \u2500\u2500 tables \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
14
+
15
+ -- The request itself. Carries, unseen by the person, the screen it was filed
16
+ -- from (route, active unit, a snapshot of what was visible) \u2014 triage reads it first.
17
+ CREATE TABLE IF NOT EXISTS public.plg_support_requests (
18
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
19
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
20
+ number integer NOT NULL, -- per-tenant sequential #; filled by trigger
21
+ kind text NOT NULL, -- problem | improvement | other
22
+ subject text, -- optional; derived from first line when blank
23
+ description text NOT NULL,
24
+ status text NOT NULL DEFAULT 'received', -- received|in_service|waiting_you|in_development|resolved_check|closed|cancelled
25
+ route text, -- origin screen hash path
26
+ unit_id uuid, -- active unit when filed (informational snapshot, no FK)
27
+ screen_snapshot jsonb NOT NULL DEFAULT '{}'::jsonb,
28
+ origin_conversation_id uuid, -- the Dico chat that spawned it, when any
29
+ area text,
30
+ created_by uuid NOT NULL DEFAULT auth.uid(), -- auth user; the owner of "Minhas". Default so the client cannot spoof it.
31
+ created_at timestamptz NOT NULL DEFAULT now(),
32
+ updated_at timestamptz NOT NULL DEFAULT now(),
33
+ resolved_at timestamptz,
34
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb
35
+ );
36
+ ALTER TABLE public.plg_support_requests ENABLE ROW LEVEL SECURITY;
37
+ CREATE INDEX IF NOT EXISTS idx_plg_support_requests_tenant ON public.plg_support_requests(tenant_id);
38
+ CREATE INDEX IF NOT EXISTS idx_plg_support_requests_tenant_created_by ON public.plg_support_requests(tenant_id, created_by);
39
+ CREATE INDEX IF NOT EXISTS idx_plg_support_requests_tenant_status ON public.plg_support_requests(tenant_id, status);
40
+ CREATE UNIQUE INDEX IF NOT EXISTS uq_plg_support_requests_tenant_number ON public.plg_support_requests(tenant_id, number);
41
+
42
+ -- The conversation inside the request ("Escreva para a equipe\u2026").
43
+ CREATE TABLE IF NOT EXISTS public.plg_support_request_messages (
44
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
45
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
46
+ request_id uuid NOT NULL REFERENCES public.plg_support_requests(id) ON DELETE CASCADE,
47
+ author_kind text NOT NULL DEFAULT 'user', -- user | team
48
+ author_id uuid DEFAULT auth.uid(),
49
+ body text NOT NULL,
50
+ created_at timestamptz NOT NULL DEFAULT now()
51
+ );
52
+ ALTER TABLE public.plg_support_request_messages ENABLE ROW LEVEL SECURITY;
53
+ CREATE INDEX IF NOT EXISTS idx_plg_support_request_messages_tenant ON public.plg_support_request_messages(tenant_id);
54
+ CREATE INDEX IF NOT EXISTS idx_plg_support_request_messages_request ON public.plg_support_request_messages(request_id, created_at);
55
+
56
+ -- The short-sentence history shown in the detail ("Solicita\xE7\xE3o aberta", "Andamento: Cancelada").
57
+ CREATE TABLE IF NOT EXISTS public.plg_support_request_events (
58
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
59
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
60
+ request_id uuid NOT NULL REFERENCES public.plg_support_requests(id) ON DELETE CASCADE,
61
+ type text NOT NULL, -- opened|status_changed|validated_ok|reopened|cancelled|closed_no_reply|merged
62
+ note text,
63
+ created_at timestamptz NOT NULL DEFAULT now()
64
+ );
65
+ ALTER TABLE public.plg_support_request_events ENABLE ROW LEVEL SECURITY;
66
+ CREATE INDEX IF NOT EXISTS idx_plg_support_request_events_tenant ON public.plg_support_request_events(tenant_id);
67
+ CREATE INDEX IF NOT EXISTS idx_plg_support_request_events_request ON public.plg_support_request_events(request_id, created_at);
68
+
69
+ -- Attachment pointers; the file itself lives in the support-attachments bucket.
70
+ CREATE TABLE IF NOT EXISTS public.plg_support_request_attachments (
71
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
72
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
73
+ request_id uuid NOT NULL REFERENCES public.plg_support_requests(id) ON DELETE CASCADE,
74
+ storage_path text NOT NULL, -- <tenant_id>/<request_id>/<uuid>/<name>
75
+ name text NOT NULL,
76
+ size_bytes bigint,
77
+ content_type text,
78
+ created_by uuid DEFAULT auth.uid(),
79
+ created_at timestamptz NOT NULL DEFAULT now()
80
+ );
81
+ ALTER TABLE public.plg_support_request_attachments ENABLE ROW LEVEL SECURITY;
82
+ CREATE INDEX IF NOT EXISTS idx_plg_support_request_attachments_tenant ON public.plg_support_request_attachments(tenant_id);
83
+ CREATE INDEX IF NOT EXISTS idx_plg_support_request_attachments_request ON public.plg_support_request_attachments(request_id);
84
+
85
+ -- The orange "Esperando voc\xEA" counter and the bell notice when the team replies.
86
+ CREATE TABLE IF NOT EXISTS public.plg_support_notifications (
87
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
88
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
89
+ request_id uuid NOT NULL REFERENCES public.plg_support_requests(id) ON DELETE CASCADE,
90
+ user_id uuid NOT NULL, -- who should see it
91
+ kind text, -- reply | resolved | waiting_you
92
+ read_at timestamptz, -- NULL = unread (counts in the orange badge)
93
+ created_at timestamptz NOT NULL DEFAULT now()
94
+ );
95
+ ALTER TABLE public.plg_support_notifications ENABLE ROW LEVEL SECURITY;
96
+ CREATE INDEX IF NOT EXISTS idx_plg_support_notifications_tenant ON public.plg_support_notifications(tenant_id);
97
+ CREATE INDEX IF NOT EXISTS idx_plg_support_notifications_user_unread ON public.plg_support_notifications(tenant_id, user_id, read_at);
98
+
99
+ -- \u2500\u2500 per-tenant sequential number \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
100
+ -- Each account counts its requests from #1. The advisory lock serialises the
101
+ -- read-then-write per tenant so two concurrent opens don't collide on the number.
102
+ CREATE OR REPLACE FUNCTION public.plg_support_assign_number()
103
+ RETURNS trigger
104
+ LANGUAGE plpgsql
105
+ AS $fn$
106
+ BEGIN
107
+ IF NEW.number IS NULL OR NEW.number = 0 THEN
108
+ PERFORM pg_advisory_xact_lock(hashtextextended('plg_support_requests:' || NEW.tenant_id::text, 0));
109
+ SELECT COALESCE(MAX(number), 0) + 1 INTO NEW.number
110
+ FROM public.plg_support_requests
111
+ WHERE tenant_id = NEW.tenant_id;
112
+ END IF;
113
+ RETURN NEW;
114
+ END;
115
+ $fn$;
116
+
117
+ DROP TRIGGER IF EXISTS trg_plg_support_assign_number ON public.plg_support_requests;
118
+ CREATE TRIGGER trg_plg_support_assign_number
119
+ BEFORE INSERT ON public.plg_support_requests
120
+ FOR EACH ROW EXECUTE FUNCTION public.plg_support_assign_number();
121
+
122
+ -- \u2500\u2500 touch updated_at \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
123
+ CREATE OR REPLACE FUNCTION public.plg_support_touch_updated_at()
124
+ RETURNS trigger
125
+ LANGUAGE plpgsql
126
+ AS $fn$
127
+ BEGIN
128
+ NEW.updated_at := now();
129
+ RETURN NEW;
130
+ END;
131
+ $fn$;
132
+
133
+ DROP TRIGGER IF EXISTS trg_plg_support_requests_touch ON public.plg_support_requests;
134
+ CREATE TRIGGER trg_plg_support_requests_touch
135
+ BEFORE UPDATE ON public.plg_support_requests
136
+ FOR EACH ROW EXECUTE FUNCTION public.plg_support_touch_updated_at();
137
+
138
+ -- \u2500\u2500 row security + grants (idempotent) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
139
+ DO $rls$
140
+ DECLARE t text;
141
+ BEGIN
142
+ FOR t IN SELECT unnest(ARRAY[
143
+ 'plg_support_requests',
144
+ 'plg_support_request_messages',
145
+ 'plg_support_request_events',
146
+ 'plg_support_request_attachments',
147
+ 'plg_support_notifications'
148
+ ])
149
+ LOOP
150
+ EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);
151
+ EXECUTE format('GRANT ALL ON public.%I TO authenticated', t);
152
+ EXECUTE format('GRANT ALL ON public.%I TO service_role', t);
153
+ BEGIN
154
+ EXECUTE format('GRANT MAINTAIN ON public.%I TO anon', t);
155
+ EXCEPTION WHEN insufficient_privilege OR undefined_object OR feature_not_supported THEN
156
+ RAISE NOTICE 'plg_support: skipped GRANT MAINTAIN on % (% )', t, SQLERRM;
157
+ END;
158
+ IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_select') THEN
159
+ EXECUTE format('CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_select', t);
160
+ END IF;
161
+ IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_insert') THEN
162
+ EXECUTE format('CREATE POLICY %I ON public.%I FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_insert', t);
163
+ END IF;
164
+ IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_update') THEN
165
+ EXECUTE format('CREATE POLICY %I ON public.%I FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_update', t);
166
+ END IF;
167
+ IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_delete') THEN
168
+ EXECUTE format('CREATE POLICY %I ON public.%I FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_delete', t);
169
+ END IF;
170
+ END LOOP;
171
+ END $rls$;
172
+
173
+ -- \u2500\u2500 attachments bucket (private; read by tenant folder) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
174
+ -- Path convention: <tenant_id>/<request_id>/<uuid>/<name>. A captura de tela
175
+ -- pode ter nome e valor de cliente borrados mas ainda sens\xEDvel \u2014 bucket privado,
176
+ -- servido por URL assinada de curta dura\xE7\xE3o; quem n\xE3o \xE9 do tenant n\xE3o alcan\xE7a.
177
+ INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
178
+ VALUES ('support-attachments', 'support-attachments', false, 20971520,
179
+ ARRAY['image/jpeg','image/png','image/webp','image/gif','application/pdf',
180
+ 'text/plain','text/csv','audio/mpeg','audio/webm','video/mp4','video/webm'])
181
+ ON CONFLICT (id) DO UPDATE SET
182
+ public = EXCLUDED.public,
183
+ file_size_limit = EXCLUDED.file_size_limit,
184
+ allowed_mime_types = EXCLUDED.allowed_mime_types;
185
+
186
+ DROP POLICY IF EXISTS plg_support_attachments_read ON storage.objects;
187
+ DROP POLICY IF EXISTS plg_support_attachments_insert ON storage.objects;
188
+ DROP POLICY IF EXISTS plg_support_attachments_update ON storage.objects;
189
+ DROP POLICY IF EXISTS plg_support_attachments_delete ON storage.objects;
190
+
191
+ CREATE POLICY plg_support_attachments_read ON storage.objects
192
+ FOR SELECT TO authenticated
193
+ USING (bucket_id = 'support-attachments'
194
+ AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text));
195
+
196
+ CREATE POLICY plg_support_attachments_insert ON storage.objects
197
+ FOR INSERT TO authenticated
198
+ WITH CHECK (bucket_id = 'support-attachments'
199
+ AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text));
200
+
201
+ CREATE POLICY plg_support_attachments_update ON storage.objects
202
+ FOR UPDATE TO authenticated
203
+ USING (bucket_id = 'support-attachments'
204
+ AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text))
205
+ WITH CHECK (bucket_id = 'support-attachments'
206
+ AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text));
207
+
208
+ CREATE POLICY plg_support_attachments_delete ON storage.objects
209
+ FOR DELETE TO authenticated
210
+ USING (bucket_id = 'support-attachments'
211
+ AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text));
212
+ `;
213
+ var MIGRATION_001_HELPDESK = `-- plugin-support \u2014 2nd wave: the cross-tenant helpdesk the baseline foresaw
214
+ -- ("the cross-member triage read is the 2nd wave with the platform bridge").
215
+ --
216
+ -- GoControl is the helpdesk: a small ALLOW-LIST of operators reads and acts on
217
+ -- the support requests of EVERY tenant, through SECURITY DEFINER functions that
218
+ -- carry the tenant boundary themselves. The per-tenant RLS from the baseline is
219
+ -- untouched \u2014 a store still sees only its own requests. Only a seeded operator,
220
+ -- and only through these functions, crosses it.
221
+ --
222
+ -- Idempotent. Additive only (new columns, a new table, new functions).
223
+
224
+ SET check_function_bodies = false;
225
+
226
+ -- \u2500\u2500 new columns on the request \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
227
+ ALTER TABLE public.plg_support_requests
228
+ ADD COLUMN IF NOT EXISTS priority text NOT NULL DEFAULT 'normal'; -- low|normal|high|urgent
229
+ ALTER TABLE public.plg_support_requests
230
+ ADD COLUMN IF NOT EXISTS linked_lead_id uuid; -- a CRM lead/client the operator tied to it
231
+ ALTER TABLE public.plg_support_requests
232
+ ADD COLUMN IF NOT EXISTS linked_lead_name text; -- denormalised: the operator's tenant, not the requester's
233
+
234
+ -- \u2500\u2500 who may operate the helpdesk \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
235
+ -- The allow-list is the whole security boundary of the cross-tenant read. A row
236
+ -- here is a GoControl support operator. Nobody writes this from the app; it is
237
+ -- seeded by an admin (see agent-provision / seed script).
238
+ CREATE TABLE IF NOT EXISTS public.plg_support_operators (
239
+ user_id uuid PRIMARY KEY,
240
+ note text,
241
+ created_at timestamptz NOT NULL DEFAULT now()
242
+ );
243
+ ALTER TABLE public.plg_support_operators ENABLE ROW LEVEL SECURITY;
244
+ GRANT SELECT ON public.plg_support_operators TO authenticated;
245
+ GRANT ALL ON public.plg_support_operators TO service_role;
246
+ -- A user may read ONLY their own row \u2014 enough to answer "am I an operator?" in
247
+ -- the UI, and it reveals no one else.
248
+ DROP POLICY IF EXISTS plg_support_operators_self ON public.plg_support_operators;
249
+ CREATE POLICY plg_support_operators_self ON public.plg_support_operators
250
+ FOR SELECT TO authenticated USING (user_id = auth.uid());
251
+
252
+ -- \u2500\u2500 gate \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
253
+ -- Operator = acting IN the helpdesk workspace. The caller's CURRENT tenant
254
+ -- (app.current_tenant_id \u2014 the workspace they have open) must be the one that
255
+ -- runs the helpdesk (support \`console\` facet active) AND they must be a member
256
+ -- of it. So the console is strictly per-WORKSPACE: it works only while you are
257
+ -- inside GoControl, never from a store, whoever you are. The plg_support_operators
258
+ -- allow-list stays as an explicit extra, but it too only counts while you are in
259
+ -- a helpdesk workspace \u2014 it never opens the console from a store.
260
+ CREATE OR REPLACE FUNCTION public.support_is_operator()
261
+ RETURNS boolean
262
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''
263
+ AS $fn$
264
+ SELECT EXISTS (
265
+ SELECT 1
266
+ FROM app.tenant_plugins tp
267
+ WHERE tp.plugin_id = 'support' AND tp.facet = 'console' AND tp.status = 'active'
268
+ AND tp.tenant_id = app.current_tenant_id()
269
+ AND (
270
+ EXISTS (
271
+ SELECT 1 FROM app.memberships m
272
+ WHERE m.tenant_id = tp.tenant_id AND m.user_id = auth.uid() AND m.active
273
+ )
274
+ OR EXISTS (SELECT 1 FROM public.plg_support_operators o WHERE o.user_id = auth.uid())
275
+ )
276
+ );
277
+ $fn$;
278
+ GRANT EXECUTE ON FUNCTION public.support_is_operator() TO authenticated;
279
+
280
+ -- A guard the write functions share \u2014 raises if the caller is not an operator.
281
+ CREATE OR REPLACE FUNCTION public.support_console_guard()
282
+ RETURNS void
283
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
284
+ AS $fn$
285
+ BEGIN
286
+ IF NOT public.support_is_operator() THEN
287
+ RAISE EXCEPTION 'not a support operator' USING ERRCODE = '42501';
288
+ END IF;
289
+ END;
290
+ $fn$;
291
+ GRANT EXECUTE ON FUNCTION public.support_console_guard() TO authenticated;
292
+
293
+ -- Resolve the auth user who opened a ticket to a human name: the person record
294
+ -- in that tenant, else the signed-up full name, else the e-mail. So the console
295
+ -- shows "Vini" instead of a uuid.
296
+ CREATE OR REPLACE FUNCTION public._support_user_name(p_user uuid, p_tenant uuid)
297
+ RETURNS text
298
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''
299
+ AS $fn$
300
+ SELECT COALESCE(
301
+ (SELECT NULLIF(btrim(p.name), '')
302
+ FROM app.memberships m JOIN public.people p ON p.id = m.person_id
303
+ WHERE m.user_id = p_user AND m.tenant_id = p_tenant LIMIT 1),
304
+ (SELECT NULLIF(btrim(u.raw_user_meta_data->>'full_name'), '') FROM auth.users u WHERE u.id = p_user),
305
+ (SELECT NULLIF(btrim(u.raw_user_meta_data->>'name'), '') FROM auth.users u WHERE u.id = p_user),
306
+ (SELECT u.email FROM auth.users u WHERE u.id = p_user)
307
+ );
308
+ $fn$;
309
+ GRANT EXECUTE ON FUNCTION public._support_user_name(uuid, uuid) TO authenticated;
310
+
311
+ -- \u2500\u2500 read: every tenant's requests, for an operator \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
312
+ CREATE OR REPLACE FUNCTION public.support_console_requests(
313
+ p_statuses text[] DEFAULT NULL,
314
+ p_search text DEFAULT NULL
315
+ )
316
+ RETURNS jsonb
317
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
318
+ AS $fn$
319
+ DECLARE result jsonb;
320
+ BEGIN
321
+ PERFORM public.support_console_guard();
322
+ SELECT COALESCE(jsonb_agg(row_to_json(r)), '[]'::jsonb) INTO result
323
+ FROM (
324
+ SELECT
325
+ q.id, q.number, q.kind, q.subject, q.description, q.status, q.priority,
326
+ q.route, q.created_by, public._support_user_name(q.created_by, q.tenant_id) AS created_by_name,
327
+ q.created_at, q.updated_at,
328
+ q.linked_lead_id, q.linked_lead_name,
329
+ q.tenant_id, t.name AS tenant_name, t.slug AS tenant_slug,
330
+ (SELECT count(*) FROM public.plg_support_request_messages m WHERE m.request_id = q.id) AS message_count
331
+ FROM public.plg_support_requests q
332
+ LEFT JOIN public.tenants t ON t.id = q.tenant_id
333
+ WHERE (p_statuses IS NULL OR q.status = ANY(p_statuses))
334
+ AND (p_search IS NULL OR p_search = ''
335
+ OR q.subject ILIKE '%'||p_search||'%'
336
+ OR q.description ILIKE '%'||p_search||'%'
337
+ OR t.name ILIKE '%'||p_search||'%')
338
+ ORDER BY
339
+ CASE q.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'normal' THEN 2 ELSE 3 END,
340
+ q.updated_at DESC
341
+ ) r;
342
+ RETURN result;
343
+ END;
344
+ $fn$;
345
+ GRANT EXECUTE ON FUNCTION public.support_console_requests(text[], text) TO authenticated;
346
+
347
+ -- \u2500\u2500 read: one request in full \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
348
+ CREATE OR REPLACE FUNCTION public.support_console_detail(p_request_id uuid)
349
+ RETURNS jsonb
350
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
351
+ AS $fn$
352
+ DECLARE result jsonb;
353
+ BEGIN
354
+ PERFORM public.support_console_guard();
355
+ SELECT jsonb_build_object(
356
+ 'request', (SELECT row_to_json(x) FROM (
357
+ SELECT q.*, t.name AS tenant_name, t.slug AS tenant_slug,
358
+ public._support_user_name(q.created_by, q.tenant_id) AS created_by_name
359
+ FROM public.plg_support_requests q
360
+ LEFT JOIN public.tenants t ON t.id = q.tenant_id
361
+ WHERE q.id = p_request_id) x),
362
+ 'messages', (SELECT COALESCE(jsonb_agg(row_to_json(m) ORDER BY m.created_at), '[]'::jsonb)
363
+ FROM public.plg_support_request_messages m WHERE m.request_id = p_request_id),
364
+ 'events', (SELECT COALESCE(jsonb_agg(row_to_json(e) ORDER BY e.created_at), '[]'::jsonb)
365
+ FROM public.plg_support_request_events e WHERE e.request_id = p_request_id),
366
+ 'attachments', (SELECT COALESCE(jsonb_agg(row_to_json(a) ORDER BY a.created_at), '[]'::jsonb)
367
+ FROM public.plg_support_request_attachments a WHERE a.request_id = p_request_id)
368
+ ) INTO result;
369
+ RETURN result;
370
+ END;
371
+ $fn$;
372
+ GRANT EXECUTE ON FUNCTION public.support_console_detail(uuid) TO authenticated;
373
+
374
+ -- Internal: drop one unread notice to the requester, in their own tenant.
375
+ CREATE OR REPLACE FUNCTION public._support_notify(p_request_id uuid, p_kind text)
376
+ RETURNS void
377
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
378
+ AS $fn$
379
+ DECLARE v_tenant uuid; v_user uuid;
380
+ BEGIN
381
+ SELECT tenant_id, created_by INTO v_tenant, v_user
382
+ FROM public.plg_support_requests WHERE id = p_request_id;
383
+ IF v_user IS NULL THEN RETURN; END IF;
384
+ INSERT INTO public.plg_support_notifications (tenant_id, request_id, user_id, kind)
385
+ VALUES (v_tenant, p_request_id, v_user, p_kind);
386
+ END;
387
+ $fn$;
388
+
389
+ -- \u2500\u2500 write: operator changes status (and the client hears about it) \u2500\u2500\u2500\u2500\u2500\u2500\u2500
390
+ CREATE OR REPLACE FUNCTION public.support_console_set_status(
391
+ p_request_id uuid, p_status text, p_note text DEFAULT NULL
392
+ )
393
+ RETURNS jsonb
394
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
395
+ AS $fn$
396
+ DECLARE v_tenant uuid;
397
+ BEGIN
398
+ PERFORM public.support_console_guard();
399
+ IF p_status NOT IN ('received','in_service','waiting_you','in_development','resolved_check','closed','cancelled') THEN
400
+ RAISE EXCEPTION 'invalid status %', p_status USING ERRCODE = '22023';
401
+ END IF;
402
+ SELECT tenant_id INTO v_tenant FROM public.plg_support_requests WHERE id = p_request_id;
403
+ IF v_tenant IS NULL THEN RAISE EXCEPTION 'request not found' USING ERRCODE = 'P0002'; END IF;
404
+ UPDATE public.plg_support_requests
405
+ SET status = p_status,
406
+ resolved_at = CASE WHEN p_status IN ('resolved_check','closed') THEN now() ELSE resolved_at END
407
+ WHERE id = p_request_id;
408
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note)
409
+ VALUES (v_tenant, p_request_id, 'status_changed', p_status);
410
+ PERFORM public._support_notify(p_request_id,
411
+ CASE WHEN p_status IN ('waiting_you','resolved_check') THEN 'waiting_you'
412
+ WHEN p_status IN ('closed') THEN 'resolved' ELSE 'reply' END);
413
+ RETURN public.support_console_detail(p_request_id);
414
+ END;
415
+ $fn$;
416
+ GRANT EXECUTE ON FUNCTION public.support_console_set_status(uuid, text, text) TO authenticated;
417
+
418
+ -- \u2500\u2500 write: operator sets priority \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
419
+ CREATE OR REPLACE FUNCTION public.support_console_set_priority(p_request_id uuid, p_priority text)
420
+ RETURNS jsonb
421
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
422
+ AS $fn$
423
+ BEGIN
424
+ PERFORM public.support_console_guard();
425
+ IF p_priority NOT IN ('low','normal','high','urgent') THEN
426
+ RAISE EXCEPTION 'invalid priority %', p_priority USING ERRCODE = '22023';
427
+ END IF;
428
+ UPDATE public.plg_support_requests SET priority = p_priority WHERE id = p_request_id;
429
+ RETURN public.support_console_detail(p_request_id);
430
+ END;
431
+ $fn$;
432
+ GRANT EXECUTE ON FUNCTION public.support_console_set_priority(uuid, text) TO authenticated;
433
+
434
+ -- \u2500\u2500 write: operator replies to the requester \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
435
+ CREATE OR REPLACE FUNCTION public.support_console_reply(p_request_id uuid, p_body text)
436
+ RETURNS jsonb
437
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
438
+ AS $fn$
439
+ DECLARE v_tenant uuid;
440
+ BEGIN
441
+ PERFORM public.support_console_guard();
442
+ IF p_body IS NULL OR btrim(p_body) = '' THEN RAISE EXCEPTION 'empty message' USING ERRCODE = '22023'; END IF;
443
+ SELECT tenant_id INTO v_tenant FROM public.plg_support_requests WHERE id = p_request_id;
444
+ IF v_tenant IS NULL THEN RAISE EXCEPTION 'request not found' USING ERRCODE = 'P0002'; END IF;
445
+ INSERT INTO public.plg_support_request_messages (tenant_id, request_id, author_kind, author_id, body)
446
+ VALUES (v_tenant, p_request_id, 'team', auth.uid(), btrim(p_body));
447
+ PERFORM public._support_notify(p_request_id, 'reply');
448
+ RETURN public.support_console_detail(p_request_id);
449
+ END;
450
+ $fn$;
451
+ GRANT EXECUTE ON FUNCTION public.support_console_reply(uuid, text) TO authenticated;
452
+
453
+ -- \u2500\u2500 write: operator links a CRM lead/client \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
454
+ CREATE OR REPLACE FUNCTION public.support_console_link_lead(
455
+ p_request_id uuid, p_lead_id uuid, p_lead_name text DEFAULT NULL
456
+ )
457
+ RETURNS jsonb
458
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
459
+ AS $fn$
460
+ BEGIN
461
+ PERFORM public.support_console_guard();
462
+ UPDATE public.plg_support_requests
463
+ SET linked_lead_id = p_lead_id, linked_lead_name = p_lead_name
464
+ WHERE id = p_request_id;
465
+ RETURN public.support_console_detail(p_request_id);
466
+ END;
467
+ $fn$;
468
+ GRANT EXECUTE ON FUNCTION public.support_console_link_lead(uuid, uuid, text) TO authenticated;
469
+ `;
470
+ var MIGRATION_002_OPERATOR_ATTACHMENT_READ = `-- plugin-support \u2014 let a helpdesk OPERATOR open a chamado's attachments.
471
+ -- Idempotent / replay-safe.
472
+ --
473
+ -- The bucket's read policy (000_baseline) scopes every object to its owning
474
+ -- tenant: (storage.foldername(name))[1] IN user_tenant_ids(). That is right for
475
+ -- the store, but the GoControl operator is in ANOTHER tenant, so the signed URL
476
+ -- never comes back and the console shows "anexo" instead of the image. This adds
477
+ -- a SECOND, permissive SELECT policy (RLS OR-combines them, so the tenant rule is
478
+ -- untouched) that lets an operator read any support-attachments object \u2014 gated by
479
+ -- the same support_is_operator() that guards the whole console. Read only: upload,
480
+ -- update and delete stay tenant-scoped.
481
+ DROP POLICY IF EXISTS plg_support_attachments_operator_read ON storage.objects;
482
+ CREATE POLICY plg_support_attachments_operator_read ON storage.objects
483
+ FOR SELECT TO authenticated
484
+ USING (bucket_id = 'support-attachments' AND public.support_is_operator());
485
+ `;
486
+ var MIGRATION_003_OPERATOR_ATTACHMENT_READ_FIX = `-- plugin-support \u2014 make the operator attachment policy actually work from Storage.
487
+ -- Idempotent / replay-safe.
488
+ --
489
+ -- 002 gated the operator read on support_is_operator(), which asks
490
+ -- app.current_tenant_id() \u2014 the OPEN workspace. That GUC is set on the normal
491
+ -- data API, but NOT on a Storage sign request, so inside the bucket policy it is
492
+ -- null and the check fails: the operator still got a 400 and saw "anexo".
493
+ --
494
+ -- This swaps to a context-independent test that leans only on auth.uid() (always
495
+ -- present from the JWT): the user is a seeded cross-tenant operator, OR an active
496
+ -- member of a tenant that runs the console (the facet). Same intent as
497
+ -- support_is_operator(), minus the current-workspace scoping that Storage cannot
498
+ -- answer. SECURITY DEFINER so the lookups bypass RLS, like the original.
499
+ CREATE OR REPLACE FUNCTION public.support_is_operator_global()
500
+ RETURNS boolean
501
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''
502
+ AS $fn$
503
+ SELECT
504
+ EXISTS (SELECT 1 FROM public.plg_support_operators o WHERE o.user_id = auth.uid())
505
+ OR EXISTS (
506
+ SELECT 1
507
+ FROM app.tenant_plugins tp
508
+ JOIN app.memberships m
509
+ ON m.tenant_id = tp.tenant_id AND m.user_id = auth.uid() AND m.active
510
+ WHERE tp.plugin_id = 'support' AND tp.facet = 'console' AND tp.status = 'active'
511
+ );
512
+ $fn$;
513
+ GRANT EXECUTE ON FUNCTION public.support_is_operator_global() TO authenticated;
514
+
515
+ DROP POLICY IF EXISTS plg_support_attachments_operator_read ON storage.objects;
516
+ CREATE POLICY plg_support_attachments_operator_read ON storage.objects
517
+ FOR SELECT TO authenticated
518
+ USING (bucket_id = 'support-attachments' AND public.support_is_operator_global());
519
+ `;
520
+ var MIGRATIONS = [
521
+ { id: "000_baseline", sql: MIGRATION_000_BASELINE },
522
+ { id: "001_helpdesk", sql: MIGRATION_001_HELPDESK },
523
+ { id: "002_operator_attachment_read", sql: MIGRATION_002_OPERATOR_ATTACHMENT_READ },
524
+ { id: "003_operator_attachment_read_fix", sql: MIGRATION_003_OPERATOR_ATTACHMENT_READ_FIX }
525
+ ];
526
+
527
+ export { MIGRATIONS, MIGRATION_000_BASELINE, MIGRATION_001_HELPDESK, MIGRATION_002_OPERATOR_ATTACHMENT_READ, MIGRATION_003_OPERATOR_ATTACHMENT_READ_FIX };
528
+ //# sourceMappingURL=main.js.map
529
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/migrations/index.ts"],"names":[],"mappings":";AAIO,IAAM,sBAAA,GAAyB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoN/B,IAAM,sBAAA,GAAyB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkQ/B,IAAM,sCAAA,GAAyC,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiB/C,IAAM,0CAAA,GAA6C,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAmCnD,IAAM,UAAA,GAAiD;AAAA,EAC5D,EAAE,EAAA,EAAI,cAAA,EAAgB,GAAA,EAAK,sBAAA,EAAuB;AAAA,EAClD,EAAE,EAAA,EAAI,cAAA,EAAgB,GAAA,EAAK,sBAAA,EAAuB;AAAA,EAClD,EAAE,EAAA,EAAI,8BAAA,EAAgC,GAAA,EAAK,sCAAA,EAAuC;AAAA,EAClF,EAAE,EAAA,EAAI,kCAAA,EAAoC,GAAA,EAAK,0CAAA;AACjD","file":"main.js","sourcesContent":["// AUTO-GENERATED from 000_baseline.sql, 001_helpdesk.sql, 002_operator_attachment_read.sql, 003_operator_attachment_read_fix.sql — regenerate with scripts/embed-migrations.mjs\n// SQL files are the source of truth; this inline copy lets the manifest declare\n// migrations as data. Do not edit by hand — run the embed script instead.\n\nexport const MIGRATION_000_BASELINE = `-- plugin-support — Central de Suporte do Dico: the solicitações a tenant files\n-- (problem / improvement / other), their conversation, history, attachments and\n-- the \"esperando você\" notifications. Port of the V1 support_* family.\n--\n-- Idempotent. Canonical RLS form: tenant_id IN (SELECT public.user_tenant_ids()).\n-- \"Minhas vs Toda a empresa\" is a query-layer filter on created_by, gated by the\n-- support.all feature — not an RLS distinction (the fleet has no SQL permission\n-- helper, and the cross-member triage read is the 2nd wave with the platform bridge).\n\nSET check_function_bodies = false;\n\n-- ── tables ──────────────────────────────────────────────────────────────\n\n-- The request itself. Carries, unseen by the person, the screen it was filed\n-- from (route, active unit, a snapshot of what was visible) — triage reads it first.\nCREATE TABLE IF NOT EXISTS public.plg_support_requests (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n number integer NOT NULL, -- per-tenant sequential #; filled by trigger\n kind text NOT NULL, -- problem | improvement | other\n subject text, -- optional; derived from first line when blank\n description text NOT NULL,\n status text NOT NULL DEFAULT 'received', -- received|in_service|waiting_you|in_development|resolved_check|closed|cancelled\n route text, -- origin screen hash path\n unit_id uuid, -- active unit when filed (informational snapshot, no FK)\n screen_snapshot jsonb NOT NULL DEFAULT '{}'::jsonb,\n origin_conversation_id uuid, -- the Dico chat that spawned it, when any\n area text,\n created_by uuid NOT NULL DEFAULT auth.uid(), -- auth user; the owner of \"Minhas\". Default so the client cannot spoof it.\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n resolved_at timestamptz,\n metadata jsonb NOT NULL DEFAULT '{}'::jsonb\n);\nALTER TABLE public.plg_support_requests ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_support_requests_tenant ON public.plg_support_requests(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_support_requests_tenant_created_by ON public.plg_support_requests(tenant_id, created_by);\nCREATE INDEX IF NOT EXISTS idx_plg_support_requests_tenant_status ON public.plg_support_requests(tenant_id, status);\nCREATE UNIQUE INDEX IF NOT EXISTS uq_plg_support_requests_tenant_number ON public.plg_support_requests(tenant_id, number);\n\n-- The conversation inside the request (\"Escreva para a equipe…\").\nCREATE TABLE IF NOT EXISTS public.plg_support_request_messages (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n request_id uuid NOT NULL REFERENCES public.plg_support_requests(id) ON DELETE CASCADE,\n author_kind text NOT NULL DEFAULT 'user', -- user | team\n author_id uuid DEFAULT auth.uid(),\n body text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_support_request_messages ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_support_request_messages_tenant ON public.plg_support_request_messages(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_support_request_messages_request ON public.plg_support_request_messages(request_id, created_at);\n\n-- The short-sentence history shown in the detail (\"Solicitação aberta\", \"Andamento: Cancelada\").\nCREATE TABLE IF NOT EXISTS public.plg_support_request_events (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n request_id uuid NOT NULL REFERENCES public.plg_support_requests(id) ON DELETE CASCADE,\n type text NOT NULL, -- opened|status_changed|validated_ok|reopened|cancelled|closed_no_reply|merged\n note text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_support_request_events ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_support_request_events_tenant ON public.plg_support_request_events(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_support_request_events_request ON public.plg_support_request_events(request_id, created_at);\n\n-- Attachment pointers; the file itself lives in the support-attachments bucket.\nCREATE TABLE IF NOT EXISTS public.plg_support_request_attachments (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n request_id uuid NOT NULL REFERENCES public.plg_support_requests(id) ON DELETE CASCADE,\n storage_path text NOT NULL, -- <tenant_id>/<request_id>/<uuid>/<name>\n name text NOT NULL,\n size_bytes bigint,\n content_type text,\n created_by uuid DEFAULT auth.uid(),\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_support_request_attachments ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_support_request_attachments_tenant ON public.plg_support_request_attachments(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_support_request_attachments_request ON public.plg_support_request_attachments(request_id);\n\n-- The orange \"Esperando você\" counter and the bell notice when the team replies.\nCREATE TABLE IF NOT EXISTS public.plg_support_notifications (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n request_id uuid NOT NULL REFERENCES public.plg_support_requests(id) ON DELETE CASCADE,\n user_id uuid NOT NULL, -- who should see it\n kind text, -- reply | resolved | waiting_you\n read_at timestamptz, -- NULL = unread (counts in the orange badge)\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_support_notifications ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_support_notifications_tenant ON public.plg_support_notifications(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_support_notifications_user_unread ON public.plg_support_notifications(tenant_id, user_id, read_at);\n\n-- ── per-tenant sequential number ────────────────────────────────────────\n-- Each account counts its requests from #1. The advisory lock serialises the\n-- read-then-write per tenant so two concurrent opens don't collide on the number.\nCREATE OR REPLACE FUNCTION public.plg_support_assign_number()\nRETURNS trigger\nLANGUAGE plpgsql\nAS $fn$\nBEGIN\n IF NEW.number IS NULL OR NEW.number = 0 THEN\n PERFORM pg_advisory_xact_lock(hashtextextended('plg_support_requests:' || NEW.tenant_id::text, 0));\n SELECT COALESCE(MAX(number), 0) + 1 INTO NEW.number\n FROM public.plg_support_requests\n WHERE tenant_id = NEW.tenant_id;\n END IF;\n RETURN NEW;\nEND;\n$fn$;\n\nDROP TRIGGER IF EXISTS trg_plg_support_assign_number ON public.plg_support_requests;\nCREATE TRIGGER trg_plg_support_assign_number\n BEFORE INSERT ON public.plg_support_requests\n FOR EACH ROW EXECUTE FUNCTION public.plg_support_assign_number();\n\n-- ── touch updated_at ────────────────────────────────────────────────────\nCREATE OR REPLACE FUNCTION public.plg_support_touch_updated_at()\nRETURNS trigger\nLANGUAGE plpgsql\nAS $fn$\nBEGIN\n NEW.updated_at := now();\n RETURN NEW;\nEND;\n$fn$;\n\nDROP TRIGGER IF EXISTS trg_plg_support_requests_touch ON public.plg_support_requests;\nCREATE TRIGGER trg_plg_support_requests_touch\n BEFORE UPDATE ON public.plg_support_requests\n FOR EACH ROW EXECUTE FUNCTION public.plg_support_touch_updated_at();\n\n-- ── row security + grants (idempotent) ──────────────────────────────────\nDO $rls$\nDECLARE t text;\nBEGIN\n FOR t IN SELECT unnest(ARRAY[\n 'plg_support_requests',\n 'plg_support_request_messages',\n 'plg_support_request_events',\n 'plg_support_request_attachments',\n 'plg_support_notifications'\n ])\n LOOP\n EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);\n EXECUTE format('GRANT ALL ON public.%I TO authenticated', t);\n EXECUTE format('GRANT ALL ON public.%I TO service_role', t);\n BEGIN\n EXECUTE format('GRANT MAINTAIN ON public.%I TO anon', t);\n EXCEPTION WHEN insufficient_privilege OR undefined_object OR feature_not_supported THEN\n RAISE NOTICE 'plg_support: skipped GRANT MAINTAIN on % (% )', t, SQLERRM;\n END;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_select') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_select', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_insert') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_insert', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_update') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_update', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_delete') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_delete', t);\n END IF;\n END LOOP;\nEND $rls$;\n\n-- ── attachments bucket (private; read by tenant folder) ─────────────────\n-- Path convention: <tenant_id>/<request_id>/<uuid>/<name>. A captura de tela\n-- pode ter nome e valor de cliente borrados mas ainda sensível — bucket privado,\n-- servido por URL assinada de curta duração; quem não é do tenant não alcança.\nINSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)\nVALUES ('support-attachments', 'support-attachments', false, 20971520,\n ARRAY['image/jpeg','image/png','image/webp','image/gif','application/pdf',\n 'text/plain','text/csv','audio/mpeg','audio/webm','video/mp4','video/webm'])\nON CONFLICT (id) DO UPDATE SET\n public = EXCLUDED.public,\n file_size_limit = EXCLUDED.file_size_limit,\n allowed_mime_types = EXCLUDED.allowed_mime_types;\n\nDROP POLICY IF EXISTS plg_support_attachments_read ON storage.objects;\nDROP POLICY IF EXISTS plg_support_attachments_insert ON storage.objects;\nDROP POLICY IF EXISTS plg_support_attachments_update ON storage.objects;\nDROP POLICY IF EXISTS plg_support_attachments_delete ON storage.objects;\n\nCREATE POLICY plg_support_attachments_read ON storage.objects\n FOR SELECT TO authenticated\n USING (bucket_id = 'support-attachments'\n AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text));\n\nCREATE POLICY plg_support_attachments_insert ON storage.objects\n FOR INSERT TO authenticated\n WITH CHECK (bucket_id = 'support-attachments'\n AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text));\n\nCREATE POLICY plg_support_attachments_update ON storage.objects\n FOR UPDATE TO authenticated\n USING (bucket_id = 'support-attachments'\n AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text))\n WITH CHECK (bucket_id = 'support-attachments'\n AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text));\n\nCREATE POLICY plg_support_attachments_delete ON storage.objects\n FOR DELETE TO authenticated\n USING (bucket_id = 'support-attachments'\n AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text));\n`\n\nexport const MIGRATION_001_HELPDESK = `-- plugin-support — 2nd wave: the cross-tenant helpdesk the baseline foresaw\n-- (\"the cross-member triage read is the 2nd wave with the platform bridge\").\n--\n-- GoControl is the helpdesk: a small ALLOW-LIST of operators reads and acts on\n-- the support requests of EVERY tenant, through SECURITY DEFINER functions that\n-- carry the tenant boundary themselves. The per-tenant RLS from the baseline is\n-- untouched — a store still sees only its own requests. Only a seeded operator,\n-- and only through these functions, crosses it.\n--\n-- Idempotent. Additive only (new columns, a new table, new functions).\n\nSET check_function_bodies = false;\n\n-- ── new columns on the request ───────────────────────────────────────────\nALTER TABLE public.plg_support_requests\n ADD COLUMN IF NOT EXISTS priority text NOT NULL DEFAULT 'normal'; -- low|normal|high|urgent\nALTER TABLE public.plg_support_requests\n ADD COLUMN IF NOT EXISTS linked_lead_id uuid; -- a CRM lead/client the operator tied to it\nALTER TABLE public.plg_support_requests\n ADD COLUMN IF NOT EXISTS linked_lead_name text; -- denormalised: the operator's tenant, not the requester's\n\n-- ── who may operate the helpdesk ─────────────────────────────────────────\n-- The allow-list is the whole security boundary of the cross-tenant read. A row\n-- here is a GoControl support operator. Nobody writes this from the app; it is\n-- seeded by an admin (see agent-provision / seed script).\nCREATE TABLE IF NOT EXISTS public.plg_support_operators (\n user_id uuid PRIMARY KEY,\n note text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_support_operators ENABLE ROW LEVEL SECURITY;\nGRANT SELECT ON public.plg_support_operators TO authenticated;\nGRANT ALL ON public.plg_support_operators TO service_role;\n-- A user may read ONLY their own row — enough to answer \"am I an operator?\" in\n-- the UI, and it reveals no one else.\nDROP POLICY IF EXISTS plg_support_operators_self ON public.plg_support_operators;\nCREATE POLICY plg_support_operators_self ON public.plg_support_operators\n FOR SELECT TO authenticated USING (user_id = auth.uid());\n\n-- ── gate ──────────────────────────────────────────────────────────────────\n-- Operator = acting IN the helpdesk workspace. The caller's CURRENT tenant\n-- (app.current_tenant_id — the workspace they have open) must be the one that\n-- runs the helpdesk (support \\`console\\` facet active) AND they must be a member\n-- of it. So the console is strictly per-WORKSPACE: it works only while you are\n-- inside GoControl, never from a store, whoever you are. The plg_support_operators\n-- allow-list stays as an explicit extra, but it too only counts while you are in\n-- a helpdesk workspace — it never opens the console from a store.\nCREATE OR REPLACE FUNCTION public.support_is_operator()\nRETURNS boolean\nLANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''\nAS $fn$\n SELECT EXISTS (\n SELECT 1\n FROM app.tenant_plugins tp\n WHERE tp.plugin_id = 'support' AND tp.facet = 'console' AND tp.status = 'active'\n AND tp.tenant_id = app.current_tenant_id()\n AND (\n EXISTS (\n SELECT 1 FROM app.memberships m\n WHERE m.tenant_id = tp.tenant_id AND m.user_id = auth.uid() AND m.active\n )\n OR EXISTS (SELECT 1 FROM public.plg_support_operators o WHERE o.user_id = auth.uid())\n )\n );\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_is_operator() TO authenticated;\n\n-- A guard the write functions share — raises if the caller is not an operator.\nCREATE OR REPLACE FUNCTION public.support_console_guard()\nRETURNS void\nLANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''\nAS $fn$\nBEGIN\n IF NOT public.support_is_operator() THEN\n RAISE EXCEPTION 'not a support operator' USING ERRCODE = '42501';\n END IF;\nEND;\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_console_guard() TO authenticated;\n\n-- Resolve the auth user who opened a ticket to a human name: the person record\n-- in that tenant, else the signed-up full name, else the e-mail. So the console\n-- shows \"Vini\" instead of a uuid.\nCREATE OR REPLACE FUNCTION public._support_user_name(p_user uuid, p_tenant uuid)\nRETURNS text\nLANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''\nAS $fn$\n SELECT COALESCE(\n (SELECT NULLIF(btrim(p.name), '')\n FROM app.memberships m JOIN public.people p ON p.id = m.person_id\n WHERE m.user_id = p_user AND m.tenant_id = p_tenant LIMIT 1),\n (SELECT NULLIF(btrim(u.raw_user_meta_data->>'full_name'), '') FROM auth.users u WHERE u.id = p_user),\n (SELECT NULLIF(btrim(u.raw_user_meta_data->>'name'), '') FROM auth.users u WHERE u.id = p_user),\n (SELECT u.email FROM auth.users u WHERE u.id = p_user)\n );\n$fn$;\nGRANT EXECUTE ON FUNCTION public._support_user_name(uuid, uuid) TO authenticated;\n\n-- ── read: every tenant's requests, for an operator ───────────────────────\nCREATE OR REPLACE FUNCTION public.support_console_requests(\n p_statuses text[] DEFAULT NULL,\n p_search text DEFAULT NULL\n)\nRETURNS jsonb\nLANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''\nAS $fn$\nDECLARE result jsonb;\nBEGIN\n PERFORM public.support_console_guard();\n SELECT COALESCE(jsonb_agg(row_to_json(r)), '[]'::jsonb) INTO result\n FROM (\n SELECT\n q.id, q.number, q.kind, q.subject, q.description, q.status, q.priority,\n q.route, q.created_by, public._support_user_name(q.created_by, q.tenant_id) AS created_by_name,\n q.created_at, q.updated_at,\n q.linked_lead_id, q.linked_lead_name,\n q.tenant_id, t.name AS tenant_name, t.slug AS tenant_slug,\n (SELECT count(*) FROM public.plg_support_request_messages m WHERE m.request_id = q.id) AS message_count\n FROM public.plg_support_requests q\n LEFT JOIN public.tenants t ON t.id = q.tenant_id\n WHERE (p_statuses IS NULL OR q.status = ANY(p_statuses))\n AND (p_search IS NULL OR p_search = ''\n OR q.subject ILIKE '%'||p_search||'%'\n OR q.description ILIKE '%'||p_search||'%'\n OR t.name ILIKE '%'||p_search||'%')\n ORDER BY\n CASE q.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'normal' THEN 2 ELSE 3 END,\n q.updated_at DESC\n ) r;\n RETURN result;\nEND;\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_console_requests(text[], text) TO authenticated;\n\n-- ── read: one request in full ────────────────────────────────────────────\nCREATE OR REPLACE FUNCTION public.support_console_detail(p_request_id uuid)\nRETURNS jsonb\nLANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''\nAS $fn$\nDECLARE result jsonb;\nBEGIN\n PERFORM public.support_console_guard();\n SELECT jsonb_build_object(\n 'request', (SELECT row_to_json(x) FROM (\n SELECT q.*, t.name AS tenant_name, t.slug AS tenant_slug,\n public._support_user_name(q.created_by, q.tenant_id) AS created_by_name\n FROM public.plg_support_requests q\n LEFT JOIN public.tenants t ON t.id = q.tenant_id\n WHERE q.id = p_request_id) x),\n 'messages', (SELECT COALESCE(jsonb_agg(row_to_json(m) ORDER BY m.created_at), '[]'::jsonb)\n FROM public.plg_support_request_messages m WHERE m.request_id = p_request_id),\n 'events', (SELECT COALESCE(jsonb_agg(row_to_json(e) ORDER BY e.created_at), '[]'::jsonb)\n FROM public.plg_support_request_events e WHERE e.request_id = p_request_id),\n 'attachments', (SELECT COALESCE(jsonb_agg(row_to_json(a) ORDER BY a.created_at), '[]'::jsonb)\n FROM public.plg_support_request_attachments a WHERE a.request_id = p_request_id)\n ) INTO result;\n RETURN result;\nEND;\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_console_detail(uuid) TO authenticated;\n\n-- Internal: drop one unread notice to the requester, in their own tenant.\nCREATE OR REPLACE FUNCTION public._support_notify(p_request_id uuid, p_kind text)\nRETURNS void\nLANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''\nAS $fn$\nDECLARE v_tenant uuid; v_user uuid;\nBEGIN\n SELECT tenant_id, created_by INTO v_tenant, v_user\n FROM public.plg_support_requests WHERE id = p_request_id;\n IF v_user IS NULL THEN RETURN; END IF;\n INSERT INTO public.plg_support_notifications (tenant_id, request_id, user_id, kind)\n VALUES (v_tenant, p_request_id, v_user, p_kind);\nEND;\n$fn$;\n\n-- ── write: operator changes status (and the client hears about it) ───────\nCREATE OR REPLACE FUNCTION public.support_console_set_status(\n p_request_id uuid, p_status text, p_note text DEFAULT NULL\n)\nRETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''\nAS $fn$\nDECLARE v_tenant uuid;\nBEGIN\n PERFORM public.support_console_guard();\n IF p_status NOT IN ('received','in_service','waiting_you','in_development','resolved_check','closed','cancelled') THEN\n RAISE EXCEPTION 'invalid status %', p_status USING ERRCODE = '22023';\n END IF;\n SELECT tenant_id INTO v_tenant FROM public.plg_support_requests WHERE id = p_request_id;\n IF v_tenant IS NULL THEN RAISE EXCEPTION 'request not found' USING ERRCODE = 'P0002'; END IF;\n UPDATE public.plg_support_requests\n SET status = p_status,\n resolved_at = CASE WHEN p_status IN ('resolved_check','closed') THEN now() ELSE resolved_at END\n WHERE id = p_request_id;\n INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note)\n VALUES (v_tenant, p_request_id, 'status_changed', p_status);\n PERFORM public._support_notify(p_request_id,\n CASE WHEN p_status IN ('waiting_you','resolved_check') THEN 'waiting_you'\n WHEN p_status IN ('closed') THEN 'resolved' ELSE 'reply' END);\n RETURN public.support_console_detail(p_request_id);\nEND;\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_console_set_status(uuid, text, text) TO authenticated;\n\n-- ── write: operator sets priority ────────────────────────────────────────\nCREATE OR REPLACE FUNCTION public.support_console_set_priority(p_request_id uuid, p_priority text)\nRETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''\nAS $fn$\nBEGIN\n PERFORM public.support_console_guard();\n IF p_priority NOT IN ('low','normal','high','urgent') THEN\n RAISE EXCEPTION 'invalid priority %', p_priority USING ERRCODE = '22023';\n END IF;\n UPDATE public.plg_support_requests SET priority = p_priority WHERE id = p_request_id;\n RETURN public.support_console_detail(p_request_id);\nEND;\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_console_set_priority(uuid, text) TO authenticated;\n\n-- ── write: operator replies to the requester ─────────────────────────────\nCREATE OR REPLACE FUNCTION public.support_console_reply(p_request_id uuid, p_body text)\nRETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''\nAS $fn$\nDECLARE v_tenant uuid;\nBEGIN\n PERFORM public.support_console_guard();\n IF p_body IS NULL OR btrim(p_body) = '' THEN RAISE EXCEPTION 'empty message' USING ERRCODE = '22023'; END IF;\n SELECT tenant_id INTO v_tenant FROM public.plg_support_requests WHERE id = p_request_id;\n IF v_tenant IS NULL THEN RAISE EXCEPTION 'request not found' USING ERRCODE = 'P0002'; END IF;\n INSERT INTO public.plg_support_request_messages (tenant_id, request_id, author_kind, author_id, body)\n VALUES (v_tenant, p_request_id, 'team', auth.uid(), btrim(p_body));\n PERFORM public._support_notify(p_request_id, 'reply');\n RETURN public.support_console_detail(p_request_id);\nEND;\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_console_reply(uuid, text) TO authenticated;\n\n-- ── write: operator links a CRM lead/client ──────────────────────────────\nCREATE OR REPLACE FUNCTION public.support_console_link_lead(\n p_request_id uuid, p_lead_id uuid, p_lead_name text DEFAULT NULL\n)\nRETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''\nAS $fn$\nBEGIN\n PERFORM public.support_console_guard();\n UPDATE public.plg_support_requests\n SET linked_lead_id = p_lead_id, linked_lead_name = p_lead_name\n WHERE id = p_request_id;\n RETURN public.support_console_detail(p_request_id);\nEND;\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_console_link_lead(uuid, uuid, text) TO authenticated;\n`\n\nexport const MIGRATION_002_OPERATOR_ATTACHMENT_READ = `-- plugin-support — let a helpdesk OPERATOR open a chamado's attachments.\n-- Idempotent / replay-safe.\n--\n-- The bucket's read policy (000_baseline) scopes every object to its owning\n-- tenant: (storage.foldername(name))[1] IN user_tenant_ids(). That is right for\n-- the store, but the GoControl operator is in ANOTHER tenant, so the signed URL\n-- never comes back and the console shows \"anexo\" instead of the image. This adds\n-- a SECOND, permissive SELECT policy (RLS OR-combines them, so the tenant rule is\n-- untouched) that lets an operator read any support-attachments object — gated by\n-- the same support_is_operator() that guards the whole console. Read only: upload,\n-- update and delete stay tenant-scoped.\nDROP POLICY IF EXISTS plg_support_attachments_operator_read ON storage.objects;\nCREATE POLICY plg_support_attachments_operator_read ON storage.objects\n FOR SELECT TO authenticated\n USING (bucket_id = 'support-attachments' AND public.support_is_operator());\n`\n\nexport const MIGRATION_003_OPERATOR_ATTACHMENT_READ_FIX = `-- plugin-support — make the operator attachment policy actually work from Storage.\n-- Idempotent / replay-safe.\n--\n-- 002 gated the operator read on support_is_operator(), which asks\n-- app.current_tenant_id() — the OPEN workspace. That GUC is set on the normal\n-- data API, but NOT on a Storage sign request, so inside the bucket policy it is\n-- null and the check fails: the operator still got a 400 and saw \"anexo\".\n--\n-- This swaps to a context-independent test that leans only on auth.uid() (always\n-- present from the JWT): the user is a seeded cross-tenant operator, OR an active\n-- member of a tenant that runs the console (the facet). Same intent as\n-- support_is_operator(), minus the current-workspace scoping that Storage cannot\n-- answer. SECURITY DEFINER so the lookups bypass RLS, like the original.\nCREATE OR REPLACE FUNCTION public.support_is_operator_global()\nRETURNS boolean\nLANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''\nAS $fn$\n SELECT\n EXISTS (SELECT 1 FROM public.plg_support_operators o WHERE o.user_id = auth.uid())\n OR EXISTS (\n SELECT 1\n FROM app.tenant_plugins tp\n JOIN app.memberships m\n ON m.tenant_id = tp.tenant_id AND m.user_id = auth.uid() AND m.active\n WHERE tp.plugin_id = 'support' AND tp.facet = 'console' AND tp.status = 'active'\n );\n$fn$;\nGRANT EXECUTE ON FUNCTION public.support_is_operator_global() TO authenticated;\n\nDROP POLICY IF EXISTS plg_support_attachments_operator_read ON storage.objects;\nCREATE POLICY plg_support_attachments_operator_read ON storage.objects\n FOR SELECT TO authenticated\n USING (bucket_id = 'support-attachments' AND public.support_is_operator_global());\n`\n\nexport const MIGRATIONS: Array<{ id: string; sql: string }> = [\n { id: \"000_baseline\", sql: MIGRATION_000_BASELINE },\n { id: \"001_helpdesk\", sql: MIGRATION_001_HELPDESK },\n { id: \"002_operator_attachment_read\", sql: MIGRATION_002_OPERATOR_ATTACHMENT_READ },\n { id: \"003_operator_attachment_read_fix\", sql: MIGRATION_003_OPERATOR_ATTACHMENT_READ_FIX },\n]\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"SupportCenter.d.ts","sourceRoot":"","sources":["../../src/views/SupportCenter.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AASzB,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,eAAe,EAAc,MAAM,gBAAgB,CAAA;AAIlG,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,OAAO,EAAE,CAAA;IACd,QAAQ,EAAE,YAAY,EAAE,CAAA;IACxB,gBAAgB,EAAE,eAAe,EAAE,CAAA;CACpC;AAoBD;+EAC+E;AAC/E,wBAAgB,aAAa,CAAC,EAAE,OAAO,EAAE,EAAE;IAAE,OAAO,EAAE,oBAAoB,CAAA;CAAE,qBAG3E;AAkPD,eAAe,aAAa,CAAA"}
1
+ {"version":3,"file":"SupportCenter.d.ts","sourceRoot":"","sources":["../../src/views/SupportCenter.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AASzB,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,eAAe,EAAc,MAAM,gBAAgB,CAAA;AAIlG,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,OAAO,EAAE,CAAA;IACd,QAAQ,EAAE,YAAY,EAAE,CAAA;IACxB,gBAAgB,EAAE,eAAe,EAAE,CAAA;CACpC;AAmBD;+EAC+E;AAC/E,wBAAgB,aAAa,CAAC,EAAE,OAAO,EAAE,EAAE;IAAE,OAAO,EAAE,oBAAoB,CAAA;CAAE,qBAG3E;AAkPD,eAAe,aAAa,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"TicketDetailPage.d.ts","sourceRoot":"","sources":["../../src/views/TicketDetailPage.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAmBzB;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,EAAE,EAAE;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,qBAqMtD;AAyID,eAAe,gBAAgB,CAAA"}
1
+ {"version":3,"file":"TicketDetailPage.d.ts","sourceRoot":"","sources":["../../src/views/TicketDetailPage.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAoBzB;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,EAAE,EAAE;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,qBAqMtD;AAyID,eAAe,gBAAgB,CAAA"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "status": "beta",
5
5
  "dependencies": []
6
6
  },
7
- "version": "0.2.12",
7
+ "version": "0.2.14",
8
8
  "description": "Fayz SDK — plugin-support plugin (Central de Suporte do Dico: solicitações)",
9
9
  "type": "module",
10
10
  "sideEffects": false,
@@ -17,6 +17,12 @@
17
17
  "import": "./dist/index.js"
18
18
  }
19
19
  },
20
+ "imports": {
21
+ "#migrations/*": {
22
+ "browser": "./dist/migrations/*.browser.js",
23
+ "default": "./dist/migrations/*.js"
24
+ }
25
+ },
20
26
  "files": [
21
27
  "dist"
22
28
  ],
@@ -27,9 +33,9 @@
27
33
  "lucide-react": ">=0.400.0 <1.0.0"
28
34
  },
29
35
  "dependencies": {
30
- "@fayz-ai/core": "^0.61.0",
31
- "@fayz-ai/admin": "^0.61.0",
32
- "@fayz-ai/ui": "^0.61.0"
36
+ "@fayz-ai/core": "^0.63.0",
37
+ "@fayz-ai/admin": "^0.63.0",
38
+ "@fayz-ai/ui": "^0.63.0"
33
39
  },
34
40
  "devDependencies": {
35
41
  "@types/react": "^18.3.0",