@fayz-ai/plugin-support 0.3.0-canary.20261028142749 → 0.3.0

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.
Files changed (105) hide show
  1. package/dist/{HelpdeskConsole-QY534ASZ.js → HelpdeskConsole-EATEBVLN.js} +10 -7
  2. package/dist/HelpdeskConsole-EATEBVLN.js.map +1 -0
  3. package/dist/{LiveChatAgentWatcher-J6PNLYWT.js → LiveChatAgentWatcher-WEUHRRLC.js} +17 -23
  4. package/dist/LiveChatAgentWatcher-WEUHRRLC.js.map +1 -0
  5. package/dist/{OpenTicketFromConversation-KDXK7A6L.js → OpenTicketFromConversation-RC26KHN3.js} +4 -4
  6. package/dist/{OpenTicketFromConversation-KDXK7A6L.js.map → OpenTicketFromConversation-RC26KHN3.js.map} +1 -1
  7. package/dist/{SupportCenter-JBBBJTKU.js → SupportCenter-HGQL4PBX.js} +12 -9
  8. package/dist/SupportCenter-HGQL4PBX.js.map +1 -0
  9. package/dist/{SupportSettingsPage-PB6A3VCI.js → SupportSettingsPage-LIVZY2XQ.js} +3 -3
  10. package/dist/{SupportSettingsPage-PB6A3VCI.js.map → SupportSettingsPage-LIVZY2XQ.js.map} +1 -1
  11. package/dist/chunk-3WPESEK2.js +136 -0
  12. package/dist/chunk-3WPESEK2.js.map +1 -0
  13. package/dist/chunk-5MGCM5C4.js +181 -0
  14. package/dist/chunk-5MGCM5C4.js.map +1 -0
  15. package/dist/{chunk-PIMV3VRT.js → chunk-DTO5R6GN.js} +26 -126
  16. package/dist/chunk-DTO5R6GN.js.map +1 -0
  17. package/dist/chunk-E5242OSS.js +88 -0
  18. package/dist/chunk-E5242OSS.js.map +1 -0
  19. package/dist/{chunk-M4LUNCKI.js → chunk-E5EXC7QW.js} +57 -16
  20. package/dist/chunk-E5EXC7QW.js.map +1 -0
  21. package/dist/chunk-JOS2QQML.js +17 -0
  22. package/dist/chunk-JOS2QQML.js.map +1 -0
  23. package/dist/{chunk-WOZTA5LS.js → chunk-L2HGTGW4.js} +6 -4
  24. package/dist/chunk-L2HGTGW4.js.map +1 -0
  25. package/dist/{chunk-37ZZRVI7.js → chunk-P4VNMWIT.js} +79 -186
  26. package/dist/chunk-P4VNMWIT.js.map +1 -0
  27. package/dist/{chunk-CWCN5PDE.js → chunk-PHIPTZSD.js} +48 -5
  28. package/dist/chunk-PHIPTZSD.js.map +1 -0
  29. package/dist/chunk-QBOQYER7.js +1603 -0
  30. package/dist/chunk-QBOQYER7.js.map +1 -0
  31. package/dist/{chunk-MQXGB4IO.js → chunk-S766CRAY.js} +42 -239
  32. package/dist/chunk-S766CRAY.js.map +1 -0
  33. package/dist/chunk-WHEJ63CM.js +156 -0
  34. package/dist/chunk-WHEJ63CM.js.map +1 -0
  35. package/dist/chunk-Y673XGDK.js +261 -0
  36. package/dist/chunk-Y673XGDK.js.map +1 -0
  37. package/dist/data/api.d.ts +5 -0
  38. package/dist/data/api.d.ts.map +1 -1
  39. package/dist/data/console.d.ts +6 -0
  40. package/dist/data/console.d.ts.map +1 -1
  41. package/dist/data/mock-host.d.ts.map +1 -1
  42. package/dist/data/provider.d.ts +12 -0
  43. package/dist/data/provider.d.ts.map +1 -1
  44. package/dist/host.d.ts +21 -0
  45. package/dist/host.d.ts.map +1 -1
  46. package/dist/host.js +24 -10
  47. package/dist/host.js.map +1 -1
  48. package/dist/in-chat-install-2BTKBF2Z.js +11 -0
  49. package/dist/in-chat-install-2BTKBF2Z.js.map +1 -0
  50. package/dist/index.js +18 -191
  51. package/dist/index.js.map +1 -1
  52. package/dist/lib/imported.d.ts +27 -0
  53. package/dist/lib/imported.d.ts.map +1 -0
  54. package/dist/lib/report-tool.d.ts +54 -9
  55. package/dist/lib/report-tool.d.ts.map +1 -1
  56. package/dist/lib/vocabulary.d.ts.map +1 -1
  57. package/dist/livechat/LiveChatAgentWatcher.d.ts +3 -2
  58. package/dist/livechat/LiveChatAgentWatcher.d.ts.map +1 -1
  59. package/dist/livechat/in-chat-install.d.ts +19 -0
  60. package/dist/livechat/in-chat-install.d.ts.map +1 -0
  61. package/dist/livechat/in-chat-link.d.ts +10 -0
  62. package/dist/livechat/in-chat-link.d.ts.map +1 -0
  63. package/dist/livechat/in-chat-machine.d.ts +99 -0
  64. package/dist/livechat/in-chat-machine.d.ts.map +1 -0
  65. package/dist/livechat/in-chat-request-machine.d.ts +147 -0
  66. package/dist/livechat/in-chat-request-machine.d.ts.map +1 -0
  67. package/dist/livechat/in-chat-request.d.ts +94 -0
  68. package/dist/livechat/in-chat-request.d.ts.map +1 -0
  69. package/dist/livechat/in-chat-widgets.d.ts +39 -0
  70. package/dist/livechat/in-chat-widgets.d.ts.map +1 -0
  71. package/dist/livechat/in-chat.d.ts +119 -0
  72. package/dist/livechat/in-chat.d.ts.map +1 -0
  73. package/dist/livechat/report-intake.d.ts +45 -0
  74. package/dist/livechat/report-intake.d.ts.map +1 -0
  75. package/dist/livechat/screen-capture.d.ts +7 -0
  76. package/dist/livechat/screen-capture.d.ts.map +1 -0
  77. package/dist/migrations/index.d.ts +2 -0
  78. package/dist/migrations/index.d.ts.map +1 -1
  79. package/dist/migrations/main.browser.js +3 -1
  80. package/dist/migrations/main.browser.js.map +1 -1
  81. package/dist/migrations/main.js +1181 -2
  82. package/dist/migrations/main.js.map +1 -1
  83. package/dist/realtime-HQVWBTML.js +3 -0
  84. package/dist/realtime-HQVWBTML.js.map +1 -0
  85. package/dist/screen-capture-FRMTTRUY.js +77 -0
  86. package/dist/screen-capture-FRMTTRUY.js.map +1 -0
  87. package/dist/types.d.ts +5 -1
  88. package/dist/types.d.ts.map +1 -1
  89. package/dist/views/SupportRequestsPanel.d.ts.map +1 -1
  90. package/dist/views/TicketSheet.d.ts +11 -1
  91. package/dist/views/TicketSheet.d.ts.map +1 -1
  92. package/package.json +5 -5
  93. package/dist/HelpdeskConsole-QY534ASZ.js.map +0 -1
  94. package/dist/LiveChatAgentWatcher-J6PNLYWT.js.map +0 -1
  95. package/dist/SupportCenter-JBBBJTKU.js.map +0 -1
  96. package/dist/chunk-37ZZRVI7.js.map +0 -1
  97. package/dist/chunk-CWCN5PDE.js.map +0 -1
  98. package/dist/chunk-JT4ZPWH7.js +0 -61
  99. package/dist/chunk-JT4ZPWH7.js.map +0 -1
  100. package/dist/chunk-M4LUNCKI.js.map +0 -1
  101. package/dist/chunk-MQXGB4IO.js.map +0 -1
  102. package/dist/chunk-PIMV3VRT.js.map +0 -1
  103. package/dist/chunk-STEDUFNR.js +0 -42
  104. package/dist/chunk-STEDUFNR.js.map +0 -1
  105. package/dist/chunk-WOZTA5LS.js.map +0 -1
@@ -5188,6 +5188,1183 @@ $fn$;
5188
5188
  REVOKE ALL ON FUNCTION public.support_console_start_thread(uuid) FROM PUBLIC, anon;
5189
5189
  GRANT EXECUTE ON FUNCTION public.support_console_start_thread(uuid) TO authenticated;
5190
5190
  `;
5191
+ var MIGRATION_030_O_CHAMADO_DA_CASA_DO_V1_NASCE_NO_V2 = `-- plugin-support 030 \u2014 o chamado da casa do V1 nasce no V2 (V1 hospedando as telas do SDK).
5192
+ --
5193
+ -- At\xE9 a 029 o chamado de uma casa do V1 nascia no support_tickets do V1 e
5194
+ -- chegava aqui pela ponte (011: support.ticket_opened \u2192 um espelho com
5195
+ -- external_source 'v1'). Com a flag \`support_v2\` da licen\xE7a, o V1 desenha as
5196
+ -- telas do cliente do plugin (\`@fayz-ai/plugin-support/host\`) e o chamado
5197
+ -- nasce AQUI \u2014 este banco vira a fonte da verdade. O caminho:
5198
+ --
5199
+ -- navegador do V1 \u2192 edge support-v2 do V1 (sess\xE3o do V1) \u2192 pedido s\xEDncrono
5200
+ -- assinado \`support.host\` (@fayz-ai/contracts/v1-bridge) \u2192 platform-v1-bridge
5201
+ -- \u2192 customer_success_external_host_account (customer-success 040: plataforma,
5202
+ -- conta espelho, regra de QA) \u2192 support_host_call (aqui).
5203
+ --
5204
+ -- * O chamado \xE9 uma linha de plg_support_requests no tenant da PLATAFORMA (a
5205
+ -- casa do V1 nunca vira tenant deste pool), com external_source 'v1_host',
5206
+ -- external_account_id = a conta espelho e SEM external_ticket_id: n\xE3o h\xE1
5207
+ -- chamado no V1 para espelhar. created_by fica NULL (quem pede n\xE3o \xE9
5208
+ -- usu\xE1rio deste pool); quem pede est\xE1 em metadata.external (v1_user_id,
5209
+ -- nome, e-mail) \u2014 "minhas" \xE9 o v1_user_id.
5210
+ -- * Tudo o que a 011 faz para um chamado externo (external_source IS NOT
5211
+ -- NULL) vale: a thread nasce na plataforma, canal \`support\` do plugin-conversations (atendimento \xE9
5212
+ -- constru\xEDdo sobre conversations), o quadro mostra a casa, a pol\xEDtica
5213
+ -- RESTRITIVA esconde a linha de todo acesso direto, a fila do chat ao vivo
5214
+ -- (021) a enxerga.
5215
+ -- * Nada volta para o V1 como comando: _support_bridge_command e o gatilho da
5216
+ -- resposta (011/023) s\xF3 agem em external_source = 'v1'. A resposta da equipe
5217
+ -- fica na thread e o V1 a l\xEA por support_host_call('detail' | 'chat').
5218
+ -- * O fechamento autom\xE1tico (010/011) passa a valer para estes chamados: aqui
5219
+ -- n\xE3o h\xE1 V1 que encerre por eles.
5220
+ -- * support_host_call reutiliza as pe\xE7as das RPCs do solicitante (004/020/021:
5221
+ -- _support_ensure_thread, _support_thread_insert, _support_settings_of,
5222
+ -- _support_chat_waiting, _support_agent_display, _support_thread_home). As
5223
+ -- RPCs da loja (support_request_*/support_chat_*) n\xE3o servem como est\xE3o: elas
5224
+ -- decidem por auth.uid()/app.current_tenant_id(), e aqui quem pede \xE9 a conta
5225
+ -- espelho de uma casa do V1, provada pela ponte.
5226
+ --
5227
+ -- Numera\xE7\xE3o 030: support 030\u2013039 \xE9 deste lote. Idempotente e aditiva: a CHECK
5228
+ -- de external_source ganha 'v1_host' (refeita s\xF3 se ainda n\xE3o o aceita), um
5229
+ -- \xEDndice, fun\xE7\xF5es novas e CREATE OR REPLACE com a mesma assinatura de
5230
+ -- support_auto_close_resolved. Nenhuma linha existente \xE9 reescrita.
5231
+
5232
+ SET check_function_bodies = false;
5233
+
5234
+ -- \u2500\u2500 o chamado nativo de uma casa do V1 \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
5235
+ DO $c$
5236
+ BEGIN
5237
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint
5238
+ WHERE conname = 'plg_support_requests_external_source_check'
5239
+ AND pg_get_constraintdef(oid) LIKE '%v1_host%') THEN
5240
+ ALTER TABLE public.plg_support_requests DROP CONSTRAINT IF EXISTS plg_support_requests_external_source_check;
5241
+ ALTER TABLE public.plg_support_requests ADD CONSTRAINT plg_support_requests_external_source_check
5242
+ CHECK (external_source IS NULL
5243
+ OR (external_source = 'v1' AND external_env IN ('sandbox', 'production') AND external_ticket_id IS NOT NULL)
5244
+ OR (external_source = 'v1_host' AND external_env IN ('sandbox', 'production')
5245
+ AND external_account_id IS NOT NULL AND external_ticket_id IS NULL));
5246
+ END IF;
5247
+ END $c$;
5248
+ COMMENT ON COLUMN public.plg_support_requests.external_source IS
5249
+ 'De onde veio o chamado quando n\xE3o nasceu de um usu\xE1rio deste pool: ''v1'' = uma casa do V1 pela ponte (011, espelho do support_tickets); ''v1_host'' = uma casa do V1 pelas telas do SDK hospedadas no V1 (030: nasceu aqui, n\xE3o h\xE1 chamado no V1). NULL = chamado do V2.';
5250
+
5251
+ CREATE INDEX IF NOT EXISTS idx_plg_support_requests_v1_host
5252
+ ON public.plg_support_requests (external_account_id, created_at DESC) WHERE external_source = 'v1_host';
5253
+
5254
+ -- \u2500\u2500 a conta espelho \xE9 desta plataforma e deste ambiente? \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
5255
+ CREATE OR REPLACE FUNCTION public._support_host_account_ok(p_platform uuid, p_account uuid, p_env text)
5256
+ RETURNS boolean
5257
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
5258
+ AS $fn$
5259
+ DECLARE v boolean := false;
5260
+ BEGIN
5261
+ IF p_platform IS NULL OR p_account IS NULL OR to_regclass('public.plg_customer_success_external_accounts') IS NULL THEN
5262
+ RETURN false;
5263
+ END IF;
5264
+ EXECUTE 'SELECT EXISTS (SELECT 1 FROM public.plg_customer_success_external_accounts e
5265
+ WHERE e.id = $1 AND e.tenant_id = $2 AND e.env = $3)'
5266
+ INTO v USING p_account, p_platform, p_env;
5267
+ RETURN coalesce(v, false);
5268
+ END;
5269
+ $fn$;
5270
+ REVOKE ALL ON FUNCTION public._support_host_account_ok(uuid, uuid, text) FROM PUBLIC, anon, authenticated;
5271
+ GRANT EXECUTE ON FUNCTION public._support_host_account_ok(uuid, uuid, text) TO service_role;
5272
+
5273
+ -- A linha como o painel do solicitante l\xEA (as colunas de plg_support_requests;
5274
+ -- do retrato do V1, s\xF3 o nome de quem abriu \u2014 e-mail e ids ficam com a equipe).
5275
+ CREATE OR REPLACE FUNCTION public._support_host_row(q public.plg_support_requests)
5276
+ RETURNS jsonb
5277
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''
5278
+ AS $fn$
5279
+ SELECT jsonb_build_object(
5280
+ 'id', q.id, 'tenant_id', q.tenant_id, 'number', q.number, 'kind', q.kind, 'subject', q.subject,
5281
+ 'description', q.description, 'status', q.status, 'route', q.route, 'unit_id', NULL,
5282
+ 'screen_snapshot', '{}'::jsonb, 'origin_conversation_id', q.origin_conversation_id,
5283
+ 'conversation_id', q.conversation_id, 'area', q.area,
5284
+ 'created_by', q.metadata #>> '{external,v1_user_id}',
5285
+ 'created_at', q.created_at, 'updated_at', q.updated_at, 'resolved_at', q.resolved_at,
5286
+ 'metadata', jsonb_strip_nulls(jsonb_build_object('opened_by_name', q.metadata #>> '{external,opened_by_name}')));
5287
+ $fn$;
5288
+ REVOKE ALL ON FUNCTION public._support_host_row(public.plg_support_requests) FROM PUBLIC, anon, authenticated;
5289
+ GRANT EXECUTE ON FUNCTION public._support_host_row(public.plg_support_requests) TO service_role;
5290
+
5291
+ -- A conversa do chamado como o solicitante l\xEA: as mensagens antigas (legacy) e
5292
+ -- a thread desde a abertura, com quem da equipe escreveu (004 + 020).
5293
+ CREATE OR REPLACE FUNCTION public._support_host_thread(p_request_id uuid)
5294
+ RETURNS jsonb
5295
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
5296
+ AS $fn$
5297
+ DECLARE r record; v_legacy jsonb; v_thread jsonb := '[]'::jsonb; v_team text;
5298
+ BEGIN
5299
+ SELECT q.id, q.conversation_id, q.created_at, q.assignee_id INTO r
5300
+ FROM public.plg_support_requests q WHERE q.id = p_request_id;
5301
+ SELECT coalesce(jsonb_agg(jsonb_build_object(
5302
+ 'id', m.id, 'author_kind', m.author_kind, 'author', NULL, 'body', m.body,
5303
+ 'created_at', m.created_at, 'legacy', true) ORDER BY m.created_at), '[]'::jsonb)
5304
+ INTO v_legacy
5305
+ FROM public.plg_support_request_messages m WHERE m.request_id = p_request_id;
5306
+ v_team := coalesce(public._support_agent_display(public._support_thread_home(r.conversation_id), r.assignee_id), 'Suporte');
5307
+ IF r.conversation_id IS NOT NULL AND to_regclass('public.plg_conversation_messages') IS NOT NULL THEN
5308
+ EXECUTE $q$
5309
+ SELECT coalesce(jsonb_agg(jsonb_build_object(
5310
+ 'id', m.id,
5311
+ 'author_kind', CASE WHEN m.direction = 'outbound' THEN 'team' ELSE 'user' END,
5312
+ 'author', CASE WHEN m.direction = 'outbound' THEN
5313
+ CASE WHEN coalesce(btrim(m.author), '') IN ('', 'You', 'Voc\xEA') THEN $3 ELSE m.author END END,
5314
+ 'body', m.body, 'created_at', m.at, 'legacy', false) ORDER BY m.at, m.id), '[]'::jsonb)
5315
+ FROM public.plg_conversation_messages m
5316
+ WHERE m.conversation_id = $1 AND m.at >= $2 AND coalesce(btrim(m.body), '') <> ''
5317
+ $q$ INTO v_thread USING r.conversation_id, r.created_at, v_team;
5318
+ END IF;
5319
+ RETURN v_legacy || v_thread;
5320
+ END;
5321
+ $fn$;
5322
+ REVOKE ALL ON FUNCTION public._support_host_thread(uuid) FROM PUBLIC, anon, authenticated;
5323
+ GRANT EXECUTE ON FUNCTION public._support_host_thread(uuid) TO service_role;
5324
+
5325
+ -- O chat ao vivo como o cliente l\xEA (021 support_chat_state, pela conta espelho).
5326
+ CREATE OR REPLACE FUNCTION public._support_host_chat_state(p_request_id uuid)
5327
+ RETURNS jsonb
5328
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
5329
+ AS $fn$
5330
+ DECLARE r record; v_home uuid; v_wait boolean; v_pos integer; v_agent text;
5331
+ BEGIN
5332
+ SELECT q.id, q.number, q.kind, q.status, q.assignee_id, q.first_reply_at, q.conversation_id, q.created_at
5333
+ INTO r FROM public.plg_support_requests q WHERE q.id = p_request_id;
5334
+ v_home := public._support_thread_home(r.conversation_id);
5335
+ v_wait := r.kind = 'chat' AND r.assignee_id IS NULL AND r.status NOT IN ('resolved_check', 'closed', 'cancelled');
5336
+ IF v_wait AND v_home IS NOT NULL THEN
5337
+ SELECT count(*)::integer INTO v_pos
5338
+ FROM public.plg_support_requests q
5339
+ WHERE q.kind = 'chat'
5340
+ AND public._support_chat_waiting(q.kind, q.assignee_id, q.status, q.external_source, q.first_reply_at)
5341
+ AND q.created_at <= r.created_at
5342
+ AND public._support_thread_home(q.conversation_id) = v_home;
5343
+ END IF;
5344
+ IF r.assignee_id IS NOT NULL THEN
5345
+ v_agent := split_part(btrim(coalesce(public._support_agent_display(v_home, r.assignee_id), 'Suporte')), ' ', 1);
5346
+ END IF;
5347
+ RETURN jsonb_build_object(
5348
+ 'id', r.id, 'number', r.number, 'kind', r.kind, 'status', r.status,
5349
+ 'waiting', v_wait, 'position', v_pos, 'team_replied', r.first_reply_at IS NOT NULL,
5350
+ 'agent_name', v_agent, 'conversation_id', r.conversation_id, 'home_id', v_home);
5351
+ END;
5352
+ $fn$;
5353
+ REVOKE ALL ON FUNCTION public._support_host_chat_state(uuid) FROM PUBLIC, anon, authenticated;
5354
+ GRANT EXECUTE ON FUNCTION public._support_host_chat_state(uuid) TO service_role;
5355
+
5356
+ -- A conversa ATIVA desta pessoa nesta casa (020 _support_active_chat, pela conta espelho).
5357
+ CREATE OR REPLACE FUNCTION public._support_host_active_chat(p_account uuid, p_v1_user text)
5358
+ RETURNS uuid
5359
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''
5360
+ AS $fn$
5361
+ SELECT q.id FROM public.plg_support_requests q
5362
+ WHERE q.external_source = 'v1_host' AND q.external_account_id = p_account
5363
+ AND q.metadata #>> '{external,v1_user_id}' = p_v1_user
5364
+ AND q.kind = 'chat' AND q.status NOT IN ('resolved_check', 'closed', 'cancelled')
5365
+ ORDER BY q.created_at DESC LIMIT 1;
5366
+ $fn$;
5367
+ REVOKE ALL ON FUNCTION public._support_host_active_chat(uuid, text) FROM PUBLIC, anon, authenticated;
5368
+ GRANT EXECUTE ON FUNCTION public._support_host_active_chat(uuid, text) TO service_role;
5369
+
5370
+ -- \u2500\u2500 a porta: um pedido da casa do V1, j\xE1 provado pela ponte \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
5371
+ -- p_actor: { email, v1_user_id, name?, can_see_all? } (support.host actor).
5372
+ -- Erros: 22023 (pedido inv\xE1lido), P0002 (chamado n\xE3o \xE9 desta casa / n\xE3o
5373
+ -- existe), 42501 (conta de outra plataforma), 55000 (sem central ao vivo).
5374
+ CREATE OR REPLACE FUNCTION public.support_host_call(
5375
+ p_platform uuid, p_account uuid, p_env text, p_actor jsonb, p_op text, p_args jsonb DEFAULT '{}'::jsonb
5376
+ )
5377
+ RETURNS jsonb
5378
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
5379
+ AS $fn$
5380
+ DECLARE
5381
+ v_args jsonb := coalesce(p_args, '{}'::jsonb);
5382
+ v_uid text := nullif(btrim(coalesce(p_actor ->> 'v1_user_id', '')), '');
5383
+ v_email text := nullif(lower(btrim(coalesce(p_actor ->> 'email', ''))), '');
5384
+ v_name text := nullif(btrim(coalesce(p_actor ->> 'name', '')), '');
5385
+ v_all boolean := coalesce((p_actor ->> 'can_see_all')::boolean, false);
5386
+ v_house text;
5387
+ v_req public.plg_support_requests%ROWTYPE;
5388
+ v_rid uuid;
5389
+ v_id uuid;
5390
+ v_number integer;
5391
+ v_conv uuid;
5392
+ v_list jsonb;
5393
+ v_ups jsonb := '[]'::jsonb;
5394
+ v_att jsonb;
5395
+ v_path text;
5396
+ v_aid uuid;
5397
+ v_kind text;
5398
+ v_desc text;
5399
+ v_subj text;
5400
+ v_body text;
5401
+ v_meta jsonb;
5402
+ v_origin uuid;
5403
+ v_set jsonb;
5404
+ v_home uuid;
5405
+ v_active uuid;
5406
+ v_online integer := 0;
5407
+ v_reused boolean := false;
5408
+ v_statuses text[];
5409
+ BEGIN
5410
+ IF p_env NOT IN ('sandbox', 'production') THEN RAISE EXCEPTION 'invalid env %', p_env USING ERRCODE = '22023'; END IF;
5411
+ IF v_uid IS NULL OR v_email IS NULL THEN RAISE EXCEPTION 'actor needs v1_user_id and email' USING ERRCODE = '22023'; END IF;
5412
+ IF NOT public._support_host_account_ok(p_platform, p_account, p_env) THEN
5413
+ RAISE EXCEPTION 'account is not of this platform' USING ERRCODE = '42501';
5414
+ END IF;
5415
+
5416
+ -- O chamado do pedido: desta casa, nascido aqui; de outra pessoa s\xF3 com "Toda a empresa".
5417
+ IF p_op IN ('detail', 'reply', 'status', 'chat') THEN
5418
+ BEGIN
5419
+ v_rid := (v_args ->> 'request_id')::uuid;
5420
+ EXCEPTION WHEN OTHERS THEN
5421
+ RAISE EXCEPTION 'request_id invalid' USING ERRCODE = '22023';
5422
+ END;
5423
+ SELECT * INTO v_req FROM public.plg_support_requests q
5424
+ WHERE q.id = v_rid AND q.external_source = 'v1_host' AND q.external_account_id = p_account
5425
+ AND q.tenant_id = p_platform
5426
+ AND (v_all OR q.metadata #>> '{external,v1_user_id}' = v_uid)
5427
+ FOR UPDATE;
5428
+ IF v_req.id IS NULL THEN RAISE EXCEPTION 'Solicita\xE7\xE3o n\xE3o encontrada.' USING ERRCODE = 'P0002'; END IF;
5429
+ END IF;
5430
+
5431
+ -- \u2500\u2500 listar \u2500\u2500
5432
+ IF p_op = 'list' THEN
5433
+ v_statuses := CASE coalesce(v_args ->> 'filter', 'all')
5434
+ WHEN 'waiting' THEN ARRAY['waiting_you', 'resolved_check']
5435
+ WHEN 'in_progress' THEN ARRAY['received', 'triage', 'in_service', 'in_development']
5436
+ WHEN 'closed' THEN ARRAY['closed', 'cancelled']
5437
+ ELSE NULL END;
5438
+ SELECT coalesce(jsonb_agg(public._support_host_row(q) ORDER BY q.number DESC), '[]'::jsonb) INTO v_list
5439
+ FROM public.plg_support_requests q
5440
+ WHERE q.external_source = 'v1_host' AND q.external_account_id = p_account AND q.tenant_id = p_platform
5441
+ AND ((v_all AND v_args ->> 'scope' = 'all') OR q.metadata #>> '{external,v1_user_id}' = v_uid)
5442
+ AND (v_statuses IS NULL OR q.status = ANY (v_statuses));
5443
+ RETURN jsonb_build_object('requests', v_list,
5444
+ 'attention', (SELECT count(*) FROM public.plg_support_requests q
5445
+ WHERE q.external_source = 'v1_host' AND q.external_account_id = p_account
5446
+ AND q.metadata #>> '{external,v1_user_id}' = v_uid
5447
+ AND q.status IN ('waiting_you', 'resolved_check')));
5448
+
5449
+ -- \u2500\u2500 detalhe \u2500\u2500
5450
+ ELSIF p_op = 'detail' THEN
5451
+ RETURN public._support_host_row(v_req) || jsonb_build_object(
5452
+ 'messages', public._support_host_thread(v_req.id),
5453
+ -- A hist\xF3ria da equipe (atribu\xEDda, prioridade, duplicata\u2026) fica com a equipe (005).
5454
+ 'events', (SELECT coalesce(jsonb_agg(jsonb_build_object('id', e.id, 'request_id', e.request_id, 'type', e.type,
5455
+ 'note', e.note, 'created_at', e.created_at) ORDER BY e.created_at), '[]'::jsonb)
5456
+ FROM public.plg_support_request_events e
5457
+ WHERE e.request_id = v_req.id
5458
+ AND e.type NOT IN ('assigned', 'priority_changed', 'marked_duplicate', 'bridge_refused', 'thread_started')),
5459
+ 'attachments', (SELECT coalesce(jsonb_agg(jsonb_build_object('id', a.id, 'request_id', a.request_id, 'storage_path', a.storage_path,
5460
+ 'name', a.name, 'size_bytes', a.size_bytes, 'content_type', a.content_type,
5461
+ 'created_at', a.created_at) ORDER BY a.created_at), '[]'::jsonb)
5462
+ FROM public.plg_support_request_attachments a
5463
+ WHERE a.request_id = v_req.id AND a.storage_deleted_at IS NULL));
5464
+
5465
+ -- \u2500\u2500 abrir \u2500\u2500
5466
+ ELSIF p_op = 'open' THEN
5467
+ v_kind := v_args ->> 'kind';
5468
+ IF v_kind IS NULL OR v_kind NOT IN ('question', 'problem', 'improvement', 'other') THEN
5469
+ RAISE EXCEPTION 'kind invalid' USING ERRCODE = '22023';
5470
+ END IF;
5471
+ v_desc := btrim(coalesce(v_args ->> 'description', ''));
5472
+ IF length(v_desc) < 5 OR length(v_desc) > 10000 THEN RAISE EXCEPTION 'description must have 5 to 10000 characters' USING ERRCODE = '22023'; END IF;
5473
+ IF jsonb_typeof(coalesce(v_args -> 'attachments', '[]'::jsonb)) <> 'array'
5474
+ OR jsonb_array_length(coalesce(v_args -> 'attachments', '[]'::jsonb)) > 8 THEN
5475
+ RAISE EXCEPTION 'at most 8 attachments' USING ERRCODE = '22023';
5476
+ END IF;
5477
+ v_subj := left(coalesce(nullif(btrim(coalesce(v_args ->> 'subject', '')), ''),
5478
+ nullif(btrim(split_part(v_desc, E'\\n', 1)), ''), v_desc), 80);
5479
+ v_house := coalesce(nullif(btrim(coalesce(v_args ->> 'house_name', '')), ''), public._support_host_house(p_account));
5480
+ v_meta := jsonb_build_object('source', 'v1_host', 'external', jsonb_strip_nulls(jsonb_build_object(
5481
+ 'env', p_env, 'host', true, 'v1_user_id', v_uid, 'opened_by_email', v_email,
5482
+ 'opened_by_name', coalesce(v_name, split_part(v_email, '@', 1)),
5483
+ 'tenant_name', v_house, 'unit_name', nullif(btrim(coalesce(v_args ->> 'unit_name', '')), ''),
5484
+ 'origin_conversation_id', nullif(btrim(coalesce(v_args ->> 'origin_conversation_id', '')), ''))));
5485
+ BEGIN
5486
+ v_origin := nullif(btrim(coalesce(v_args ->> 'origin_conversation_id', '')), '')::uuid;
5487
+ EXCEPTION WHEN OTHERS THEN v_origin := NULL; -- o id do assistente do V2 n\xE3o \xE9 uuid: fica no retrato
5488
+ END;
5489
+ INSERT INTO public.plg_support_requests (
5490
+ tenant_id, kind, subject, description, status, route, created_by, screen_snapshot, origin_conversation_id,
5491
+ metadata, external_source, external_env, external_account_id
5492
+ ) VALUES (
5493
+ p_platform, v_kind, v_subj, v_desc, 'received', nullif(btrim(coalesce(v_args ->> 'route', '')), ''), NULL,
5494
+ CASE WHEN jsonb_typeof(v_args -> 'screen_snapshot') = 'object' THEN v_args -> 'screen_snapshot' ELSE '{}'::jsonb END,
5495
+ v_origin, v_meta, 'v1_host', p_env, p_account
5496
+ ) RETURNING id, number INTO v_id, v_number;
5497
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note) VALUES (p_platform, v_id, 'opened', NULL);
5498
+ -- Os anexos: a linha agora, o arquivo pelo link assinado que a edge devolve.
5499
+ FOR v_att IN SELECT * FROM jsonb_array_elements(coalesce(v_args -> 'attachments', '[]'::jsonb)) LOOP
5500
+ IF coalesce(btrim(v_att ->> 'name'), '') = '' OR coalesce((v_att ->> 'size_bytes')::bigint, 0) <= 0
5501
+ OR (v_att ->> 'size_bytes')::bigint > 20 * 1024 * 1024 THEN
5502
+ RAISE EXCEPTION 'attachment invalid' USING ERRCODE = '22023';
5503
+ END IF;
5504
+ v_aid := gen_random_uuid();
5505
+ v_path := p_platform::text || '/' || v_id::text || '/' || v_aid::text || '/'
5506
+ || left(regexp_replace(btrim(v_att ->> 'name'), '[^A-Za-z0-9_.-]+', '_', 'g'), 120);
5507
+ INSERT INTO public.plg_support_request_attachments (id, tenant_id, request_id, storage_path, name, size_bytes, content_type, created_by)
5508
+ VALUES (v_aid, p_platform, v_id, v_path, left(btrim(v_att ->> 'name'), 300), (v_att ->> 'size_bytes')::bigint,
5509
+ left(coalesce(nullif(btrim(v_att ->> 'content_type'), ''), 'application/octet-stream'), 120), NULL);
5510
+ v_ups := v_ups || jsonb_build_array(jsonb_build_object('attachment_id', v_aid, 'name', left(btrim(v_att ->> 'name'), 300), 'storage_path', v_path));
5511
+ END LOOP;
5512
+ SELECT q.conversation_id INTO v_conv FROM public.plg_support_requests q WHERE q.id = v_id;
5513
+ RETURN jsonb_build_object('id', v_id, 'number', v_number, 'conversation_id', v_conv, 'uploads', v_ups);
5514
+
5515
+ -- \u2500\u2500 responder \u2500\u2500
5516
+ ELSIF p_op = 'reply' THEN
5517
+ v_body := btrim(coalesce(v_args ->> 'body', ''));
5518
+ IF v_body = '' OR length(v_body) > 20000 THEN RAISE EXCEPTION 'empty message' USING ERRCODE = '22023'; END IF;
5519
+ IF v_req.status IN ('closed', 'cancelled') THEN
5520
+ RAISE EXCEPTION 'Esta solicita\xE7\xE3o est\xE1 encerrada.' USING ERRCODE = '22023';
5521
+ END IF;
5522
+ v_conv := public._support_ensure_thread(v_req.id, p_platform);
5523
+ IF v_conv IS NULL THEN
5524
+ INSERT INTO public.plg_support_request_messages (tenant_id, request_id, author_kind, author_id, body)
5525
+ VALUES (p_platform, v_req.id, 'user', NULL, v_body);
5526
+ ELSE
5527
+ PERFORM public._support_thread_insert(v_conv, 'inbound', v_body,
5528
+ coalesce(v_name, v_req.metadata #>> '{external,opened_by_name}', 'Solicitante'));
5529
+ END IF;
5530
+ RETURN jsonb_build_object('conversation_id', v_conv, 'messages', public._support_host_thread(v_req.id));
5531
+
5532
+ -- \u2500\u2500 andamento pelo solicitante \u2500\u2500
5533
+ ELSIF p_op = 'status' THEN
5534
+ IF v_args ->> 'action' = 'cancel' THEN
5535
+ IF v_req.status NOT IN ('received', 'triage', 'waiting_you') THEN
5536
+ RAISE EXCEPTION 'Esta solicita\xE7\xE3o n\xE3o pode mais ser cancelada.' USING ERRCODE = '22023';
5537
+ END IF;
5538
+ UPDATE public.plg_support_requests SET status = 'cancelled' WHERE id = v_req.id;
5539
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note) VALUES (p_platform, v_req.id, 'cancelled', NULL);
5540
+ ELSIF v_args ->> 'action' IN ('accept', 'reopen') THEN
5541
+ IF v_req.status <> 'resolved_check' THEN
5542
+ RAISE EXCEPTION 'Esta solicita\xE7\xE3o n\xE3o est\xE1 esperando a sua confirma\xE7\xE3o.' USING ERRCODE = '22023';
5543
+ END IF;
5544
+ IF v_args ->> 'action' = 'accept' THEN
5545
+ UPDATE public.plg_support_requests SET status = 'closed' WHERE id = v_req.id;
5546
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note) VALUES (p_platform, v_req.id, 'validated_ok', NULL);
5547
+ ELSE
5548
+ UPDATE public.plg_support_requests SET status = 'received', resolved_at = NULL WHERE id = v_req.id;
5549
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note)
5550
+ VALUES (p_platform, v_req.id, 'reopened', nullif(left(btrim(coalesce(v_args ->> 'reason', '')), 2000), ''));
5551
+ END IF;
5552
+ ELSE
5553
+ RAISE EXCEPTION 'action invalid' USING ERRCODE = '22023';
5554
+ END IF;
5555
+ SELECT * INTO v_req FROM public.plg_support_requests q WHERE q.id = v_req.id;
5556
+ RETURN public._support_host_row(v_req);
5557
+
5558
+ -- \u2500\u2500 a porta do chat ao vivo \u2500\u2500
5559
+ ELSIF p_op = 'chat_availability' THEN
5560
+ -- A central de um chamado externo \xE9 a pr\xF3pria plataforma (011); ela atende se roda o console.
5561
+ v_home := CASE WHEN public._support_is_console_tenant(p_platform) AND to_regclass('public.plg_conversations') IS NOT NULL
5562
+ THEN p_platform END;
5563
+ v_set := public._support_settings_of(coalesce(v_home, p_platform));
5564
+ v_active := public._support_host_active_chat(p_account, v_uid);
5565
+ IF v_active IS NOT NULL THEN SELECT q.number INTO v_number FROM public.plg_support_requests q WHERE q.id = v_active; END IF;
5566
+ -- O navegador do V1 n\xE3o v\xEA a presen\xE7a do Realtime daqui: conta o ponto dos atendentes (021).
5567
+ IF v_home IS NOT NULL THEN
5568
+ SELECT count(*)::integer INTO v_online
5569
+ FROM public.plg_support_agent_presence pr
5570
+ WHERE pr.tenant_id = v_home AND pr.status = 'online' AND public._support_presence_fresh(pr.seen_at)
5571
+ AND (NOT EXISTS (SELECT 1 FROM public.plg_support_agents a WHERE a.tenant_id = v_home)
5572
+ OR EXISTS (SELECT 1 FROM public.plg_support_agents a WHERE a.tenant_id = v_home AND a.user_id = pr.user_id AND a.active));
5573
+ END IF;
5574
+ RETURN jsonb_build_object(
5575
+ 'home_id', v_home, 'enabled', v_home IS NOT NULL,
5576
+ 'offline_message', v_set ->> 'offline_message', 'business_hours', v_set -> 'business_hours', 'timezone', v_set ->> 'timezone',
5577
+ 'active_chat', CASE WHEN v_active IS NULL THEN NULL ELSE jsonb_build_object('id', v_active, 'number', v_number) END,
5578
+ 'online', v_online);
5579
+
5580
+ ELSIF p_op = 'chat_open' THEN
5581
+ IF NOT public._support_is_console_tenant(p_platform) OR to_regclass('public.plg_conversations') IS NULL THEN
5582
+ RAISE EXCEPTION 'O atendimento ao vivo n\xE3o est\xE1 dispon\xEDvel nesta conta.' USING ERRCODE = '55000';
5583
+ END IF;
5584
+ -- Uma conversa por pessoa por vez: clicar de novo volta \xE0 que est\xE1 aberta.
5585
+ PERFORM pg_advisory_xact_lock(hashtextextended('support_host_chat_open:' || p_account::text || ':' || v_uid, 0));
5586
+ v_id := public._support_host_active_chat(p_account, v_uid);
5587
+ IF v_id IS NOT NULL THEN
5588
+ v_reused := true;
5589
+ ELSE
5590
+ v_house := coalesce(nullif(btrim(coalesce(v_args ->> 'house_name', '')), ''), public._support_host_house(p_account));
5591
+ v_meta := jsonb_build_object('source', 'v1_host', 'external', jsonb_strip_nulls(jsonb_build_object(
5592
+ 'env', p_env, 'host', true, 'v1_user_id', v_uid, 'opened_by_email', v_email,
5593
+ 'opened_by_name', coalesce(v_name, split_part(v_email, '@', 1)),
5594
+ 'tenant_name', v_house, 'unit_name', nullif(btrim(coalesce(v_args ->> 'unit_name', '')), ''),
5595
+ 'origin_conversation_id', nullif(btrim(coalesce(v_args ->> 'origin_conversation_id', '')), ''))));
5596
+ BEGIN
5597
+ v_origin := nullif(btrim(coalesce(v_args ->> 'origin_conversation_id', '')), '')::uuid;
5598
+ EXCEPTION WHEN OTHERS THEN v_origin := NULL;
5599
+ END;
5600
+ INSERT INTO public.plg_support_requests (
5601
+ tenant_id, kind, subject, description, status, route, created_by, screen_snapshot, origin_conversation_id,
5602
+ metadata, external_source, external_env, external_account_id
5603
+ ) VALUES (
5604
+ p_platform, 'chat',
5605
+ left(coalesce(nullif(btrim(coalesce(v_args ->> 'subject', '')), ''), 'Conversa com atendente'), 200),
5606
+ left(coalesce(nullif(btrim(coalesce(v_args ->> 'description', '')), ''), 'A pessoa pediu para falar com um atendente.'), 10000),
5607
+ 'received', nullif(btrim(coalesce(v_args ->> 'route', '')), ''), NULL,
5608
+ CASE WHEN jsonb_typeof(v_args -> 'screen_snapshot') = 'object' THEN v_args -> 'screen_snapshot' ELSE '{}'::jsonb END,
5609
+ v_origin, v_meta, 'v1_host', p_env, p_account
5610
+ ) RETURNING id INTO v_id;
5611
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note) VALUES (p_platform, v_id, 'opened', NULL);
5612
+ END IF;
5613
+ v_conv := public._support_ensure_thread(v_id, p_platform);
5614
+ SELECT q.number INTO v_number FROM public.plg_support_requests q WHERE q.id = v_id;
5615
+ RETURN jsonb_build_object('id', v_id, 'number', v_number, 'conversation_id', v_conv, 'reused', v_reused);
5616
+
5617
+ ELSIF p_op = 'chat' THEN
5618
+ RETURN jsonb_build_object('state', public._support_host_chat_state(v_req.id),
5619
+ 'messages', public._support_host_thread(v_req.id));
5620
+ END IF;
5621
+
5622
+ RAISE EXCEPTION 'unknown op %', p_op USING ERRCODE = '22023';
5623
+ END;
5624
+ $fn$;
5625
+ REVOKE ALL ON FUNCTION public.support_host_call(uuid, uuid, text, jsonb, text, jsonb) FROM PUBLIC, anon, authenticated;
5626
+ GRANT EXECUTE ON FUNCTION public.support_host_call(uuid, uuid, text, jsonb, text, jsonb) TO service_role;
5627
+
5628
+ -- O nome da casa no espelho (customer-success 003), sem FK entre prefixos.
5629
+ CREATE OR REPLACE FUNCTION public._support_host_house(p_account uuid)
5630
+ RETURNS text
5631
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
5632
+ AS $fn$
5633
+ DECLARE v text;
5634
+ BEGIN
5635
+ IF p_account IS NULL OR to_regclass('public.plg_customer_success_external_accounts') IS NULL THEN RETURN NULL; END IF;
5636
+ EXECUTE 'SELECT nullif(btrim(e.name), '''') FROM public.plg_customer_success_external_accounts e WHERE e.id = $1' INTO v USING p_account;
5637
+ RETURN v;
5638
+ END;
5639
+ $fn$;
5640
+ REVOKE ALL ON FUNCTION public._support_host_house(uuid) FROM PUBLIC, anon, authenticated;
5641
+ GRANT EXECUTE ON FUNCTION public._support_host_house(uuid) TO service_role;
5642
+
5643
+ -- \u2500\u2500 fechamento autom\xE1tico (010/011) + os chamados nativos da casa do V1 \u2500\u2500
5644
+ -- O V1 encerra os dele (external_source 'v1'); os nativos n\xE3o t\xEAm quem encerre l\xE1.
5645
+ CREATE OR REPLACE FUNCTION public.support_auto_close_resolved(p_now timestamptz DEFAULT now())
5646
+ RETURNS integer
5647
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
5648
+ AS $fn$
5649
+ DECLARE
5650
+ r record;
5651
+ v_days integer;
5652
+ v_n integer := 0;
5653
+ BEGIN
5654
+ FOR r IN
5655
+ SELECT q.id, q.tenant_id, coalesce(q.resolved_at, q.updated_at) AS since
5656
+ FROM public.plg_support_requests q
5657
+ WHERE q.status = 'resolved_check' AND (q.external_source IS NULL OR q.external_source = 'v1_host')
5658
+ FOR UPDATE SKIP LOCKED
5659
+ LOOP
5660
+ v_days := (public._support_settings_of(public._support_default_home(r.id)) ->> 'auto_close_resolved_days')::integer;
5661
+ IF r.since <= p_now - make_interval(days => v_days) THEN
5662
+ UPDATE public.plg_support_requests SET status = 'closed' WHERE id = r.id;
5663
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note)
5664
+ VALUES (r.tenant_id, r.id, 'closed_no_reply', 'Encerrada sem resposta do cliente no prazo');
5665
+ v_n := v_n + 1;
5666
+ END IF;
5667
+ END LOOP;
5668
+ RETURN v_n;
5669
+ END;
5670
+ $fn$;
5671
+ REVOKE ALL ON FUNCTION public.support_auto_close_resolved(timestamptz) FROM PUBLIC, anon, authenticated;
5672
+ GRANT EXECUTE ON FUNCTION public.support_auto_close_resolved(timestamptz) TO service_role;
5673
+ `;
5674
+ var MIGRATION_040_OS_CHAMADOS_DO_V1_MIGRAM_SEM_AVISAR_NINGUEM = `-- plugin-support 040 \u2014 os chamados do V1 migram para o quadro sem avisar ningu\xE9m.
5675
+ --
5676
+ -- Decis\xE3o do dono do produto (28/10): o hist\xF3rico de chamados do V1 de PRODU\xC7\xC3O
5677
+ -- (s\xF3 leitura) entra no Atendimento do tenant controlgroup real \u2014 para testar a
5678
+ -- paridade e como base do corte. A ponte (011) s\xF3 conhece o chamado que nasce ou
5679
+ -- muda DEPOIS de ligada; o que j\xE1 existia no V1 chega por aqui, uma vez, pelo
5680
+ -- script scripts/support-migrate-v1-tickets.mjs (runbook:
5681
+ -- docs/checkpoints/SUPPORT-MIGRATE-V1.md).
5682
+ --
5683
+ -- * support_import_v1_ticket(p_tenant, p_payload) \u2014 s\xF3 service_role. Cria o
5684
+ -- chamado de origem 'v1' com a MESMA forma do que chega pela ponte
5685
+ -- (support_external_apply, 011): tenant da plataforma, conta espelho da
5686
+ -- licen\xE7a (customer-success 003), retrato em metadata.external, andamento
5687
+ -- por _support_status_from_v1 (a mesma tabela da ponte), tipo e prioridade
5688
+ -- pelo mesmo de-para, e a thread do canal \`support\` por _support_ensure_thread
5689
+ -- (011/024). Os hor\xE1rios s\xE3o os ORIGINAIS do V1 (aberto, \xFAltima atividade,
5690
+ -- primeira resposta, resolvido); o SLA do quadro (lib/sla.ts) \xE9 calculado a
5691
+ -- partir deles \u2014 um chamado antigo e aberto aparece vencido, como no V1.
5692
+ -- * Chave de idempot\xEAncia: a da ponte (external_source, external_env,
5693
+ -- external_ticket_id \u2014 uq_plg_support_requests_external). Mensagem p\xFAblica \u2192
5694
+ -- plg_conversation_messages.provider_message_id = 'v1:<env>:<id>' (\xEDndice
5695
+ -- \xFAnico global); nota interna \u2192 plg_support_request_notes.external_message_id;
5696
+ -- anexo \u2192 plg_support_request_attachments.external_attachment_id. Rodar duas
5697
+ -- vezes n\xE3o duplica nada; a segunda passada s\xF3 acrescenta o que o V1 ganhou
5698
+ -- e acompanha o andamento.
5699
+ -- * Um chamado que J\xC1 chegou pela ponte (imported_at NULL) n\xE3o \xE9 tocado:
5700
+ -- volta 'skipped: bridge'.
5701
+ -- * Nada sai: a importa\xE7\xE3o liga, s\xF3 na pr\xF3pria transa\xE7\xE3o, duas flags \u2014
5702
+ -- fayz.support_bridge_ingest (a da 011: nenhum support.reply/support.status
5703
+ -- volta ao V1) e fayz.support_import (esta): os gatilhos do suporte que
5704
+ -- tocam campainha (_support_board_ping, _support_ring), avisam o solicitante
5705
+ -- (_support_notify \u2192 e-mail da 022) ou mexem no andamento
5706
+ -- (_support_on_public_message) n\xE3o fazem nada, e o carimbo de updated_at
5707
+ -- respeita o hor\xE1rio do V1. Os gatilhos da CAIXA (conversations: campainha
5708
+ -- da chegada, ao vivo, n\xE3o lidas, funil) s\xE3o de outro plugin e n\xE3o s\xE3o
5709
+ -- alterados aqui: cada mensagem hist\xF3rica entra na forma neutra que todos
5710
+ -- eles ignoram (direction e channel NULL) e ganha dire\xE7\xE3o/canal num UPDATE
5711
+ -- logo depois \u2014 a tabela n\xE3o tem gatilho de UPDATE. Para essa garantia n\xE3o
5712
+ -- envelhecer em sil\xEAncio, a fun\xE7\xE3o recusa (55000) rodar se os gatilhos das
5713
+ -- tabelas que ela escreve n\xE3o forem exatamente os auditados
5714
+ -- (_support_import_v1_audited_triggers): um gatilho novo exige auditoria e
5715
+ -- uma migration que o acrescente \xE0 lista.
5716
+ -- * Anexos: o padr\xE3o \xE9 N\xC3O copiar (decis\xE3o de 27/10, 014) \u2014 o anexo entra com
5717
+ -- location = 'v1' (o painel mostra o nome; o link vem do V1 sob demanda pela
5718
+ -- ponte). Com --copy-attachments e as chaves de servi\xE7o no ambiente, o script
5719
+ -- copia o arquivo para o bucket support-attachments do V2 antes de chamar a
5720
+ -- fun\xE7\xE3o, e o anexo entra com location = 'v2' (uma passada posterior com
5721
+ -- c\xF3pia promove 'v1' \u2192 'v2').
5722
+ -- * Selo "migrado do V1": imported_at no chamado; o quadro pede os ids por
5723
+ -- support_console_imported_ids() (o quadro, support_console_board, n\xE3o \xE9
5724
+ -- redefinido aqui) e o painel l\xEA imported_at do detalhe.
5725
+ -- * support_import_v1_rollback(p_tenant, p_env, p_apply) \u2014 desfaz s\xF3 o que tem
5726
+ -- marca de importado e n\xE3o foi tocado depois (sem resposta, nota ou anexo do
5727
+ -- V2, sem mudan\xE7a no V2); p_apply = false \xE9 a pr\xE9via. Uma segunda passada
5728
+ -- tamb\xE9m n\xE3o sobrescreve o andamento de um chamado j\xE1 mexido no V2.
5729
+ --
5730
+ -- Idempotente e aditiva: colunas novas, \xEDndices, uma CHECK, fun\xE7\xF5es novas e
5731
+ -- CREATE OR REPLACE com as MESMAS assinaturas de cinco fun\xE7\xF5es pequenas
5732
+ -- (plg_support_touch_updated_at, _support_board_ping, _support_ring,
5733
+ -- _support_notify, _support_on_public_message) \u2014 fora da importa\xE7\xE3o, o
5734
+ -- comportamento \xE9 o de antes. Nenhuma linha existente \xE9 reescrita.
5735
+
5736
+ SET check_function_bodies = false;
5737
+
5738
+ -- \u2500\u2500 as marcas de importado \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
5739
+ ALTER TABLE public.plg_support_requests ADD COLUMN IF NOT EXISTS imported_at timestamptz;
5740
+ COMMENT ON COLUMN public.plg_support_requests.imported_at IS
5741
+ 'Quando o chamado do V1 entrou por importa\xE7\xE3o (040), n\xE3o pela ponte. NULL = nasceu no V2 ou chegou pela ponte.';
5742
+ CREATE INDEX IF NOT EXISTS idx_plg_support_requests_imported
5743
+ ON public.plg_support_requests (tenant_id, external_env) WHERE imported_at IS NOT NULL;
5744
+
5745
+ ALTER TABLE public.plg_support_request_attachments ADD COLUMN IF NOT EXISTS external_attachment_id text;
5746
+ ALTER TABLE public.plg_support_request_attachments ADD COLUMN IF NOT EXISTS location text;
5747
+ COMMENT ON COLUMN public.plg_support_request_attachments.location IS
5748
+ 'Onde o arquivo est\xE1 (040): NULL ou ''v2'' = bucket support-attachments do V2; ''v1'' = ficou no V1 (s\xF3 o nome veio).';
5749
+ DO $c$
5750
+ BEGIN
5751
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_support_request_attachments_location_check') THEN
5752
+ ALTER TABLE public.plg_support_request_attachments ADD CONSTRAINT plg_support_request_attachments_location_check
5753
+ CHECK (location IS NULL OR location IN ('v1', 'v2'));
5754
+ END IF;
5755
+ END $c$;
5756
+ CREATE UNIQUE INDEX IF NOT EXISTS uq_plg_support_request_attachments_external
5757
+ ON public.plg_support_request_attachments (request_id, external_attachment_id) WHERE external_attachment_id IS NOT NULL;
5758
+
5759
+ ALTER TABLE public.plg_support_request_notes ADD COLUMN IF NOT EXISTS external_message_id text;
5760
+ CREATE UNIQUE INDEX IF NOT EXISTS uq_plg_support_request_notes_external
5761
+ ON public.plg_support_request_notes (request_id, external_message_id) WHERE external_message_id IS NOT NULL;
5762
+
5763
+ -- \u2500\u2500 os gatilhos do suporte respeitam a importa\xE7\xE3o \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
5764
+ -- current_setting inline (n\xE3o uma fun\xE7\xE3o auxiliar): estes corpos rodam tamb\xE9m
5765
+ -- como \`authenticated\`, e o teste n\xE3o pode depender de um EXECUTE concedido.
5766
+
5767
+ -- O carimbo de updated_at (000): na importa\xE7\xE3o vale o hor\xE1rio do V1.
5768
+ CREATE OR REPLACE FUNCTION public.plg_support_touch_updated_at()
5769
+ RETURNS trigger
5770
+ LANGUAGE plpgsql
5771
+ AS $fn$
5772
+ BEGIN
5773
+ IF coalesce(current_setting('fayz.support_import', true), '') = 'on' THEN RETURN NEW; END IF;
5774
+ NEW.updated_at := now();
5775
+ RETURN NEW;
5776
+ END;
5777
+ $fn$;
5778
+
5779
+ -- A campainha do quadro (005).
5780
+ CREATE OR REPLACE FUNCTION public._support_board_ping(p_request_id uuid)
5781
+ RETURNS void
5782
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
5783
+ AS $fn$
5784
+ BEGIN
5785
+ IF coalesce(current_setting('fayz.support_import', true), '') = 'on' THEN RETURN; END IF;
5786
+ BEGIN
5787
+ PERFORM realtime.send(jsonb_build_object('requestId', p_request_id), 'changed', 'suporte:quadro', false);
5788
+ EXCEPTION WHEN OTHERS THEN
5789
+ NULL;
5790
+ END;
5791
+ END;
5792
+ $fn$;
5793
+ REVOKE ALL ON FUNCTION public._support_board_ping(uuid) FROM PUBLIC, anon, authenticated;
5794
+ GRANT EXECUTE ON FUNCTION public._support_board_ping(uuid) TO service_role;
5795
+
5796
+ -- As campainhas da conversa e da fila (020/021).
5797
+ CREATE OR REPLACE FUNCTION public._support_ring(p_topic text, p_event text, p_payload jsonb)
5798
+ RETURNS void
5799
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
5800
+ AS $fn$
5801
+ BEGIN
5802
+ IF coalesce(current_setting('fayz.support_import', true), '') = 'on' THEN RETURN; END IF;
5803
+ BEGIN
5804
+ PERFORM realtime.send(p_payload, p_event, p_topic, false);
5805
+ EXCEPTION WHEN OTHERS THEN
5806
+ NULL; -- sem Realtime (banco de teste): a tela rel\xEA no pr\xF3ximo carregamento
5807
+ END;
5808
+ END;
5809
+ $fn$;
5810
+ REVOKE ALL ON FUNCTION public._support_ring(text, text, jsonb) FROM PUBLIC, anon, authenticated;
5811
+ GRANT EXECUTE ON FUNCTION public._support_ring(text, text, jsonb) TO service_role;
5812
+
5813
+ -- O aviso ao solicitante (001) \u2014 e, por ele, o e-mail da 022.
5814
+ CREATE OR REPLACE FUNCTION public._support_notify(p_request_id uuid, p_kind text)
5815
+ RETURNS void
5816
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
5817
+ AS $fn$
5818
+ DECLARE v_tenant uuid; v_user uuid;
5819
+ BEGIN
5820
+ IF coalesce(current_setting('fayz.support_import', true), '') = 'on' THEN RETURN; END IF;
5821
+ SELECT tenant_id, created_by INTO v_tenant, v_user
5822
+ FROM public.plg_support_requests WHERE id = p_request_id;
5823
+ IF v_user IS NULL THEN RETURN; END IF;
5824
+ INSERT INTO public.plg_support_notifications (tenant_id, request_id, user_id, kind)
5825
+ VALUES (v_tenant, p_request_id, v_user, p_kind);
5826
+ END;
5827
+ $fn$;
5828
+ REVOKE ALL ON FUNCTION public._support_notify(uuid, text) FROM PUBLIC, anon, authenticated;
5829
+ GRANT EXECUTE ON FUNCTION public._support_notify(uuid, text) TO service_role;
5830
+
5831
+ -- O que uma mensagem p\xFAblica faz com o chamado (005): na importa\xE7\xE3o, nada \u2014
5832
+ -- a primeira resposta e o andamento v\xEAm prontos do V1.
5833
+ CREATE OR REPLACE FUNCTION public._support_on_public_message(p_request_id uuid, p_from text, p_at timestamptz)
5834
+ RETURNS void
5835
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
5836
+ AS $fn$
5837
+ DECLARE r record;
5838
+ BEGIN
5839
+ IF coalesce(current_setting('fayz.support_import', true), '') = 'on' THEN RETURN; END IF;
5840
+ SELECT q.tenant_id, q.status, q.first_reply_at INTO r
5841
+ FROM public.plg_support_requests q WHERE q.id = p_request_id;
5842
+ IF NOT FOUND THEN RETURN; END IF;
5843
+
5844
+ IF p_from = 'team' THEN
5845
+ IF r.first_reply_at IS NULL THEN
5846
+ UPDATE public.plg_support_requests SET first_reply_at = coalesce(p_at, now()) WHERE id = p_request_id;
5847
+ END IF;
5848
+ IF r.status IN ('received', 'triage') THEN
5849
+ UPDATE public.plg_support_requests SET status = 'in_service' WHERE id = p_request_id;
5850
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note)
5851
+ VALUES (r.tenant_id, p_request_id, 'status_changed', 'in_service');
5852
+ END IF;
5853
+ ELSIF p_from = 'customer' THEN
5854
+ IF r.status = 'waiting_you' THEN
5855
+ UPDATE public.plg_support_requests SET status = 'in_service' WHERE id = p_request_id;
5856
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note)
5857
+ VALUES (r.tenant_id, p_request_id, 'status_changed', 'in_service');
5858
+ END IF;
5859
+ END IF;
5860
+ END;
5861
+ $fn$;
5862
+ REVOKE ALL ON FUNCTION public._support_on_public_message(uuid, text, timestamptz) FROM PUBLIC, anon, authenticated;
5863
+ GRANT EXECUTE ON FUNCTION public._support_on_public_message(uuid, text, timestamptz) TO service_role;
5864
+
5865
+ -- \u2500\u2500 os gatilhos auditados \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
5866
+ -- Cada gatilho de usu\xE1rio das tabelas que a importa\xE7\xE3o escreve, com o porqu\xEA
5867
+ -- de ele n\xE3o disparar nada para fora (prova: .evidence/2026-10-28-support-migrate-v1).
5868
+ -- Um gatilho que n\xE3o est\xE1 aqui faz a importa\xE7\xE3o recusar at\xE9 ser auditado.
5869
+ CREATE OR REPLACE FUNCTION public._support_import_v1_audited_triggers()
5870
+ RETURNS text[]
5871
+ LANGUAGE sql IMMUTABLE SET search_path TO ''
5872
+ AS $fn$
5873
+ SELECT ARRAY[
5874
+ -- chamado
5875
+ 'plg_support_requests:trg_plg_support_assign_number', -- n\xFAmero do V2 (o quadro mostra o do V1)
5876
+ 'plg_support_requests:trg_plg_support_requests_touch', -- respeita fayz.support_import (040)
5877
+ 'plg_support_requests:trg_plg_support_requests_open_thread', -- a thread (mesma forma da ponte)
5878
+ 'plg_support_requests:trg_plg_support_requests_ping', -- _support_board_ping: mudo na importa\xE7\xE3o
5879
+ 'plg_support_requests:trg_plg_support_chat_bells', -- _support_ring: mudo na importa\xE7\xE3o
5880
+ 'plg_support_requests:trg_plg_support_requests_bridge_status',-- _support_bridge_command: mudo com fayz.support_bridge_ingest
5881
+ -- anexos e notas
5882
+ 'plg_support_request_attachments:trg_plg_support_attachment_expiry', -- s\xF3 carimba expires_at
5883
+ 'plg_support_request_notes:trg_plg_support_notes_ping', -- _support_board_ping: mudo
5884
+ -- a caixa
5885
+ 'plg_conversation_messages:plg_conversation_messages_stamp_direction', -- direction NULL no INSERT: no-op
5886
+ 'plg_conversation_messages:plg_conversation_messages_bump_unread', -- s\xF3 inbound: no-op
5887
+ 'plg_conversation_messages:conversations_log_crm_activity', -- canal support: no-op (conversations 024)
5888
+ 'plg_conversation_messages:plg_conversations_anunciar_chegada', -- s\xF3 inbound: no-op
5889
+ 'plg_conversation_messages:plg_conversations_ao_vivo', -- channel NULL no INSERT: no-op
5890
+ 'plg_conversation_messages:plg_support_thread_notify', -- sem dire\xE7\xE3o: no-op (e mudo)
5891
+ 'plg_conversation_messages:plg_support_bridge_reply' -- n\xE3o \xE9 outbound no INSERT (e mudo)
5892
+ ]::text[];
5893
+ $fn$;
5894
+ REVOKE ALL ON FUNCTION public._support_import_v1_audited_triggers() FROM PUBLIC, anon, authenticated;
5895
+ GRANT EXECUTE ON FUNCTION public._support_import_v1_audited_triggers() TO service_role;
5896
+
5897
+ -- Os gatilhos que existem e n\xE3o foram auditados (vazio = pode importar).
5898
+ CREATE OR REPLACE FUNCTION public._support_import_v1_unaudited_triggers()
5899
+ RETURNS text[]
5900
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''
5901
+ AS $fn$
5902
+ SELECT coalesce(array_agg(x.k ORDER BY x.k), '{}'::text[])
5903
+ FROM (
5904
+ SELECT c.relname || ':' || tg.tgname AS k
5905
+ FROM pg_catalog.pg_trigger tg
5906
+ JOIN pg_catalog.pg_class c ON c.oid = tg.tgrelid
5907
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
5908
+ WHERE NOT tg.tgisinternal
5909
+ AND tg.tgenabled <> 'D'
5910
+ AND n.nspname = 'public'
5911
+ AND c.relname IN ('plg_support_requests', 'plg_support_request_events', 'plg_support_request_attachments',
5912
+ 'plg_support_request_notes', 'plg_conversations', 'plg_conversation_messages')
5913
+ ) x
5914
+ WHERE NOT (x.k = ANY (public._support_import_v1_audited_triggers()));
5915
+ $fn$;
5916
+ REVOKE ALL ON FUNCTION public._support_import_v1_unaudited_triggers() FROM PUBLIC, anon, authenticated;
5917
+ GRANT EXECUTE ON FUNCTION public._support_import_v1_unaudited_triggers() TO service_role;
5918
+
5919
+ -- \u2500\u2500 de-para do V1 (o mesmo da ponte, 011) \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
5920
+ CREATE OR REPLACE FUNCTION public._support_kind_from_v1(p text)
5921
+ RETURNS text LANGUAGE sql IMMUTABLE SET search_path TO '' AS $fn$
5922
+ SELECT CASE WHEN p IN ('question', 'problem', 'improvement', 'other', 'chat') THEN p ELSE 'problem' END;
5923
+ $fn$;
5924
+ CREATE OR REPLACE FUNCTION public._support_priority_from_v1(p text)
5925
+ RETURNS text LANGUAGE sql IMMUTABLE SET search_path TO '' AS $fn$
5926
+ SELECT CASE p WHEN 'critical' THEN 'urgent' WHEN 'high' THEN 'high' WHEN 'low' THEN 'low' ELSE 'normal' END;
5927
+ $fn$;
5928
+ -- Autor de uma mensagem P\xDABLICA do V1 \u2192 a linha da thread: (dire\xE7\xE3o, sender_kind, autor padr\xE3o).
5929
+ -- Cliente entra; atendente do V1 sai como pessoa (conta como resposta da equipe);
5930
+ -- assistente (ai) e sistema saem como automa\xE7\xE3o (n\xE3o contam).
5931
+ CREATE OR REPLACE FUNCTION public._support_v1_author(p_kind text)
5932
+ RETURNS text[] LANGUAGE sql IMMUTABLE SET search_path TO '' AS $fn$
5933
+ SELECT CASE p_kind
5934
+ WHEN 'customer' THEN ARRAY['inbound', NULL, 'Solicitante']
5935
+ WHEN 'agent' THEN ARRAY['outbound', 'user', 'Equipe de Suporte (V1)']
5936
+ WHEN 'ai' THEN ARRAY['outbound', 'ai', 'Assistente (V1)']
5937
+ ELSE ARRAY['outbound', 'system', 'Sistema (V1)'] END;
5938
+ $fn$;
5939
+ -- O hist\xF3rico do V1 (support_ticket_events) \u2192 o do V2: (tipo, nota) ou NULL (fica de fora).
5940
+ CREATE OR REPLACE FUNCTION public._support_v1_event(p_event text, p_to text, p_note text)
5941
+ RETURNS text[] LANGUAGE sql IMMUTABLE SET search_path TO '' AS $fn$
5942
+ SELECT CASE p_event
5943
+ WHEN 'status_changed' THEN CASE WHEN public._support_status_from_v1(p_to) IS NOT NULL
5944
+ THEN ARRAY['status_changed', public._support_status_from_v1(p_to)] END
5945
+ WHEN 'validated' THEN ARRAY['validated_ok', NULL]
5946
+ WHEN 'reopened' THEN ARRAY['reopened', nullif(btrim(coalesce(p_note, '')), '')]
5947
+ WHEN 'marked_duplicate' THEN ARRAY['marked_duplicate', NULL]
5948
+ WHEN 'auto_closed' THEN ARRAY['closed_no_reply', NULL]
5949
+ END;
5950
+ $fn$;
5951
+ REVOKE ALL ON FUNCTION public._support_kind_from_v1(text), public._support_priority_from_v1(text),
5952
+ public._support_v1_author(text), public._support_v1_event(text, text, text)
5953
+ FROM PUBLIC, anon, authenticated;
5954
+ GRANT EXECUTE ON FUNCTION public._support_kind_from_v1(text), public._support_priority_from_v1(text),
5955
+ public._support_v1_author(text), public._support_v1_event(text, text, text)
5956
+ TO service_role;
5957
+
5958
+ CREATE OR REPLACE FUNCTION public._support_ts(p text)
5959
+ RETURNS timestamptz LANGUAGE plpgsql STABLE SET search_path TO '' AS $fn$
5960
+ BEGIN
5961
+ RETURN nullif(btrim(coalesce(p, '')), '')::timestamptz;
5962
+ EXCEPTION WHEN OTHERS THEN
5963
+ RETURN NULL;
5964
+ END;
5965
+ $fn$;
5966
+ REVOKE ALL ON FUNCTION public._support_ts(text) FROM PUBLIC, anon, authenticated;
5967
+ GRANT EXECUTE ON FUNCTION public._support_ts(text) TO service_role;
5968
+
5969
+ -- A \xFAltima vez que a importa\xE7\xE3o escreveu o chamado (a primeira ou uma segunda
5970
+ -- passada). updated_at depois disso = algu\xE9m mexeu no V2 (o carimbo respeita o
5971
+ -- hor\xE1rio do V1 dentro da importa\xE7\xE3o).
5972
+ CREATE OR REPLACE FUNCTION public._support_import_v1_mark(p_imported timestamptz, p_metadata jsonb)
5973
+ RETURNS timestamptz LANGUAGE sql STABLE SET search_path TO '' AS $fn$
5974
+ SELECT greatest(p_imported, public._support_ts(p_metadata #>> '{imported,synced_at}'));
5975
+ $fn$;
5976
+ REVOKE ALL ON FUNCTION public._support_import_v1_mark(timestamptz, jsonb) FROM PUBLIC, anon, authenticated;
5977
+ GRANT EXECUTE ON FUNCTION public._support_import_v1_mark(timestamptz, jsonb) TO service_role;
5978
+
5979
+ -- Algu\xE9m mexeu no chamado importado, no V2, depois da \xFAltima passada? Mudan\xE7a
5980
+ -- (updated_at depois da marca), mensagem da thread que n\xE3o veio do V1, nota ou
5981
+ -- anexo do V2, ou a thread dividida com outro chamado. A segunda passada n\xE3o
5982
+ -- sobrescreve o andamento dele; o desfazer n\xE3o o remove.
5983
+ CREATE OR REPLACE FUNCTION public._support_import_v1_touched(p_request_id uuid)
5984
+ RETURNS boolean
5985
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''
5986
+ AS $fn$
5987
+ SELECT q.updated_at > public._support_import_v1_mark(q.imported_at, q.metadata)
5988
+ OR EXISTS (SELECT 1 FROM public.plg_conversation_messages cm
5989
+ WHERE cm.conversation_id = q.conversation_id
5990
+ AND (cm.provider_message_id IS NULL OR cm.provider_message_id NOT LIKE 'v1:' || q.external_env || ':%'))
5991
+ OR EXISTS (SELECT 1 FROM public.plg_support_request_notes n WHERE n.request_id = q.id AND n.external_message_id IS NULL)
5992
+ OR EXISTS (SELECT 1 FROM public.plg_support_request_attachments a WHERE a.request_id = q.id AND a.external_attachment_id IS NULL)
5993
+ OR EXISTS (SELECT 1 FROM public.plg_support_requests o WHERE o.conversation_id = q.conversation_id AND o.id <> q.id)
5994
+ FROM public.plg_support_requests q
5995
+ WHERE q.id = p_request_id AND q.imported_at IS NOT NULL;
5996
+ $fn$;
5997
+ REVOKE ALL ON FUNCTION public._support_import_v1_touched(uuid) FROM PUBLIC, anon, authenticated;
5998
+ GRANT EXECUTE ON FUNCTION public._support_import_v1_touched(uuid) TO service_role;
5999
+
6000
+ -- \u2500\u2500 importar um chamado \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
6001
+ -- p_payload (o script monta a partir das tabelas do V1, vocabul\xE1rio do V1):
6002
+ -- { env, ticket: { id, number, license_id, license_uuid, kind, status, priority, subject, description,
6003
+ -- source, product_key, area, route, unit_name, tenant_name, opened_by_name, opened_by_email,
6004
+ -- origin_conversation_id, dev_reference, first_reply_at, resolved_at, closed_at,
6005
+ -- created_at, updated_at, last_activity_at },
6006
+ -- messages: [{ id, author_kind, author_name, body, internal, created_at }],
6007
+ -- attachments: [{ id, name, mime, size, created_at, expires_at, storage_deleted_at,
6008
+ -- location: 'v1'|'v2', v1_path, storage_path (s\xF3 'v2') }],
6009
+ -- events: [{ event, to_value, note, created_at }] }
6010
+ CREATE OR REPLACE FUNCTION public.support_import_v1_ticket(p_tenant uuid, p_payload jsonb)
6011
+ RETURNS jsonb
6012
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
6013
+ AS $fn$
6014
+ DECLARE
6015
+ v_env text := p_payload ->> 'env';
6016
+ v_t jsonb := coalesce(p_payload -> 'ticket', '{}'::jsonb);
6017
+ v_tid text := nullif(btrim(coalesce(p_payload #>> '{ticket,id}', '')), '');
6018
+ v_home uuid;
6019
+ v_bad text[];
6020
+ v_req record;
6021
+ v_id uuid;
6022
+ v_action text;
6023
+ v_account uuid;
6024
+ v_status text;
6025
+ v_kind text;
6026
+ v_prio text;
6027
+ v_created timestamptz;
6028
+ v_updated timestamptz;
6029
+ v_first timestamptz;
6030
+ v_resolved timestamptz;
6031
+ v_number bigint;
6032
+ v_snap jsonb;
6033
+ v_conv uuid;
6034
+ v_conv_tenant uuid;
6035
+ m jsonb;
6036
+ a jsonb;
6037
+ e jsonb;
6038
+ v_auth text[];
6039
+ v_ev text[];
6040
+ v_msg uuid;
6041
+ v_msgs integer := 0;
6042
+ v_notes integer := 0;
6043
+ v_atts integer := 0;
6044
+ v_at timestamptz;
6045
+ v_loc text;
6046
+ v_path text;
6047
+ v_last record;
6048
+ BEGIN
6049
+ IF v_env IS NULL OR v_env NOT IN ('sandbox', 'production') THEN
6050
+ RAISE EXCEPTION 'invalid env %', coalesce(v_env, '?') USING ERRCODE = '22023';
6051
+ END IF;
6052
+ IF v_tid IS NULL OR v_tid !~ '^[0-9a-fA-F-]{36}$' THEN
6053
+ RAISE EXCEPTION 'ticket.id must be the V1 uuid' USING ERRCODE = '22023';
6054
+ END IF;
6055
+ v_created := public._support_ts(v_t ->> 'created_at');
6056
+ IF v_created IS NULL THEN RAISE EXCEPTION 'ticket % without created_at', v_tid USING ERRCODE = '22023'; END IF;
6057
+ IF p_tenant IS NULL OR NOT EXISTS (SELECT 1 FROM public.tenants t WHERE t.id = p_tenant) THEN
6058
+ RAISE EXCEPTION 'tenant not found' USING ERRCODE = 'P0002';
6059
+ END IF;
6060
+ IF NOT public._support_is_console_tenant(p_tenant) THEN
6061
+ RAISE EXCEPTION 'tenant does not run the support console' USING ERRCODE = '42501';
6062
+ END IF;
6063
+ -- O mesmo par da ponte (customer-success 003/006): produ\xE7\xE3o s\xF3 na plataforma de casa; sandbox nunca nela.
6064
+ IF to_regprocedure('public.customer_success_home_platform()') IS NOT NULL THEN
6065
+ EXECUTE 'SELECT public.customer_success_home_platform()' INTO v_home;
6066
+ IF v_home IS NOT NULL AND (v_env = 'production') <> (p_tenant = v_home) THEN
6067
+ RAISE EXCEPTION 'a % ticket cannot land on this tenant', v_env USING ERRCODE = '42501';
6068
+ END IF;
6069
+ END IF;
6070
+ v_bad := public._support_import_v1_unaudited_triggers();
6071
+ IF cardinality(v_bad) > 0 THEN
6072
+ RAISE EXCEPTION 'unaudited triggers on the import tables: %', array_to_string(v_bad, ', ')
6073
+ USING ERRCODE = '55000', HINT = 'audit them and add to _support_import_v1_audited_triggers() in a migration';
6074
+ END IF;
6075
+ IF to_regclass('public.plg_conversations') IS NULL THEN
6076
+ RAISE EXCEPTION 'plugin-conversations is not applied: the ticket thread has nowhere to live' USING ERRCODE = '55000';
6077
+ END IF;
6078
+
6079
+ -- Nada do que acontece aqui sai daqui (011 + 040).
6080
+ PERFORM set_config('fayz.support_bridge_ingest', 'on', true);
6081
+ PERFORM set_config('fayz.support_import', 'on', true);
6082
+
6083
+ SELECT q.id, q.tenant_id, q.status, q.imported_at, q.conversation_id, q.external_account_id, q.updated_at, q.first_reply_at,
6084
+ coalesce(public._support_import_v1_touched(q.id), false) AS touched
6085
+ INTO v_req
6086
+ FROM public.plg_support_requests q
6087
+ WHERE q.external_source = 'v1' AND q.external_env = v_env AND q.external_ticket_id = v_tid
6088
+ FOR UPDATE;
6089
+ IF FOUND AND (v_req.imported_at IS NULL OR v_req.tenant_id <> p_tenant) THEN
6090
+ PERFORM set_config('fayz.support_import', '', true);
6091
+ PERFORM set_config('fayz.support_bridge_ingest', '', true);
6092
+ RETURN jsonb_build_object('ticket_id', v_tid, 'request_id', v_req.id, 'action', 'skipped',
6093
+ 'reason', CASE WHEN v_req.imported_at IS NULL THEN 'bridge' ELSE 'other_tenant' END);
6094
+ END IF;
6095
+
6096
+ -- A conta espelho da licen\xE7a (customer-success 003), se existir. Nunca criada aqui.
6097
+ IF to_regclass('public.plg_customer_success_external_accounts') IS NOT NULL THEN
6098
+ EXECUTE 'SELECT e.id FROM public.plg_customer_success_external_accounts e
6099
+ WHERE e.tenant_id = $1 AND e.source = ''v1'' AND e.env = $2
6100
+ AND (e.external_uuid = $3 OR ($3 IS NULL AND e.external_id = $4))
6101
+ ORDER BY (e.external_uuid = $3) DESC NULLS LAST, e.created_at LIMIT 1'
6102
+ INTO v_account
6103
+ USING p_tenant, v_env,
6104
+ CASE WHEN (v_t ->> 'license_uuid') ~ '^[0-9a-fA-F-]{36}$' THEN (v_t ->> 'license_uuid')::uuid END,
6105
+ CASE WHEN (v_t ->> 'license_id') ~ '^[0-9]{1,18}$' THEN (v_t ->> 'license_id')::bigint END;
6106
+ END IF;
6107
+
6108
+ v_status := coalesce(public._support_status_from_v1(v_t ->> 'status'), 'received');
6109
+ v_kind := public._support_kind_from_v1(v_t ->> 'kind');
6110
+ v_prio := public._support_priority_from_v1(v_t ->> 'priority');
6111
+ v_number := CASE WHEN (v_t ->> 'number') ~ '^[0-9]{1,15}$' THEN (v_t ->> 'number')::bigint END;
6112
+ v_updated := greatest(v_created, public._support_ts(v_t ->> 'updated_at'), public._support_ts(v_t ->> 'last_activity_at'));
6113
+ -- A primeira resposta: a do V1; sem ela, a primeira mensagem p\xFAblica de um atendente.
6114
+ v_first := coalesce(public._support_ts(v_t ->> 'first_reply_at'),
6115
+ (SELECT min(public._support_ts(x ->> 'created_at'))
6116
+ FROM jsonb_array_elements(coalesce(p_payload -> 'messages', '[]'::jsonb)) x
6117
+ WHERE x ->> 'author_kind' = 'agent' AND coalesce((x ->> 'internal')::boolean, false) = false));
6118
+ v_resolved := CASE WHEN v_status IN ('resolved_check', 'closed')
6119
+ THEN coalesce(public._support_ts(v_t ->> 'resolved_at'), public._support_ts(v_t ->> 'closed_at'), v_updated) END;
6120
+ -- O retrato da ponte (011) + a licen\xE7a e a marca da migra\xE7\xE3o.
6121
+ v_snap := jsonb_strip_nulls(jsonb_build_object(
6122
+ 'env', v_env, 'number', v_number,
6123
+ 'tenant_name', nullif(btrim(coalesce(v_t ->> 'tenant_name', '')), ''),
6124
+ 'unit_name', nullif(btrim(coalesce(v_t ->> 'unit_name', '')), ''),
6125
+ 'opened_by_name', nullif(btrim(coalesce(v_t ->> 'opened_by_name', '')), ''),
6126
+ 'opened_by_email', nullif(btrim(coalesce(v_t ->> 'opened_by_email', '')), ''),
6127
+ 'product', nullif(btrim(coalesce(v_t ->> 'product_key', '')), ''),
6128
+ 'area', nullif(btrim(coalesce(v_t ->> 'area', '')), ''),
6129
+ 'channel', nullif(btrim(coalesce(v_t ->> 'source', '')), ''),
6130
+ 'origin_conversation_id', nullif(btrim(coalesce(v_t ->> 'origin_conversation_id', '')), ''),
6131
+ 'license_id', CASE WHEN (v_t ->> 'license_id') ~ '^[0-9]{1,18}$' THEN (v_t ->> 'license_id')::bigint END,
6132
+ 'license_uuid', nullif(btrim(coalesce(v_t ->> 'license_uuid', '')), ''),
6133
+ 'v1_status', nullif(btrim(coalesce(v_t ->> 'status', '')), '')));
6134
+
6135
+ IF v_req.id IS NULL THEN
6136
+ INSERT INTO public.plg_support_requests (
6137
+ tenant_id, kind, subject, description, status, priority, route, created_by, created_at, updated_at,
6138
+ resolved_at, first_reply_at, area, dev_reference, metadata,
6139
+ external_source, external_env, external_ticket_id, external_account_id, imported_at
6140
+ ) VALUES (
6141
+ p_tenant, v_kind,
6142
+ coalesce(nullif(btrim(coalesce(v_t ->> 'subject', '')), ''),
6143
+ CASE WHEN v_number IS NOT NULL THEN 'Chamado #' || v_number || ' do V1' ELSE 'Chamado do V1' END),
6144
+ coalesce(nullif(btrim(coalesce(v_t ->> 'description', '')), ''), nullif(btrim(coalesce(v_t ->> 'subject', '')), ''), 'Chamado aberto no V1.'),
6145
+ v_status, v_prio,
6146
+ nullif(btrim(coalesce(v_t ->> 'route', '')), ''),
6147
+ NULL, v_created, v_updated,
6148
+ v_resolved, v_first,
6149
+ nullif(btrim(coalesce(v_t ->> 'area', '')), ''),
6150
+ nullif(btrim(coalesce(v_t ->> 'dev_reference', '')), ''),
6151
+ jsonb_build_object('source', 'v1', 'external', v_snap,
6152
+ 'imported', jsonb_build_object('at', now(), 'by', 'support-migrate-v1-tickets')),
6153
+ 'v1', v_env, v_tid, v_account, now()
6154
+ )
6155
+ RETURNING id INTO v_id;
6156
+ v_action := 'created';
6157
+
6158
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note, created_at)
6159
+ VALUES (p_tenant, v_id, 'opened', 'Aberta no V1', v_created);
6160
+ FOR e IN SELECT x FROM jsonb_array_elements(coalesce(p_payload -> 'events', '[]'::jsonb)) x
6161
+ ORDER BY public._support_ts(x ->> 'created_at') NULLS LAST LOOP
6162
+ v_ev := public._support_v1_event(e ->> 'event', e ->> 'to_value', e ->> 'note');
6163
+ v_at := public._support_ts(e ->> 'created_at');
6164
+ IF v_ev IS NOT NULL AND v_at IS NOT NULL THEN
6165
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note, created_at)
6166
+ VALUES (p_tenant, v_id, v_ev[1], v_ev[2], v_at);
6167
+ END IF;
6168
+ END LOOP;
6169
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note, created_at)
6170
+ VALUES (p_tenant, v_id, 'imported', 'Migrado do V1', now());
6171
+ ELSE
6172
+ -- Segunda passada: acompanha o V1 (andamento, conta que apareceu) e acrescenta o que faltar.
6173
+ -- Um chamado que a equipe j\xE1 mexeu no V2 mant\xE9m o andamento do V2 (s\xF3 ganha mensagens).
6174
+ v_id := v_req.id;
6175
+ v_action := CASE WHEN v_req.touched THEN 'synced_touched' ELSE 'synced' END;
6176
+ IF v_status IS DISTINCT FROM v_req.status AND NOT v_req.touched THEN
6177
+ UPDATE public.plg_support_requests
6178
+ SET status = v_status, resolved_at = v_resolved, updated_at = greatest(v_req.updated_at, v_updated)
6179
+ WHERE id = v_id;
6180
+ INSERT INTO public.plg_support_request_events (tenant_id, request_id, type, note, created_at)
6181
+ VALUES (p_tenant, v_id, 'status_changed', v_status, greatest(v_req.updated_at, v_updated));
6182
+ END IF;
6183
+ UPDATE public.plg_support_requests q
6184
+ SET external_account_id = coalesce(q.external_account_id, v_account),
6185
+ first_reply_at = coalesce(q.first_reply_at, v_first),
6186
+ metadata = jsonb_set(q.metadata, '{imported,synced_at}', to_jsonb(now()))
6187
+ WHERE q.id = v_id;
6188
+ END IF;
6189
+
6190
+ -- A thread: a mesma forma da que a ponte cria (011/024).
6191
+ v_conv := public._support_ensure_thread(v_id, p_tenant);
6192
+ IF v_conv IS NULL THEN RAISE EXCEPTION 'thread not created for ticket %', v_tid USING ERRCODE = '55000'; END IF;
6193
+ SELECT c.tenant_id INTO v_conv_tenant FROM public.plg_conversations c WHERE c.id = v_conv;
6194
+
6195
+ -- As mensagens, em ordem. P\xFAblica \u2192 thread (forma neutra + UPDATE); interna \u2192 nota da central.
6196
+ FOR m IN SELECT x FROM jsonb_array_elements(coalesce(p_payload -> 'messages', '[]'::jsonb)) x
6197
+ ORDER BY public._support_ts(x ->> 'created_at') NULLS FIRST, x ->> 'id' LOOP
6198
+ CONTINUE WHEN coalesce(btrim(m ->> 'body'), '') = '' OR coalesce(m ->> 'id', '') = '';
6199
+ v_at := coalesce(public._support_ts(m ->> 'created_at'), v_created);
6200
+ IF coalesce((m ->> 'internal')::boolean, false) THEN
6201
+ INSERT INTO public.plg_support_request_notes (tenant_id, request_id, author_id, author_name, body, created_at, external_message_id)
6202
+ VALUES (p_tenant, v_id, NULL,
6203
+ left(coalesce(nullif(btrim(coalesce(m ->> 'author_name', '')), ''), 'Equipe de Suporte (V1)'), 120) || ' (V1)',
6204
+ left(m ->> 'body', 20000), v_at, m ->> 'id')
6205
+ ON CONFLICT (request_id, external_message_id) WHERE external_message_id IS NOT NULL DO NOTHING
6206
+ RETURNING id INTO v_msg;
6207
+ IF v_msg IS NOT NULL THEN v_notes := v_notes + 1; END IF;
6208
+ ELSE
6209
+ v_auth := public._support_v1_author(m ->> 'author_kind');
6210
+ v_msg := NULL;
6211
+ INSERT INTO public.plg_conversation_messages
6212
+ (tenant_id, conversation_id, channel, direction, body, author, at, provider_message_id, sender_kind)
6213
+ VALUES (v_conv_tenant, v_conv, NULL, NULL, left(m ->> 'body', 20000),
6214
+ left(coalesce(nullif(btrim(coalesce(m ->> 'author_name', '')), ''), v_auth[3]), 120),
6215
+ v_at, 'v1:' || v_env || ':' || (m ->> 'id'), NULL)
6216
+ ON CONFLICT (provider_message_id) WHERE provider_message_id IS NOT NULL DO NOTHING
6217
+ RETURNING id INTO v_msg;
6218
+ IF v_msg IS NOT NULL THEN
6219
+ UPDATE public.plg_conversation_messages
6220
+ SET channel = 'support', direction = v_auth[1], sender_kind = v_auth[2]
6221
+ WHERE id = v_msg;
6222
+ v_msgs := v_msgs + 1;
6223
+ END IF;
6224
+ END IF;
6225
+ END LOOP;
6226
+
6227
+ -- A thread fica como o hist\xF3rico deixou: \xFAltima mensagem, sem "n\xE3o lidas" (\xE9 hist\xF3rico).
6228
+ SELECT cm.body, cm.at, cm.direction INTO v_last
6229
+ FROM public.plg_conversation_messages cm
6230
+ WHERE cm.conversation_id = v_conv AND cm.direction IS NOT NULL
6231
+ ORDER BY cm.at DESC, cm.id DESC LIMIT 1;
6232
+ UPDATE public.plg_conversations c
6233
+ SET last_message_preview = CASE WHEN v_last.body IS NOT NULL THEN left(v_last.body, 280) ELSE c.last_message_preview END,
6234
+ last_message_at = coalesce(v_last.at, c.last_message_at),
6235
+ last_message_direction = coalesce(v_last.direction, c.last_message_direction),
6236
+ unread_count = 0,
6237
+ status = CASE WHEN v_status IN ('closed', 'cancelled') THEN 'closed' ELSE 'open' END
6238
+ WHERE c.id = v_conv;
6239
+
6240
+ -- Os anexos p\xFAblicos.
6241
+ FOR a IN SELECT x FROM jsonb_array_elements(coalesce(p_payload -> 'attachments', '[]'::jsonb)) x LOOP
6242
+ CONTINUE WHEN coalesce(a ->> 'id', '') = '' OR coalesce(btrim(a ->> 'name'), '') = '';
6243
+ v_loc := CASE WHEN a ->> 'location' = 'v2' THEN 'v2' ELSE 'v1' END;
6244
+ IF v_loc = 'v2' THEN
6245
+ v_path := a ->> 'storage_path';
6246
+ -- O arquivo copiado mora na pasta do tenant (a pol\xEDtica do bucket, 000/003).
6247
+ IF v_path IS NULL OR v_path NOT LIKE p_tenant::text || '/%' OR v_path LIKE '%..%' THEN
6248
+ RAISE EXCEPTION 'attachment % of ticket %: copied path outside the tenant folder', a ->> 'id', v_tid USING ERRCODE = '22023';
6249
+ END IF;
6250
+ ELSE
6251
+ v_path := 'v1:' || coalesce(nullif(a ->> 'v1_path', ''), a ->> 'id');
6252
+ END IF;
6253
+ v_msg := NULL;
6254
+ INSERT INTO public.plg_support_request_attachments
6255
+ (tenant_id, request_id, storage_path, name, size_bytes, content_type, created_by, created_at,
6256
+ expires_at, storage_deleted_at, external_attachment_id, location)
6257
+ VALUES (p_tenant, v_id, v_path, left(a ->> 'name', 255),
6258
+ CASE WHEN (a ->> 'size') ~ '^[0-9]{1,15}$' THEN (a ->> 'size')::bigint END,
6259
+ nullif(a ->> 'mime', ''), NULL,
6260
+ coalesce(public._support_ts(a ->> 'created_at'), v_created),
6261
+ -- 'v1': o arquivo n\xE3o \xE9 nosso; a limpeza (013) nunca o alcan\xE7a.
6262
+ CASE WHEN v_loc = 'v1' THEN 'infinity'::timestamptz ELSE public._support_ts(a ->> 'expires_at') END,
6263
+ public._support_ts(a ->> 'storage_deleted_at'),
6264
+ a ->> 'id', v_loc)
6265
+ ON CONFLICT (request_id, external_attachment_id) WHERE external_attachment_id IS NOT NULL
6266
+ DO UPDATE SET storage_path = EXCLUDED.storage_path, location = EXCLUDED.location, expires_at = EXCLUDED.expires_at
6267
+ WHERE public.plg_support_request_attachments.location = 'v1' AND EXCLUDED.location = 'v2'
6268
+ RETURNING id INTO v_msg;
6269
+ IF v_msg IS NOT NULL THEN v_atts := v_atts + 1; END IF;
6270
+ END LOOP;
6271
+
6272
+ PERFORM set_config('fayz.support_import', '', true);
6273
+ PERFORM set_config('fayz.support_bridge_ingest', '', true);
6274
+ RETURN jsonb_build_object('ticket_id', v_tid, 'request_id', v_id, 'action', v_action, 'conversation_id', v_conv,
6275
+ 'messages_added', v_msgs, 'notes_added', v_notes, 'attachments_added', v_atts,
6276
+ 'account', v_account IS NOT NULL);
6277
+ END;
6278
+ $fn$;
6279
+ REVOKE ALL ON FUNCTION public.support_import_v1_ticket(uuid, jsonb) FROM PUBLIC, anon, authenticated;
6280
+ GRANT EXECUTE ON FUNCTION public.support_import_v1_ticket(uuid, jsonb) TO service_role;
6281
+
6282
+ -- \u2500\u2500 desfazer \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
6283
+ -- S\xF3 o que tem marca de importado, no tenant e ambiente dados, e que ningu\xE9m
6284
+ -- tocou depois: o chamado n\xE3o mudou no V2 (updated_at \u2264 imported_at, o carimbo
6285
+ -- respeita o hor\xE1rio do V1 na importa\xE7\xE3o), a thread s\xF3 tem mensagens importadas
6286
+ -- e n\xE3o h\xE1 nota nem anexo do V2. O tocado fica e \xE9 contado. p_apply = false: a
6287
+ -- pr\xE9via (nada muda). Devolve os caminhos dos arquivos COPIADOS (location 'v2')
6288
+ -- dos chamados removidos \u2014 o Storage n\xE3o se apaga por SQL; o script apaga.
6289
+ CREATE OR REPLACE FUNCTION public.support_import_v1_rollback(p_tenant uuid, p_env text, p_apply boolean DEFAULT false)
6290
+ RETURNS jsonb
6291
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
6292
+ AS $fn$
6293
+ DECLARE
6294
+ v_ids uuid[];
6295
+ v_kept integer;
6296
+ v_convs uuid[];
6297
+ v_paths text[];
6298
+ v_msgs bigint;
6299
+ v_notes bigint;
6300
+ v_atts bigint;
6301
+ v_total integer;
6302
+ BEGIN
6303
+ IF p_env IS NULL OR p_env NOT IN ('sandbox', 'production') THEN
6304
+ RAISE EXCEPTION 'invalid env %', coalesce(p_env, '?') USING ERRCODE = '22023';
6305
+ END IF;
6306
+ IF p_tenant IS NULL OR NOT EXISTS (SELECT 1 FROM public.tenants t WHERE t.id = p_tenant) THEN
6307
+ RAISE EXCEPTION 'tenant not found' USING ERRCODE = 'P0002';
6308
+ END IF;
6309
+
6310
+ WITH imp AS (
6311
+ SELECT q.id, q.conversation_id, coalesce(public._support_import_v1_touched(q.id), false) AS touched
6312
+ FROM public.plg_support_requests q
6313
+ WHERE q.tenant_id = p_tenant AND q.external_source = 'v1' AND q.external_env = p_env AND q.imported_at IS NOT NULL
6314
+ )
6315
+ SELECT (SELECT count(*) FROM imp)::integer,
6316
+ (SELECT count(*) FROM imp WHERE touched)::integer,
6317
+ (SELECT array_agg(i.id) FROM imp i WHERE NOT i.touched),
6318
+ (SELECT array_agg(i.conversation_id) FROM imp i WHERE NOT i.touched AND i.conversation_id IS NOT NULL)
6319
+ INTO v_total, v_kept, v_ids, v_convs;
6320
+
6321
+ v_ids := coalesce(v_ids, '{}'::uuid[]);
6322
+ v_convs := coalesce(v_convs, '{}'::uuid[]);
6323
+ SELECT count(*) INTO v_msgs FROM public.plg_conversation_messages cm WHERE cm.conversation_id = ANY (v_convs);
6324
+ SELECT count(*) INTO v_notes FROM public.plg_support_request_notes n WHERE n.request_id = ANY (v_ids);
6325
+ SELECT count(*), coalesce(array_agg(at.storage_path) FILTER (WHERE at.location = 'v2'), '{}'::text[])
6326
+ INTO v_atts, v_paths
6327
+ FROM public.plg_support_request_attachments at WHERE at.request_id = ANY (v_ids);
6328
+
6329
+ IF p_apply AND cardinality(v_ids) > 0 THEN
6330
+ PERFORM set_config('fayz.support_bridge_ingest', 'on', true);
6331
+ PERFORM set_config('fayz.support_import', 'on', true);
6332
+ DELETE FROM public.plg_support_requests q WHERE q.id = ANY (v_ids); -- eventos, notas, anexos: CASCADE
6333
+ DELETE FROM public.plg_conversations c WHERE c.id = ANY (v_convs); -- mensagens: CASCADE
6334
+ PERFORM set_config('fayz.support_import', '', true);
6335
+ PERFORM set_config('fayz.support_bridge_ingest', '', true);
6336
+ END IF;
6337
+
6338
+ RETURN jsonb_build_object('applied', p_apply AND cardinality(v_ids) > 0,
6339
+ 'imported', v_total, 'kept_touched', v_kept, 'removable', cardinality(v_ids),
6340
+ 'conversations', cardinality(v_convs), 'messages', v_msgs, 'notes', v_notes,
6341
+ 'attachments', v_atts, 'copied_files', to_jsonb(v_paths));
6342
+ END;
6343
+ $fn$;
6344
+ REVOKE ALL ON FUNCTION public.support_import_v1_rollback(uuid, text, boolean) FROM PUBLIC, anon, authenticated;
6345
+ GRANT EXECUTE ON FUNCTION public.support_import_v1_rollback(uuid, text, boolean) TO service_role;
6346
+
6347
+ -- \u2500\u2500 o selo do quadro \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
6348
+ -- Os ids dos chamados importados que o quadro mostra (os mesmos recortes de
6349
+ -- support_console_board: abertos + encerrados h\xE1 at\xE9 14 dias). O quadro marca
6350
+ -- "migrado do V1" neles; o painel l\xEA imported_at do detalhe.
6351
+ CREATE OR REPLACE FUNCTION public.support_console_imported_ids()
6352
+ RETURNS uuid[]
6353
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
6354
+ AS $fn$
6355
+ DECLARE v uuid[];
6356
+ BEGIN
6357
+ PERFORM public.support_console_guard();
6358
+ SELECT coalesce(array_agg(q.id), '{}'::uuid[]) INTO v
6359
+ FROM public.plg_support_requests q
6360
+ WHERE q.imported_at IS NOT NULL
6361
+ AND (q.status NOT IN ('closed', 'cancelled') OR q.updated_at >= now() - interval '14 days');
6362
+ RETURN v;
6363
+ END;
6364
+ $fn$;
6365
+ REVOKE ALL ON FUNCTION public.support_console_imported_ids() FROM PUBLIC, anon;
6366
+ GRANT EXECUTE ON FUNCTION public.support_console_imported_ids() TO authenticated;
6367
+ `;
5191
6368
  var MIGRATIONS = [
5192
6369
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
5193
6370
  { id: "001_helpdesk", sql: MIGRATION_001_HELPDESK },
@@ -5204,9 +6381,11 @@ var MIGRATIONS = [
5204
6381
  { id: "021_a_conversa_da_casa_do_v1_entra_na_fila", sql: MIGRATION_021_A_CONVERSA_DA_CASA_DO_V1_ENTRA_NA_FILA },
5205
6382
  { id: "022_o_aviso_vira_email_quando_ninguem_abre", sql: MIGRATION_022_O_AVISO_VIRA_EMAIL_QUANDO_NINGUEM_ABRE },
5206
6383
  { id: "023_a_resposta_ao_v1_assina_com_o_nome_da_pessoa", sql: MIGRATION_023_A_RESPOSTA_AO_V1_ASSINA_COM_O_NOME_DA_PESSOA },
5207
- { id: "024_o_atendente_conversa_pelo_chamado", sql: MIGRATION_024_O_ATENDENTE_CONVERSA_PELO_CHAMADO }
6384
+ { id: "024_o_atendente_conversa_pelo_chamado", sql: MIGRATION_024_O_ATENDENTE_CONVERSA_PELO_CHAMADO },
6385
+ { id: "030_o_chamado_da_casa_do_v1_nasce_no_v2", sql: MIGRATION_030_O_CHAMADO_DA_CASA_DO_V1_NASCE_NO_V2 },
6386
+ { id: "040_os_chamados_do_v1_migram_sem_avisar_ninguem", sql: MIGRATION_040_OS_CHAMADOS_DO_V1_MIGRAM_SEM_AVISAR_NINGUEM }
5208
6387
  ];
5209
6388
 
5210
- export { MIGRATIONS, MIGRATION_000_BASELINE, MIGRATION_001_HELPDESK, MIGRATION_002_OPERATOR_ATTACHMENT_READ, MIGRATION_003_OPERATOR_ATTACHMENT_READ_FIX, MIGRATION_004_A_CONVERSA_DO_CHAMADO_E_UMA_CONVERSA, MIGRATION_005_O_QUADRO_DO_ATENDIMENTO, MIGRATION_010_AS_CONFIGURACOES_DA_CENTRAL, MIGRATION_011_OS_CHAMADOS_DAS_CASAS_DO_V1, MIGRATION_012_SO_ATENDENTE_ESCREVE, MIGRATION_013_A_LIMPEZA_DOS_ANEXOS_FICA_DESLIGADA, MIGRATION_014_OS_ANEXOS_DO_V1_POR_LINK_ASSINADO, MIGRATION_020_A_CONVERSA_AO_VIVO_E_UMA_THREAD_DA_CAIXA, MIGRATION_021_A_CONVERSA_DA_CASA_DO_V1_ENTRA_NA_FILA, MIGRATION_022_O_AVISO_VIRA_EMAIL_QUANDO_NINGUEM_ABRE, MIGRATION_023_A_RESPOSTA_AO_V1_ASSINA_COM_O_NOME_DA_PESSOA, MIGRATION_024_O_ATENDENTE_CONVERSA_PELO_CHAMADO };
6389
+ export { MIGRATIONS, MIGRATION_000_BASELINE, MIGRATION_001_HELPDESK, MIGRATION_002_OPERATOR_ATTACHMENT_READ, MIGRATION_003_OPERATOR_ATTACHMENT_READ_FIX, MIGRATION_004_A_CONVERSA_DO_CHAMADO_E_UMA_CONVERSA, MIGRATION_005_O_QUADRO_DO_ATENDIMENTO, MIGRATION_010_AS_CONFIGURACOES_DA_CENTRAL, MIGRATION_011_OS_CHAMADOS_DAS_CASAS_DO_V1, MIGRATION_012_SO_ATENDENTE_ESCREVE, MIGRATION_013_A_LIMPEZA_DOS_ANEXOS_FICA_DESLIGADA, MIGRATION_014_OS_ANEXOS_DO_V1_POR_LINK_ASSINADO, MIGRATION_020_A_CONVERSA_AO_VIVO_E_UMA_THREAD_DA_CAIXA, MIGRATION_021_A_CONVERSA_DA_CASA_DO_V1_ENTRA_NA_FILA, MIGRATION_022_O_AVISO_VIRA_EMAIL_QUANDO_NINGUEM_ABRE, MIGRATION_023_A_RESPOSTA_AO_V1_ASSINA_COM_O_NOME_DA_PESSOA, MIGRATION_024_O_ATENDENTE_CONVERSA_PELO_CHAMADO, MIGRATION_030_O_CHAMADO_DA_CASA_DO_V1_NASCE_NO_V2, MIGRATION_040_OS_CHAMADOS_DO_V1_MIGRAM_SEM_AVISAR_NINGUEM };
5211
6390
  //# sourceMappingURL=main.js.map
5212
6391
  //# sourceMappingURL=main.js.map