@fayz-ai/plugin-clinical 0.2.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.
package/dist/index.js ADDED
@@ -0,0 +1,3487 @@
1
+ import { definePlugin } from '@fayz-ai/core';
2
+
3
+ // src/index.ts
4
+
5
+ // src/migrations/index.ts
6
+ var MIGRATION_001_O_ATENDIMENTO_CLINICO_TEM_ONDE_MORAR = `-- O atendimento cl\xEDnico tem onde morar.
7
+ --
8
+ -- 358.577 linhas do Espa\xE7o Facial n\xE3o tinham destino nenhum no V2 \u2014 96% de tudo
9
+ -- que ainda falta portar daquele tenant. N\xE3o era uma tabela esquecida: era um
10
+ -- DOM\xCDNIO inteiro sem casa.
11
+ --
12
+ -- journey_executions 233.934 a sess\xE3o de execu\xE7\xE3o
13
+ -- execution_products 117.011 o produto consumido na sess\xE3o
14
+ -- execution_requirements 6.590 o que trava come\xE7ar e terminar
15
+ -- service_revisions 110 a vers\xE3o do servi\xE7o (pre\xE7o, prazo)
16
+ -- service_revision_forms 87 os formul\xE1rios daquela vers\xE3o
17
+ -- prepaid_item_outcomes 30 o desfecho do item contratado
18
+ --
19
+ -- \u2500\u2500 Por que n\xE3o \xE9 a agenda \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
20
+ --
21
+ -- A agenda termina em QUEM, QUANDO e ONDE \u2014 \`appointments\` e
22
+ -- \`appointment_items\`, que j\xE1 atravessaram na migration 008. O que est\xE1 aqui \xE9
23
+ -- O QUE FOI FEITO, e tem ciclo de vida pr\xF3prio: revis\xE3o com pai
24
+ -- (\`parent_execution_id\`), requisitos que bloqueiam in\xEDcio e fim, consumo de
25
+ -- produto auditado contra o estoque, foto por pose.
26
+ --
27
+ -- A jornada est\xE1 documentada em
28
+ -- ~/dev/beautyplace/docs/v1-guide/jornadas/avaliacao-e-contratacao/FLOW.md
29
+ -- (\`v2.status: missing\`): anamnese COM VALIDADE \u2192 avalia\xE7\xE3o com desenho do rosto
30
+ -- e foto \u2192 indica\xE7\xE3o com quantidade \u2192 "o que o cliente deseja contratar" \u2192
31
+ -- contrato assinado e termo de sess\xE3o \u2192 executar s\xF3 o que couber hoje \u2192 r\xE9gua de
32
+ -- etapas com cron\xF4metro e evolu\xE7\xE3o cl\xEDnica.
33
+ --
34
+ -- \xC9 capacidade de VERTICAL (est\xE9tica, sa\xFAde), n\xE3o do n\xFAcleo. Por isso plugin
35
+ -- pr\xF3prio e entrada em \`optional\` no chain.json, como o workforce.
36
+ --
37
+ -- \u2500\u2500 O que N\xC3O \xE9 deste dom\xEDnio, apesar do nome \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
38
+ --
39
+ -- \`journeys\` e \`journey_steps\` compartilham o prefixo com \`journey_executions\` e
40
+ -- n\xE3o t\xEAm rela\xE7\xE3o nenhuma com ele: ZERO chave estrangeira entre os dois, e
41
+ -- \`journey_steps\` aponta para \`message_templates\` carregando \`wait_value\`,
42
+ -- \`channel\`, \`quiet_hours_start\` e \`cooldown_days\`. \xC9 automa\xE7\xE3o de COMUNICA\xC7\xC3O,
43
+ -- e o destino dela \xE9 \`plg_automations_flows\`, que j\xE1 existe. S\xE3o 7 linhas, e a
44
+ -- tela delas no V1 nem abre (V1-027).
45
+ --
46
+ -- \u2500\u2500 As colunas que ficaram para tr\xE1s, e por qu\xEA \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
47
+ --
48
+ -- Medido no tenant 1 em 21/09/2026:
49
+ --
50
+ -- \`execution_products.stock_deducted\` 0 de 117.015 verdadeiras
51
+ -- \`execution_products.stock_movement_id\` 0 preenchidas
52
+ -- \`execution_products.stock_position_id\` 0 preenchidas
53
+ -- \`position_allocations\` / \`unit_label_allocations\` 0 preenchidas
54
+ --
55
+ -- O consumo NUNCA deu baixa no estoque neste tenant. Isso n\xE3o \xE9 defeito do
56
+ -- porte: \xE9 o que o pr\xF3prio Guia do V1 descreve na jornada
57
+ -- \`auditoria-de-uso-e-estoque\`, onde a auditoria \xE9 port\xE3o PR\xC9-baixa e a baixa
58
+ -- fica pendurada. Trazer colunas vazias faria a tela do V2 afirmar que existe um
59
+ -- v\xEDnculo com o raz\xE3o que nunca existiu. O dia em que houver baixa, ela vira
60
+ -- \`plg_inventory_stock_movements\` com \`subject_id\` apontando para a sess\xE3o.
61
+ --
62
+ -- \`journey_executions.product_id\` 0 de 233.950 \u2014 coluna morta
63
+ -- \`journey_executions.status\` redundante com \`journey_status\`, que
64
+ -- \xE9 mais granular (separa quoted de
65
+ -- contracted). Vai para metadata.
66
+ -- \`execution_photos\` / \`consumption_photos\` s\xE3o ARQUIVO, e arquivo no V2 \xE9
67
+ -- \`public.documents\`. S\xE3o muitos por sess\xE3o, cada um com a sua pose, ent\xE3o o
68
+ -- v\xEDnculo \xE9 \`documents.subject_type\`/\`subject_id\` \u2014 e n\xE3o uma coluna de
69
+ -- array que nenhuma RLS de arquivo alcan\xE7a.
70
+ --
71
+ -- Idempotente.
72
+
73
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
74
+ -- 1. A sess\xE3o
75
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
76
+
77
+ CREATE TABLE IF NOT EXISTS public.plg_clinical_sessions (
78
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
79
+ tenant_id uuid NOT NULL,
80
+ unit_id uuid,
81
+ -- O \`journey_status\` do V1. Fechado num CHECK porque \xE9 vocabul\xE1rio de
82
+ -- plugin, n\xE3o arqu\xE9tipo \u2014 \`schedule_kinds\`/\`appointment_kinds\` s\xE3o registros
83
+ -- de esp\xE9cie, e uma sess\xE3o cl\xEDnica n\xE3o \xE9 esp\xE9cie de nada.
84
+ status text DEFAULT 'pending'::text NOT NULL,
85
+ -- O agendamento: 226.551 de 233.950 (96,8%). Os que faltam s\xE3o sess\xE3o sem
86
+ -- agenda \u2014 contratada e ainda n\xE3o marcada.
87
+ booking_id uuid,
88
+ -- O item do agendamento: 2.511 de 233.950. Raro no V1 e mantido assim: o
89
+ -- v\xEDnculo forte com o que foi vendido \xE9 \`order_item_id\`.
90
+ booking_item_id uuid,
91
+ party_id uuid,
92
+ -- Quem estava marcado e quem de fato executou s\xE3o duas perguntas. O V1
93
+ -- guarda as duas (\`professional_id\`, \`execution_professional_id\`) e a
94
+ -- segunda s\xF3 existe em 148.414 \u2014 \xE9 ela que a comiss\xE3o l\xEA.
95
+ assignee_id uuid,
96
+ performed_by_id uuid,
97
+ service_id uuid,
98
+ order_item_id uuid,
99
+ quote_item_id uuid,
100
+ -- 233.281 de 233.950 (99,7%) t\xEAm oportunidade. A sess\xE3o pendura no NEG\xD3CIO
101
+ -- antes de pendurar na agenda, e \xE9 por isso que ela existe para o que foi
102
+ -- or\xE7ado e nunca marcado.
103
+ deal_id uuid,
104
+ revision_number integer DEFAULT 1 NOT NULL,
105
+ parent_session_id uuid,
106
+ source_evaluation_id uuid,
107
+ scheduled_for date,
108
+ started_at timestamp with time zone,
109
+ ended_at timestamp with time zone,
110
+ products_initialized boolean DEFAULT false NOT NULL,
111
+ notes text,
112
+ metadata jsonb DEFAULT '{}'::jsonb NOT NULL,
113
+ owner_id uuid,
114
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
115
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
116
+ CONSTRAINT plg_clinical_sessions_status_check CHECK (status = ANY (ARRAY[
117
+ 'quoted'::text, 'contracted'::text, 'scheduled'::text, 'in_service'::text,
118
+ 'in_progress'::text, 'executed'::text, 'pending'::text])),
119
+ CONSTRAINT plg_clinical_sessions_revision_check CHECK (revision_number >= 1),
120
+ -- A sess\xE3o termina depois de come\xE7ar. O V1 n\xE3o cobra isso e por isso a
121
+ -- recusa vive no writer do porte, n\xE3o aqui \u2014 mas daqui para frente vale.
122
+ CONSTRAINT plg_clinical_sessions_window_check
123
+ CHECK (started_at IS NULL OR ended_at IS NULL OR ended_at >= started_at)
124
+ );
125
+
126
+ COMMENT ON TABLE public.plg_clinical_sessions IS
127
+ 'A sess\xE3o de execu\xE7\xE3o do atendimento cl\xEDnico. V1: journey_executions \u2014 que N\xC3O tem rela\xE7\xE3o com journeys, apesar do nome.';
128
+ COMMENT ON COLUMN public.plg_clinical_sessions.performed_by_id IS
129
+ 'V1: execution_professional_id \u2014 quem de fato executou, que pode n\xE3o ser quem estava marcado.';
130
+ COMMENT ON COLUMN public.plg_clinical_sessions.source_evaluation_id IS
131
+ 'V1: source_evaluation_execution_id \u2014 a avalia\xE7\xE3o que originou esta indica\xE7\xE3o.';
132
+
133
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
134
+ -- 2. O produto consumido
135
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
136
+
137
+ CREATE TABLE IF NOT EXISTS public.plg_clinical_session_products (
138
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
139
+ tenant_id uuid NOT NULL,
140
+ unit_id uuid,
141
+ session_id uuid NOT NULL,
142
+ product_id uuid NOT NULL,
143
+ order_item_id uuid,
144
+ assignee_id uuid,
145
+ -- O "Padr\xE3o: N" da ficha t\xE9cnica contra o que a profissional realmente usou.
146
+ -- \xC9 a diferen\xE7a entre os dois que a auditoria de consumo l\xEA.
147
+ default_quantity numeric(14,4),
148
+ used_quantity numeric(14,4),
149
+ used_unit_id uuid,
150
+ executed_on date,
151
+ is_audited boolean DEFAULT false NOT NULL,
152
+ audited_at timestamp with time zone,
153
+ audited_by uuid,
154
+ audit_notes text,
155
+ metadata jsonb DEFAULT '{}'::jsonb NOT NULL,
156
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
157
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
158
+ CONSTRAINT plg_clinical_session_products_qty_check
159
+ CHECK (used_quantity IS NULL OR used_quantity >= 0)
160
+ );
161
+
162
+ COMMENT ON TABLE public.plg_clinical_session_products IS
163
+ 'O produto consumido na sess\xE3o, com o padr\xE3o da ficha t\xE9cnica ao lado do usado. V1: execution_products. As colunas de baixa de estoque n\xE3o vieram: 0 de 117.015 estavam preenchidas.';
164
+
165
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
166
+ -- 3. O que trava come\xE7ar e terminar
167
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
168
+
169
+ CREATE TABLE IF NOT EXISTS public.plg_clinical_requirements (
170
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
171
+ tenant_id uuid NOT NULL,
172
+ unit_id uuid,
173
+ session_id uuid,
174
+ booking_id uuid,
175
+ party_id uuid,
176
+ service_id uuid,
177
+ kind text NOT NULL,
178
+ scope text NOT NULL,
179
+ -- As duas travas do V1, e elas s\xE3o diferentes: a anamnese impede COME\xC7AR, o
180
+ -- termo de sess\xE3o impede TERMINAR. 1.107 e 1.023 linhas no tenant 1.
181
+ blocks_start boolean DEFAULT false NOT NULL,
182
+ blocks_finish boolean DEFAULT false NOT NULL,
183
+ status text DEFAULT 'pending'::text NOT NULL,
184
+ -- O que resolveu a exig\xEAncia \xE9 polim\xF3rfico no V1 (\`resolved_table\` +
185
+ -- \`resolved_id\`) e continua sendo aqui, com o mesmo par que
186
+ -- \`public.documents\` j\xE1 usa. Um formul\xE1rio resolve por uma linha de
187
+ -- plg_forms_documents; um contrato, por outra.
188
+ subject_type text,
189
+ subject_id uuid,
190
+ candidate_type text,
191
+ candidate_id uuid,
192
+ resolved_via text,
193
+ resolved_at timestamp with time zone,
194
+ -- A anamnese vale at\xE9 uma data ("V\xE1lido at\xE9 08/03/2027"), e \xE9 isso que
195
+ -- solta o resto da r\xE9gua.
196
+ valid_until timestamp with time zone,
197
+ frozen_at timestamp with time zone,
198
+ rule_sources jsonb DEFAULT '[]'::jsonb NOT NULL,
199
+ metadata jsonb DEFAULT '{}'::jsonb NOT NULL,
200
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
201
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
202
+ CONSTRAINT plg_clinical_requirements_kind_check CHECK (kind = ANY (ARRAY[
203
+ 'form'::text, 'evaluation'::text, 'contract'::text, 'session_term'::text,
204
+ 'products'::text, 'invoice_item'::text, 'revision_link'::text])),
205
+ CONSTRAINT plg_clinical_requirements_scope_check
206
+ CHECK (scope = ANY (ARRAY['service'::text, 'attendance'::text])),
207
+ CONSTRAINT plg_clinical_requirements_status_check CHECK (status = ANY (ARRAY[
208
+ 'pending'::text, 'resolved'::text, 'not_applicable'::text]))
209
+ );
210
+
211
+ COMMENT ON TABLE public.plg_clinical_requirements IS
212
+ 'A exig\xEAncia que trava o in\xEDcio ou o fim do atendimento \u2014 anamnese, avalia\xE7\xE3o, contrato, termo, kit. V1: execution_requirements.';
213
+
214
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
215
+ -- 4. A vers\xE3o do servi\xE7o
216
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
217
+ --
218
+ -- O servi\xE7o muda de pre\xE7o e de prazo, e o que foi contratado tem de continuar
219
+ -- valendo o que valia. A revis\xE3o \xE9 o congelamento \u2014 e ela carrega os
220
+ -- formul\xE1rios que aquela vers\xE3o exigia.
221
+ CREATE TABLE IF NOT EXISTS public.plg_clinical_service_revisions (
222
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
223
+ tenant_id uuid NOT NULL,
224
+ service_id uuid NOT NULL,
225
+ revision_number integer NOT NULL,
226
+ price numeric(14,2),
227
+ duration_minutes integer,
228
+ deadline_days integer,
229
+ -- Os \`service_revision_forms\` daquela revis\xE3o. S\xE3o 87 linhas em 110
230
+ -- revis\xF5es: uma lista curta, sem vida pr\xF3pria e sem tela \u2014 jsonb em vez de
231
+ -- uma quarta tabela que ningu\xE9m consulta sozinha.
232
+ form_template_refs jsonb DEFAULT '[]'::jsonb NOT NULL,
233
+ metadata jsonb DEFAULT '{}'::jsonb NOT NULL,
234
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
235
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
236
+ CONSTRAINT plg_clinical_service_revisions_number_check CHECK (revision_number >= 1)
237
+ );
238
+
239
+ COMMENT ON TABLE public.plg_clinical_service_revisions IS
240
+ 'A vers\xE3o congelada do servi\xE7o \u2014 pre\xE7o, dura\xE7\xE3o e prazo no momento da contrata\xE7\xE3o. V1: service_revisions + service_revision_forms.';
241
+
242
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
243
+ -- 5. O desfecho do que foi contratado e n\xE3o executado
244
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
245
+
246
+ CREATE TABLE IF NOT EXISTS public.plg_clinical_prepaid_outcomes (
247
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
248
+ tenant_id uuid NOT NULL,
249
+ unit_id uuid,
250
+ booking_id uuid,
251
+ order_item_id uuid,
252
+ outcome text NOT NULL,
253
+ reason text,
254
+ decided_by uuid,
255
+ decided_at timestamp with time zone DEFAULT now() NOT NULL,
256
+ metadata jsonb DEFAULT '{}'::jsonb NOT NULL,
257
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
258
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
259
+ CONSTRAINT plg_clinical_prepaid_outcomes_check CHECK (outcome = ANY (ARRAY[
260
+ 'contracted'::text, 'declined'::text, 'postponed'::text]))
261
+ );
262
+
263
+ COMMENT ON TABLE public.plg_clinical_prepaid_outcomes IS
264
+ 'O que aconteceu com o servi\xE7o contratado e n\xE3o executado no dia \u2014 contratado, recusado ou adiado. V1: prepaid_item_outcomes.';
265
+
266
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
267
+ -- 6. As chaves
268
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
269
+ --
270
+ -- Toda FK para uma tabela escopada por unidade \xE9 COMPOSTA (tenant_id, id): \xE9
271
+ -- ela que impede a sess\xE3o de uma casa apontar para o agendamento de outra. Onde
272
+ -- a refer\xEAncia \xE9 opcional, \`ON DELETE SET NULL\` \u2014 apagar o agendamento n\xE3o pode
273
+ -- levar o prontu\xE1rio junto.
274
+ DO $$
275
+ DECLARE
276
+ t text;
277
+ tabelas text[] := ARRAY['plg_clinical_sessions', 'plg_clinical_session_products',
278
+ 'plg_clinical_requirements', 'plg_clinical_service_revisions',
279
+ 'plg_clinical_prepaid_outcomes'];
280
+ BEGIN
281
+ FOREACH t IN ARRAY tabelas LOOP
282
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint
283
+ WHERE conrelid = ('public.' || t)::regclass AND contype = 'p') THEN
284
+ EXECUTE format('ALTER TABLE ONLY public.%I ADD CONSTRAINT %I PRIMARY KEY (id)', t, t || '_pkey');
285
+ END IF;
286
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = t || '_tenant_id_id_key') THEN
287
+ EXECUTE format('ALTER TABLE ONLY public.%I ADD CONSTRAINT %I UNIQUE (tenant_id, id)', t, t || '_tenant_id_id_key');
288
+ END IF;
289
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = t || '_tenant_fkey') THEN
290
+ EXECUTE format('ALTER TABLE ONLY public.%I ADD CONSTRAINT %I FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE', t, t || '_tenant_fkey');
291
+ END IF;
292
+ END LOOP;
293
+ END $$;
294
+
295
+ DO $$ BEGIN
296
+ -- sess\xF5es
297
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_unit_fkey') THEN
298
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_unit_fkey
299
+ FOREIGN KEY (tenant_id, unit_id) REFERENCES app.units(tenant_id, id) ON DELETE SET NULL;
300
+ END IF;
301
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_booking_fkey') THEN
302
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_booking_fkey
303
+ FOREIGN KEY (booking_id) REFERENCES public.appointments(id) ON DELETE SET NULL;
304
+ END IF;
305
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_booking_item_fkey') THEN
306
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_booking_item_fkey
307
+ FOREIGN KEY (booking_item_id) REFERENCES public.appointment_items(id) ON DELETE SET NULL;
308
+ END IF;
309
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_party_fkey') THEN
310
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_party_fkey
311
+ FOREIGN KEY (party_id) REFERENCES public.people(id) ON DELETE SET NULL;
312
+ END IF;
313
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_assignee_fkey') THEN
314
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_assignee_fkey
315
+ FOREIGN KEY (assignee_id) REFERENCES public.people(id) ON DELETE SET NULL;
316
+ END IF;
317
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_performed_by_fkey') THEN
318
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_performed_by_fkey
319
+ FOREIGN KEY (performed_by_id) REFERENCES public.people(id) ON DELETE SET NULL;
320
+ END IF;
321
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_service_fkey') THEN
322
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_service_fkey
323
+ FOREIGN KEY (service_id) REFERENCES public.products(id) ON DELETE SET NULL;
324
+ END IF;
325
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_order_item_fkey') THEN
326
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_order_item_fkey
327
+ FOREIGN KEY (order_item_id) REFERENCES public.items(id) ON DELETE SET NULL;
328
+ END IF;
329
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_quote_item_fkey') THEN
330
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_quote_item_fkey
331
+ FOREIGN KEY (quote_item_id) REFERENCES public.items(id) ON DELETE SET NULL;
332
+ END IF;
333
+ -- O pai e a avalia\xE7\xE3o de origem s\xE3o a MESMA tabela. CASCADE aqui apagaria a
334
+ -- corrente de revis\xF5es inteira ao apagar a primeira; SET NULL deixa as filhas
335
+ -- \xF3rf\xE3s e leg\xEDveis, que \xE9 o que um prontu\xE1rio pede.
336
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_parent_fkey') THEN
337
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_parent_fkey
338
+ FOREIGN KEY (parent_session_id) REFERENCES public.plg_clinical_sessions(id) ON DELETE SET NULL;
339
+ END IF;
340
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_sessions_source_eval_fkey') THEN
341
+ ALTER TABLE ONLY public.plg_clinical_sessions ADD CONSTRAINT plg_clinical_sessions_source_eval_fkey
342
+ FOREIGN KEY (source_evaluation_id) REFERENCES public.plg_clinical_sessions(id) ON DELETE SET NULL;
343
+ END IF;
344
+
345
+ -- produtos da sess\xE3o: a sess\xE3o some, o consumo some junto \u2014 ele n\xE3o existe fora dela
346
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_session_products_session_fkey') THEN
347
+ ALTER TABLE ONLY public.plg_clinical_session_products ADD CONSTRAINT plg_clinical_session_products_session_fkey
348
+ FOREIGN KEY (tenant_id, session_id) REFERENCES public.plg_clinical_sessions(tenant_id, id) ON DELETE CASCADE;
349
+ END IF;
350
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_session_products_product_fkey') THEN
351
+ ALTER TABLE ONLY public.plg_clinical_session_products ADD CONSTRAINT plg_clinical_session_products_product_fkey
352
+ FOREIGN KEY (product_id) REFERENCES public.products(id) ON DELETE CASCADE;
353
+ END IF;
354
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_session_products_unit_fkey') THEN
355
+ ALTER TABLE ONLY public.plg_clinical_session_products ADD CONSTRAINT plg_clinical_session_products_unit_fkey
356
+ FOREIGN KEY (tenant_id, unit_id) REFERENCES app.units(tenant_id, id) ON DELETE SET NULL;
357
+ END IF;
358
+ -- A UNIDADE DE MEDIDA (SR, UI, mL) MORA NO ESTOQUE, E FICA SEM CHAVE.
359
+ --
360
+ -- Havia uma FK para \`plg_inventory_measurement_units\`. Ela amarra dois ciclos
361
+ -- de release e torna imposs\xEDvel desinstalar o estoque sem derrubar o
362
+ -- prontu\xE1rio \u2014 a cl\xEDnica que n\xE3o usa estoque passaria a precisar dele. O
363
+ -- \`used_unit_id\` continua sendo o uuid de l\xE1; quem quiser o s\xEDmbolo resolve
364
+ -- na leitura, e unidade apagada vira n\xFAmero sem r\xF3tulo em vez de escrita
365
+ -- recusada.
366
+ ALTER TABLE public.plg_clinical_session_products
367
+ DROP CONSTRAINT IF EXISTS plg_clinical_session_products_uom_fkey;
368
+
369
+ -- exig\xEAncias
370
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_requirements_session_fkey') THEN
371
+ ALTER TABLE ONLY public.plg_clinical_requirements ADD CONSTRAINT plg_clinical_requirements_session_fkey
372
+ FOREIGN KEY (tenant_id, session_id) REFERENCES public.plg_clinical_sessions(tenant_id, id) ON DELETE CASCADE;
373
+ END IF;
374
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_requirements_booking_fkey') THEN
375
+ ALTER TABLE ONLY public.plg_clinical_requirements ADD CONSTRAINT plg_clinical_requirements_booking_fkey
376
+ FOREIGN KEY (booking_id) REFERENCES public.appointments(id) ON DELETE CASCADE;
377
+ END IF;
378
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_requirements_unit_fkey') THEN
379
+ ALTER TABLE ONLY public.plg_clinical_requirements ADD CONSTRAINT plg_clinical_requirements_unit_fkey
380
+ FOREIGN KEY (tenant_id, unit_id) REFERENCES app.units(tenant_id, id) ON DELETE SET NULL;
381
+ END IF;
382
+
383
+ -- revis\xE3o do servi\xE7o: uma por (servi\xE7o, n\xFAmero)
384
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_service_revisions_service_fkey') THEN
385
+ ALTER TABLE ONLY public.plg_clinical_service_revisions ADD CONSTRAINT plg_clinical_service_revisions_service_fkey
386
+ FOREIGN KEY (service_id) REFERENCES public.products(id) ON DELETE CASCADE;
387
+ END IF;
388
+
389
+ -- desfecho
390
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_prepaid_outcomes_booking_fkey') THEN
391
+ ALTER TABLE ONLY public.plg_clinical_prepaid_outcomes ADD CONSTRAINT plg_clinical_prepaid_outcomes_booking_fkey
392
+ FOREIGN KEY (booking_id) REFERENCES public.appointments(id) ON DELETE CASCADE;
393
+ END IF;
394
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_prepaid_outcomes_item_fkey') THEN
395
+ ALTER TABLE ONLY public.plg_clinical_prepaid_outcomes ADD CONSTRAINT plg_clinical_prepaid_outcomes_item_fkey
396
+ FOREIGN KEY (order_item_id) REFERENCES public.items(id) ON DELETE SET NULL;
397
+ END IF;
398
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_clinical_prepaid_outcomes_unit_fkey') THEN
399
+ ALTER TABLE ONLY public.plg_clinical_prepaid_outcomes ADD CONSTRAINT plg_clinical_prepaid_outcomes_unit_fkey
400
+ FOREIGN KEY (tenant_id, unit_id) REFERENCES app.units(tenant_id, id) ON DELETE SET NULL;
401
+ END IF;
402
+ END $$;
403
+
404
+ CREATE UNIQUE INDEX IF NOT EXISTS plg_clinical_service_revisions_service_number_key
405
+ ON public.plg_clinical_service_revisions USING btree (tenant_id, service_id, revision_number);
406
+
407
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
408
+ -- 7. Os \xEDndices das tr\xEAs perguntas que a tela faz
409
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
410
+ --
411
+ -- "o que aconteceu com esta paciente" \xB7 "o que falta neste atendimento" \xB7
412
+ -- "quanto deste produto saiu". Com 233 mil sess\xF5es numa rede de 63 unidades,
413
+ -- cada uma dessas sem \xEDndice \xE9 uma varredura.
414
+ CREATE INDEX IF NOT EXISTS plg_clinical_sessions_party_idx
415
+ ON public.plg_clinical_sessions USING btree (tenant_id, party_id, scheduled_for DESC);
416
+ CREATE INDEX IF NOT EXISTS plg_clinical_sessions_booking_idx
417
+ ON public.plg_clinical_sessions USING btree (tenant_id, booking_id) WHERE booking_id IS NOT NULL;
418
+ CREATE INDEX IF NOT EXISTS plg_clinical_sessions_unit_status_idx
419
+ ON public.plg_clinical_sessions USING btree (tenant_id, unit_id, status, scheduled_for DESC);
420
+ CREATE INDEX IF NOT EXISTS plg_clinical_sessions_deal_idx
421
+ ON public.plg_clinical_sessions USING btree (tenant_id, deal_id) WHERE deal_id IS NOT NULL;
422
+ CREATE INDEX IF NOT EXISTS plg_clinical_session_products_session_idx
423
+ ON public.plg_clinical_session_products USING btree (tenant_id, session_id);
424
+ CREATE INDEX IF NOT EXISTS plg_clinical_session_products_product_idx
425
+ ON public.plg_clinical_session_products USING btree (tenant_id, product_id, executed_on DESC);
426
+ CREATE INDEX IF NOT EXISTS plg_clinical_requirements_session_idx
427
+ ON public.plg_clinical_requirements USING btree (tenant_id, session_id, status);
428
+ CREATE INDEX IF NOT EXISTS plg_clinical_requirements_booking_pending_idx
429
+ ON public.plg_clinical_requirements USING btree (tenant_id, booking_id)
430
+ WHERE status = 'pending'::text;
431
+
432
+ DO $$
433
+ DECLARE t text;
434
+ BEGIN
435
+ FOREACH t IN ARRAY ARRAY['plg_clinical_sessions', 'plg_clinical_session_products',
436
+ 'plg_clinical_requirements', 'plg_clinical_service_revisions',
437
+ 'plg_clinical_prepaid_outcomes'] LOOP
438
+ EXECUTE format('DROP TRIGGER IF EXISTS %I ON public.%I', t || '_updated_at', t);
439
+ EXECUTE format('CREATE TRIGGER %I BEFORE UPDATE ON public.%I FOR EACH ROW EXECUTE FUNCTION public.handle_updated_at()', t || '_updated_at', t);
440
+ END LOOP;
441
+ END $$;
442
+
443
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
444
+ -- 8. Quem enxerga o prontu\xE1rio
445
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
446
+ --
447
+ -- Escopo de UNIDADE nas quatro tabelas que t\xEAm unidade, e permiss\xE3o pr\xF3pria:
448
+ -- \`clinical.read\` n\xE3o \xE9 \`agenda.read\`. Quem marca hor\xE1rio n\xE3o l\xEA anamnese.
449
+ --
450
+ -- A revis\xE3o do servi\xE7o \xE9 a exce\xE7\xE3o: ela \xE9 do CAT\xC1LOGO, n\xE3o de uma filial \u2014 o
451
+ -- pre\xE7o congelado de um servi\xE7o vale na rede inteira, e escond\xEA-lo por unidade
452
+ -- faria a fatura de ontem virar um n\xFAmero sem origem.
453
+ -- As cinco, uma a uma e por extenso. O la\xE7o abaixo j\xE1 liga tudo isto \u2014 mas ele
454
+ -- liga por \`EXECUTE format(...)\`, e o port\xE3o que revisa plugin l\xEA o ARQUIVO,
455
+ -- n\xE3o o banco: para ele, tabela com tenant_id e sem um ENABLE literal \xE9 tabela
456
+ -- aberta. Uma garantia que o revisor n\xE3o consegue ler \xE9 uma garantia que
457
+ -- ningu\xE9m confere.
458
+ ALTER TABLE public.plg_clinical_sessions ENABLE ROW LEVEL SECURITY;
459
+ ALTER TABLE public.plg_clinical_session_products ENABLE ROW LEVEL SECURITY;
460
+ ALTER TABLE public.plg_clinical_requirements ENABLE ROW LEVEL SECURITY;
461
+ ALTER TABLE public.plg_clinical_service_revisions ENABLE ROW LEVEL SECURITY;
462
+ ALTER TABLE public.plg_clinical_prepaid_outcomes ENABLE ROW LEVEL SECURITY;
463
+
464
+ DO $$
465
+ DECLARE
466
+ t text;
467
+ unidade boolean;
468
+ BEGIN
469
+ FOREACH t IN ARRAY ARRAY['plg_clinical_sessions', 'plg_clinical_session_products',
470
+ 'plg_clinical_requirements', 'plg_clinical_service_revisions',
471
+ 'plg_clinical_prepaid_outcomes'] LOOP
472
+ unidade := t <> 'plg_clinical_service_revisions';
473
+ EXECUTE format('ALTER TABLE public.%I FORCE ROW LEVEL SECURITY', t);
474
+ EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);
475
+ EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.%I TO authenticated', t);
476
+ EXECUTE format('GRANT ALL ON TABLE public.%I TO service_role', t);
477
+
478
+ EXECUTE format('DROP POLICY IF EXISTS %I ON public.%I', t || '_authz_select', t);
479
+ EXECUTE format($f$CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (
480
+ tenant_id = (SELECT app.current_tenant_id())
481
+ AND (%s)
482
+ AND (SELECT app.has_permission('clinical.read', %s)))$f$,
483
+ t || '_authz_select', t,
484
+ CASE WHEN unidade THEN format('unit_id IS NULL OR (SELECT app.has_unit(%I.unit_id))', t) ELSE 'true' END,
485
+ CASE WHEN unidade THEN format('%I.unit_id', t) ELSE 'NULL::uuid' END);
486
+
487
+ EXECUTE format('DROP POLICY IF EXISTS %I ON public.%I', t || '_authz_insert', t);
488
+ EXECUTE format($f$CREATE POLICY %I ON public.%I FOR INSERT TO authenticated WITH CHECK (
489
+ tenant_id = (SELECT app.current_tenant_id())
490
+ AND (%s)
491
+ AND (SELECT app.has_permission('clinical.create', %s)))$f$,
492
+ t || '_authz_insert', t,
493
+ CASE WHEN unidade THEN format('unit_id IS NULL OR (SELECT app.has_unit(%I.unit_id))', t) ELSE 'true' END,
494
+ CASE WHEN unidade THEN format('%I.unit_id', t) ELSE 'NULL::uuid' END);
495
+
496
+ EXECUTE format('DROP POLICY IF EXISTS %I ON public.%I', t || '_authz_update', t);
497
+ EXECUTE format($f$CREATE POLICY %I ON public.%I FOR UPDATE TO authenticated USING (
498
+ tenant_id = (SELECT app.current_tenant_id())
499
+ AND (%s)
500
+ AND (SELECT app.has_permission('clinical.edit', %s)))
501
+ WITH CHECK (
502
+ tenant_id = (SELECT app.current_tenant_id())
503
+ AND (SELECT app.has_permission('clinical.edit', %s)))$f$,
504
+ t || '_authz_update', t,
505
+ CASE WHEN unidade THEN format('unit_id IS NULL OR (SELECT app.has_unit(%I.unit_id))', t) ELSE 'true' END,
506
+ CASE WHEN unidade THEN format('%I.unit_id', t) ELSE 'NULL::uuid' END,
507
+ CASE WHEN unidade THEN format('%I.unit_id', t) ELSE 'NULL::uuid' END);
508
+
509
+ EXECUTE format('DROP POLICY IF EXISTS %I ON public.%I', t || '_authz_delete', t);
510
+ EXECUTE format($f$CREATE POLICY %I ON public.%I FOR DELETE TO authenticated USING (
511
+ tenant_id = (SELECT app.current_tenant_id())
512
+ AND (%s)
513
+ AND (SELECT app.has_permission('clinical.delete', %s)))$f$,
514
+ t || '_authz_delete', t,
515
+ CASE WHEN unidade THEN format('unit_id IS NULL OR (SELECT app.has_unit(%I.unit_id))', t) ELSE 'true' END,
516
+ CASE WHEN unidade THEN format('%I.unit_id', t) ELSE 'NULL::uuid' END);
517
+ END LOOP;
518
+ END $$;
519
+
520
+ -- \`owner_id\` s\xF3 na sess\xE3o, e \`shareable\` falso: um prontu\xE1rio n\xE3o se compartilha
521
+ -- por tupla \u2014 ou a pessoa atende naquela unidade, ou n\xE3o l\xEA.
522
+ INSERT INTO public.scoped_resources (resource_table, unit_column, owner_column, shareable, default_visibility, label)
523
+ VALUES ('plg_clinical_sessions', 'unit_id', 'owner_id', false, 'unit', 'Atendimentos cl\xEDnicos')
524
+ ON CONFLICT (resource_table) DO UPDATE
525
+ SET unit_column = EXCLUDED.unit_column, default_visibility = EXCLUDED.default_visibility, label = EXCLUDED.label;
526
+
527
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
528
+ -- 9. A permiss\xE3o existe antes da pol\xEDtica precisar dela
529
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
530
+ --
531
+ -- \`clinical.read\` n\xE3o \xE9 \`agenda.read\`, e a diferen\xE7a \xE9 o ponto: a recep\xE7\xE3o marca
532
+ -- hor\xE1rio e N\xC3O l\xEA anamnese. Quem hoje tem \`agenda.*\` num papel herda o
533
+ -- equivalente cl\xEDnico, porque \xE9 quem atende \u2014 e quem quiser separar recep\xE7\xE3o de
534
+ -- profissional tira a linha do papel, que \xE9 uma decis\xE3o de uma tela, n\xE3o de uma
535
+ -- migration.
536
+ INSERT INTO app.permissions (key, plugin, description, owner_only) VALUES
537
+ ('clinical.read', 'clinical', 'Prontu\xE1rio: ler o atendimento, a anamnese e o consumo', false),
538
+ ('clinical.read_all', 'clinical', 'Prontu\xE1rio: ler o de todas as unidades', false),
539
+ ('clinical.create', 'clinical', 'Prontu\xE1rio: abrir sess\xE3o e registrar consumo', false),
540
+ ('clinical.edit', 'clinical', 'Prontu\xE1rio: corrigir sess\xE3o, consumo e exig\xEAncia', false),
541
+ ('clinical.delete', 'clinical', 'Prontu\xE1rio: apagar', false),
542
+ ('clinical.manage', 'clinical', 'Prontu\xE1rio: administrar', false)
543
+ ON CONFLICT (key) DO UPDATE SET plugin = EXCLUDED.plugin, description = EXCLUDED.description;
544
+
545
+ INSERT INTO app.role_permissions (tenant_id, role_id, permission)
546
+ SELECT rp.tenant_id, rp.role_id, replace(rp.permission, 'agenda.', 'clinical.')
547
+ FROM app.role_permissions rp
548
+ WHERE rp.permission IN ('agenda.read', 'agenda.read_all', 'agenda.create',
549
+ 'agenda.edit', 'agenda.delete', 'agenda.manage')
550
+ ON CONFLICT DO NOTHING;
551
+ `;
552
+ var MIGRATION_002_O_PRONTUARIO_DO_V1_ATRAVESSA = `-- O prontu\xE1rio do V1 atravessa.
553
+ --
554
+ -- A 001 fez as cinco tabelas. Esta faz o TRANSPORTE: os writers do motor de
555
+ -- porte e as cinco linhas do de-para. Sem ela as tabelas existem vazias.
556
+ --
557
+ -- journey_executions 233.934 \u2192 plg_clinical_sessions
558
+ -- execution_products 117.011 \u2192 plg_clinical_session_products
559
+ -- execution_requirements 6.590 \u2192 plg_clinical_requirements
560
+ -- service_revisions 110 \u2192 plg_clinical_service_revisions
561
+ -- service_revision_forms 87 \u2192 (jsonb da revis\xE3o)
562
+ -- prepaid_item_outcomes 30 \u2192 plg_clinical_prepaid_outcomes
563
+ --
564
+ -- \u2500\u2500 Duas tabelas do V1 n\xE3o t\xEAm \`uuid\` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
565
+ --
566
+ -- \`execution_requirements\` e \`prepaid_item_outcomes\` n\xE3o guardam uuid nenhum \u2014
567
+ -- s\xF3 o id num\xE9rico. O motor j\xE1 sabe lidar com isso (o id do destino nasce
568
+ -- determin\xEDstico da chave da origem), e \xE9 por isso que o de-para delas n\xE3o
569
+ -- mapeia \`uuid\`.
570
+ --
571
+ -- \u2500\u2500 A refer\xEAncia polim\xF3rfica, resolvida em tempo de escrita \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
572
+ --
573
+ -- \`execution_requirements.resolved_table\` + \`resolved_id\` apontam para uma
574
+ -- tabela QUALQUER, e o \`@tabela\` do de-para \xE9 est\xE1tico. Ent\xE3o quem resolve \xE9 o
575
+ -- writer, lendo o ledger com o nome da tabela que chegou na linha. Medido no
576
+ -- tenant 1:
577
+ --
578
+ -- client_form_responses 2.685 ainda n\xE3o migrou \u2192 fica NULO, com o
579
+ -- n\xFAmero cru em metadata
580
+ -- journey_executions 1.048 resolve
581
+ -- generated_contracts 845 ainda n\xE3o migrou
582
+ -- invoice_items 423 resolve
583
+ -- appointments 80 resolve
584
+ --
585
+ -- O n\xFAmero cru fica em \`metadata.clinical.v1_resolved_ref\` de prop\xF3sito: no dia
586
+ -- em que \`client_form_responses\` atravessar, uma passada de costura preenche os
587
+ -- 2.685 sem reler a origem \u2014 foi o que a 011 da agenda fez com a sala.
588
+ --
589
+ -- \u2500\u2500 A revis\xE3o e os formul\xE1rios dela \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
590
+ --
591
+ -- 87 linhas de \`service_revision_forms\` em 110 revis\xF5es. Uma lista curta, sem
592
+ -- tela e sem vida pr\xF3pria, ent\xE3o ela entra como jsonb DENTRO da revis\xE3o \u2014 e o
593
+ -- writer que a escreve \xE9 um facet: acha a revis\xE3o pelo ledger e acrescenta,
594
+ -- sem duplicar quando a onda roda de novo.
595
+ --
596
+ -- Idempotente.
597
+
598
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
599
+ -- 1. O vocabul\xE1rio fechado aprende quatro palavras
600
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
601
+ --
602
+ -- Por ACR\xC9SCIMO, lendo a defini\xE7\xE3o vigente. Lista literal apaga o que um passo
603
+ -- anterior acrescentou \u2014 \xE9 a armadilha registrada em financial/072 e agenda/008.
604
+ DO $$
605
+ DECLARE v_def text;
606
+ BEGIN
607
+ SELECT pg_get_constraintdef(oid) INTO v_def
608
+ FROM pg_constraint WHERE conname = 'allowlist_writer_check';
609
+ IF v_def IS NULL OR strpos(v_def, 'clinical_session') > 0 THEN RETURN; END IF;
610
+ ALTER TABLE migration.allowlist DROP CONSTRAINT allowlist_writer_check;
611
+ EXECUTE replace(
612
+ 'ALTER TABLE migration.allowlist ADD CONSTRAINT allowlist_writer_check ' || v_def,
613
+ '''person''::text',
614
+ '''person''::text, ''clinical_session''::text, ''clinical_session_product''::text, '
615
+ '''clinical_requirement''::text, ''clinical_service_revision''::text, '
616
+ '''clinical_revision_form''::text, ''clinical_prepaid_outcome''::text');
617
+ END $$;
618
+
619
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
620
+ -- 2. Uma ajuda: resolver refer\xEAncia polim\xF3rfica pelo ledger
621
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
622
+ --
623
+ -- SECURITY DEFINER porque l\xEA \`migration.ledger\`, que o papel do porte j\xE1
624
+ -- alcan\xE7a mas nenhuma pol\xEDtica de tenant descreve. Devolve NULO quando a linha
625
+ -- de origem ainda n\xE3o atravessou \u2014 e NULO aqui \xE9 resposta, n\xE3o erro.
626
+ CREATE OR REPLACE FUNCTION migration._clinical_resolve(
627
+ p_tenant uuid, p_table text, p_id text
628
+ ) RETURNS uuid
629
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO ''
630
+ AS $function$
631
+ SELECT l.target_id
632
+ FROM migration.ledger l
633
+ WHERE l.tenant_id = p_tenant
634
+ AND l.source_table = p_table
635
+ AND l.status = 'migrated'
636
+ AND l.source_numeric_id = nullif(p_id, '')::bigint
637
+ LIMIT 1
638
+ $function$;
639
+
640
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
641
+ -- 3. O writer da sess\xE3o
642
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
643
+
644
+ CREATE OR REPLACE FUNCTION migration.upsert_clinical_session(
645
+ p_tenant uuid, p_id uuid, p_row jsonb, p_args jsonb DEFAULT '{}'::jsonb
646
+ ) RETURNS jsonb
647
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
648
+ AS $function$
649
+ DECLARE
650
+ v_meta jsonb := coalesce(p_row -> 'metadata', '{}'::jsonb);
651
+ v_status text := nullif(p_row ->> 'status', '');
652
+ v_unit uuid;
653
+ v_existing uuid;
654
+ v_created boolean := false;
655
+ v_standalone boolean := migration._standalone();
656
+ BEGIN
657
+ IF v_standalone THEN PERFORM migration._assert_fence(p_tenant); PERFORM set_config('migration.writer', 'on', true); END IF;
658
+ IF p_id IS NULL THEN
659
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'state', 'reason', 'a clinical session needs an id');
660
+ END IF;
661
+
662
+ -- O vocabul\xE1rio \xE9 fechado na tabela. Recusar aqui, com a palavra na m\xE3o, \xE9
663
+ -- melhor do que deixar a CHECK derrubar o lote sem dizer qual linha.
664
+ IF v_status IS NULL OR v_status NOT IN ('quoted','contracted','scheduled','in_service','in_progress','executed','pending') THEN
665
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'value',
666
+ 'reason', format('clinical session status %L is not one of the seven the V1 writes', v_status));
667
+ END IF;
668
+
669
+ BEGIN v_unit := (p_row ->> 'unit_id')::uuid; EXCEPTION WHEN OTHERS THEN v_unit := NULL; END;
670
+ -- Sem unidade na linha, a do agendamento serve: \xE9 o mesmo atendimento.
671
+ IF v_unit IS NULL AND (p_row ->> 'booking_id') IS NOT NULL THEN
672
+ SELECT a.unit_id INTO v_unit FROM public.appointments a
673
+ WHERE a.id = (p_row ->> 'booking_id')::uuid AND a.tenant_id = p_tenant;
674
+ END IF;
675
+
676
+ SELECT tenant_id INTO v_existing FROM public.plg_clinical_sessions WHERE id = p_id;
677
+ IF v_existing IS NOT NULL AND v_existing <> p_tenant THEN
678
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'tenant',
679
+ 'reason', format('clinical session %s already exists in another tenant', p_id));
680
+ END IF;
681
+
682
+ IF v_existing IS NULL THEN
683
+ INSERT INTO public.plg_clinical_sessions
684
+ (id, tenant_id, unit_id, status, booking_id, booking_item_id, party_id,
685
+ assignee_id, performed_by_id, service_id, order_item_id, quote_item_id, deal_id,
686
+ revision_number, parent_session_id, source_evaluation_id,
687
+ scheduled_for, started_at, ended_at, products_initialized, notes,
688
+ metadata, created_at, updated_at)
689
+ VALUES
690
+ (p_id, p_tenant, v_unit, v_status,
691
+ nullif(p_row ->> 'booking_id', '')::uuid,
692
+ nullif(p_row ->> 'booking_item_id', '')::uuid,
693
+ nullif(p_row ->> 'party_id', '')::uuid,
694
+ nullif(p_row ->> 'assignee_id', '')::uuid,
695
+ nullif(p_row ->> 'performed_by_id', '')::uuid,
696
+ nullif(p_row ->> 'service_id', '')::uuid,
697
+ nullif(p_row ->> 'order_item_id', '')::uuid,
698
+ nullif(p_row ->> 'quote_item_id', '')::uuid,
699
+ nullif(p_row ->> 'deal_id', '')::uuid,
700
+ greatest(coalesce(nullif(p_row ->> 'revision_number', '')::integer, 1), 1),
701
+ nullif(p_row ->> 'parent_session_id', '')::uuid,
702
+ nullif(p_row ->> 'source_evaluation_id', '')::uuid,
703
+ nullif(p_row ->> 'scheduled_for', '')::date,
704
+ nullif(p_row ->> 'started_at', '')::timestamptz,
705
+ nullif(p_row ->> 'ended_at', '')::timestamptz,
706
+ coalesce((p_row ->> 'products_initialized')::boolean, false),
707
+ p_row ->> 'notes', v_meta,
708
+ coalesce(nullif(p_row ->> 'created_at', '')::timestamptz, now()),
709
+ coalesce(nullif(p_row ->> 'updated_at', '')::timestamptz, now()));
710
+ v_created := true;
711
+ ELSE
712
+ UPDATE public.plg_clinical_sessions SET
713
+ unit_id = coalesce(v_unit, unit_id),
714
+ status = v_status,
715
+ booking_id = coalesce(nullif(p_row ->> 'booking_id', '')::uuid, booking_id),
716
+ booking_item_id = coalesce(nullif(p_row ->> 'booking_item_id', '')::uuid, booking_item_id),
717
+ party_id = coalesce(nullif(p_row ->> 'party_id', '')::uuid, party_id),
718
+ assignee_id = coalesce(nullif(p_row ->> 'assignee_id', '')::uuid, assignee_id),
719
+ performed_by_id = coalesce(nullif(p_row ->> 'performed_by_id', '')::uuid, performed_by_id),
720
+ service_id = coalesce(nullif(p_row ->> 'service_id', '')::uuid, service_id),
721
+ order_item_id = coalesce(nullif(p_row ->> 'order_item_id', '')::uuid, order_item_id),
722
+ quote_item_id = coalesce(nullif(p_row ->> 'quote_item_id', '')::uuid, quote_item_id),
723
+ deal_id = coalesce(nullif(p_row ->> 'deal_id', '')::uuid, deal_id),
724
+ parent_session_id = coalesce(nullif(p_row ->> 'parent_session_id', '')::uuid, parent_session_id),
725
+ source_evaluation_id = coalesce(nullif(p_row ->> 'source_evaluation_id', '')::uuid, source_evaluation_id),
726
+ scheduled_for = nullif(p_row ->> 'scheduled_for', '')::date,
727
+ started_at = nullif(p_row ->> 'started_at', '')::timestamptz,
728
+ ended_at = nullif(p_row ->> 'ended_at', '')::timestamptz,
729
+ products_initialized = coalesce((p_row ->> 'products_initialized')::boolean, products_initialized),
730
+ notes = CASE WHEN p_row ? 'notes' THEN p_row ->> 'notes' ELSE notes END,
731
+ metadata = migration._merge_meta(metadata, v_meta),
732
+ updated_at = coalesce(nullif(p_row ->> 'updated_at', '')::timestamptz, now())
733
+ WHERE id = p_id;
734
+ END IF;
735
+
736
+ PERFORM migration._set_unit('public.plg_clinical_sessions', p_id, v_unit);
737
+ IF v_standalone THEN
738
+ PERFORM migration._audit(p_tenant, 'public.plg_clinical_sessions', p_id,
739
+ jsonb_build_object('reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END));
740
+ END IF;
741
+ RETURN jsonb_build_object('status', 'migrated', 'target_id', p_id,
742
+ 'reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END);
743
+ END $function$;
744
+
745
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
746
+ -- 4. O writer do produto consumido
747
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
748
+
749
+ CREATE OR REPLACE FUNCTION migration.upsert_clinical_session_product(
750
+ p_tenant uuid, p_id uuid, p_row jsonb, p_args jsonb DEFAULT '{}'::jsonb
751
+ ) RETURNS jsonb
752
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
753
+ AS $function$
754
+ DECLARE
755
+ v_meta jsonb := coalesce(p_row -> 'metadata', '{}'::jsonb);
756
+ v_session uuid;
757
+ v_product uuid;
758
+ v_unit uuid;
759
+ v_existing uuid;
760
+ v_created boolean := false;
761
+ v_standalone boolean := migration._standalone();
762
+ BEGIN
763
+ IF v_standalone THEN PERFORM migration._assert_fence(p_tenant); PERFORM set_config('migration.writer', 'on', true); END IF;
764
+ IF p_id IS NULL THEN
765
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'state', 'reason', 'a session product needs an id');
766
+ END IF;
767
+
768
+ BEGIN v_session := (p_row ->> 'session_id')::uuid; EXCEPTION WHEN OTHERS THEN v_session := NULL; END;
769
+ BEGIN v_product := (p_row ->> 'product_id')::uuid; EXCEPTION WHEN OTHERS THEN v_product := NULL; END;
770
+ -- Consumo sem sess\xE3o \xE9 consumo que nenhuma tela alcan\xE7a; sem produto \xE9 uma
771
+ -- quantidade de nada. Os dois s\xE3o recusa de FK, e a 2\xAA passada do motor os
772
+ -- reapresenta depois que a sess\xE3o migrar.
773
+ IF v_session IS NULL THEN
774
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'fk',
775
+ 'reason', 'a session product needs the session it was used in');
776
+ END IF;
777
+ IF v_product IS NULL THEN
778
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'fk',
779
+ 'reason', 'a session product needs the product that was used');
780
+ END IF;
781
+
782
+ SELECT s.unit_id INTO v_unit FROM public.plg_clinical_sessions s
783
+ WHERE s.id = v_session AND s.tenant_id = p_tenant;
784
+
785
+ SELECT tenant_id INTO v_existing FROM public.plg_clinical_session_products WHERE id = p_id;
786
+ IF v_existing IS NOT NULL AND v_existing <> p_tenant THEN
787
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'tenant',
788
+ 'reason', format('session product %s already exists in another tenant', p_id));
789
+ END IF;
790
+
791
+ IF v_existing IS NULL THEN
792
+ INSERT INTO public.plg_clinical_session_products
793
+ (id, tenant_id, unit_id, session_id, product_id, order_item_id, assignee_id,
794
+ default_quantity, used_quantity, used_unit_id, executed_on,
795
+ is_audited, audited_at, audit_notes, metadata, created_at, updated_at)
796
+ VALUES
797
+ (p_id, p_tenant, v_unit, v_session, v_product,
798
+ nullif(p_row ->> 'order_item_id', '')::uuid,
799
+ nullif(p_row ->> 'assignee_id', '')::uuid,
800
+ nullif(p_row ->> 'default_quantity', '')::numeric,
801
+ nullif(p_row ->> 'used_quantity', '')::numeric,
802
+ nullif(p_row ->> 'used_unit_id', '')::uuid,
803
+ nullif(p_row ->> 'executed_on', '')::date,
804
+ coalesce((p_row ->> 'is_audited')::boolean, false),
805
+ nullif(p_row ->> 'audited_at', '')::timestamptz,
806
+ p_row ->> 'audit_notes', v_meta,
807
+ coalesce(nullif(p_row ->> 'created_at', '')::timestamptz, now()),
808
+ coalesce(nullif(p_row ->> 'updated_at', '')::timestamptz, now()));
809
+ v_created := true;
810
+ ELSE
811
+ UPDATE public.plg_clinical_session_products SET
812
+ unit_id = coalesce(v_unit, unit_id),
813
+ session_id = v_session,
814
+ product_id = v_product,
815
+ order_item_id = coalesce(nullif(p_row ->> 'order_item_id', '')::uuid, order_item_id),
816
+ assignee_id = coalesce(nullif(p_row ->> 'assignee_id', '')::uuid, assignee_id),
817
+ default_quantity = nullif(p_row ->> 'default_quantity', '')::numeric,
818
+ used_quantity = nullif(p_row ->> 'used_quantity', '')::numeric,
819
+ used_unit_id = coalesce(nullif(p_row ->> 'used_unit_id', '')::uuid, used_unit_id),
820
+ executed_on = nullif(p_row ->> 'executed_on', '')::date,
821
+ is_audited = coalesce((p_row ->> 'is_audited')::boolean, is_audited),
822
+ audited_at = nullif(p_row ->> 'audited_at', '')::timestamptz,
823
+ audit_notes = CASE WHEN p_row ? 'audit_notes' THEN p_row ->> 'audit_notes' ELSE audit_notes END,
824
+ metadata = migration._merge_meta(metadata, v_meta),
825
+ updated_at = coalesce(nullif(p_row ->> 'updated_at', '')::timestamptz, now())
826
+ WHERE id = p_id;
827
+ END IF;
828
+
829
+ IF v_standalone THEN
830
+ PERFORM migration._audit(p_tenant, 'public.plg_clinical_session_products', p_id,
831
+ jsonb_build_object('reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END));
832
+ END IF;
833
+ RETURN jsonb_build_object('status', 'migrated', 'target_id', p_id,
834
+ 'reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END);
835
+ END $function$;
836
+
837
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
838
+ -- 5. O writer da exig\xEAncia
839
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
840
+
841
+ CREATE OR REPLACE FUNCTION migration.upsert_clinical_requirement(
842
+ p_tenant uuid, p_id uuid, p_row jsonb, p_args jsonb DEFAULT '{}'::jsonb
843
+ ) RETURNS jsonb
844
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
845
+ AS $function$
846
+ DECLARE
847
+ v_meta jsonb := coalesce(p_row -> 'metadata', '{}'::jsonb);
848
+ v_kind text := nullif(p_row ->> 'kind', '');
849
+ v_scope text := nullif(p_row ->> 'scope', '');
850
+ v_status text := coalesce(nullif(p_row ->> 'status', ''), 'pending');
851
+ v_session uuid;
852
+ v_unit uuid;
853
+ v_subj_t text := nullif(p_row ->> 'subject_type', '');
854
+ v_cand_t text := nullif(p_row ->> 'candidate_type', '');
855
+ v_subj_id uuid;
856
+ v_cand_id uuid;
857
+ v_existing uuid;
858
+ v_created boolean := false;
859
+ v_standalone boolean := migration._standalone();
860
+ BEGIN
861
+ IF v_standalone THEN PERFORM migration._assert_fence(p_tenant); PERFORM set_config('migration.writer', 'on', true); END IF;
862
+ IF p_id IS NULL THEN
863
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'state', 'reason', 'a requirement needs an id');
864
+ END IF;
865
+ IF v_kind IS NULL OR v_kind NOT IN ('form','evaluation','contract','session_term','products','invoice_item','revision_link') THEN
866
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'value',
867
+ 'reason', format('requirement kind %L is not one of the seven the V1 writes', v_kind));
868
+ END IF;
869
+ IF v_scope IS NULL OR v_scope NOT IN ('service','attendance') THEN
870
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'value',
871
+ 'reason', format('requirement scope %L is neither service nor attendance', v_scope));
872
+ END IF;
873
+ IF v_status NOT IN ('pending','resolved','not_applicable') THEN
874
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'value',
875
+ 'reason', format('requirement status %L is not a status the V1 writes', v_status));
876
+ END IF;
877
+
878
+ BEGIN v_session := (p_row ->> 'session_id')::uuid; EXCEPTION WHEN OTHERS THEN v_session := NULL; END;
879
+ IF v_session IS NOT NULL THEN
880
+ SELECT s.unit_id INTO v_unit FROM public.plg_clinical_sessions s
881
+ WHERE s.id = v_session AND s.tenant_id = p_tenant;
882
+ END IF;
883
+
884
+ -- A refer\xEAncia polim\xF3rfica: o de-para n\xE3o alcan\xE7a, o ledger sim. Quando a
885
+ -- tabela apontada ainda n\xE3o atravessou o resultado \xE9 NULO \u2014 e o n\xFAmero cru
886
+ -- fica no metadata para a costura de depois.
887
+ v_subj_id := migration._clinical_resolve(p_tenant, v_subj_t, p_row ->> 'v1_resolved_ref');
888
+ v_cand_id := migration._clinical_resolve(p_tenant, v_cand_t, p_row ->> 'v1_candidate_ref');
889
+
890
+ SELECT tenant_id INTO v_existing FROM public.plg_clinical_requirements WHERE id = p_id;
891
+ IF v_existing IS NOT NULL AND v_existing <> p_tenant THEN
892
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'tenant',
893
+ 'reason', format('requirement %s already exists in another tenant', p_id));
894
+ END IF;
895
+
896
+ IF v_existing IS NULL THEN
897
+ INSERT INTO public.plg_clinical_requirements
898
+ (id, tenant_id, unit_id, session_id, booking_id, party_id, service_id,
899
+ kind, scope, blocks_start, blocks_finish, status,
900
+ subject_type, subject_id, candidate_type, candidate_id,
901
+ resolved_via, resolved_at, valid_until, frozen_at, rule_sources,
902
+ metadata, created_at, updated_at)
903
+ VALUES
904
+ (p_id, p_tenant, v_unit, v_session,
905
+ nullif(p_row ->> 'booking_id', '')::uuid,
906
+ nullif(p_row ->> 'party_id', '')::uuid,
907
+ nullif(p_row ->> 'service_id', '')::uuid,
908
+ v_kind, v_scope,
909
+ coalesce((p_row ->> 'blocks_start')::boolean, false),
910
+ coalesce((p_row ->> 'blocks_finish')::boolean, false),
911
+ v_status, v_subj_t, v_subj_id, v_cand_t, v_cand_id,
912
+ nullif(p_row ->> 'resolved_via', ''),
913
+ nullif(p_row ->> 'resolved_at', '')::timestamptz,
914
+ nullif(p_row ->> 'valid_until', '')::timestamptz,
915
+ nullif(p_row ->> 'frozen_at', '')::timestamptz,
916
+ coalesce(p_row -> 'rule_sources', '[]'::jsonb),
917
+ v_meta,
918
+ coalesce(nullif(p_row ->> 'created_at', '')::timestamptz, now()),
919
+ coalesce(nullif(p_row ->> 'updated_at', '')::timestamptz, now()));
920
+ v_created := true;
921
+ ELSE
922
+ UPDATE public.plg_clinical_requirements SET
923
+ unit_id = coalesce(v_unit, unit_id),
924
+ session_id = coalesce(v_session, session_id),
925
+ booking_id = coalesce(nullif(p_row ->> 'booking_id', '')::uuid, booking_id),
926
+ party_id = coalesce(nullif(p_row ->> 'party_id', '')::uuid, party_id),
927
+ service_id = coalesce(nullif(p_row ->> 'service_id', '')::uuid, service_id),
928
+ kind = v_kind,
929
+ scope = v_scope,
930
+ blocks_start = coalesce((p_row ->> 'blocks_start')::boolean, blocks_start),
931
+ blocks_finish = coalesce((p_row ->> 'blocks_finish')::boolean, blocks_finish),
932
+ status = v_status,
933
+ subject_type = v_subj_t,
934
+ -- \`coalesce\` e n\xE3o substitui\xE7\xE3o: a segunda onda resolve o que a primeira
935
+ -- n\xE3o alcan\xE7ou, e nunca apaga o que j\xE1 estava resolvido.
936
+ subject_id = coalesce(v_subj_id, subject_id),
937
+ candidate_type = v_cand_t,
938
+ candidate_id = coalesce(v_cand_id, candidate_id),
939
+ resolved_via = nullif(p_row ->> 'resolved_via', ''),
940
+ resolved_at = nullif(p_row ->> 'resolved_at', '')::timestamptz,
941
+ valid_until = nullif(p_row ->> 'valid_until', '')::timestamptz,
942
+ frozen_at = nullif(p_row ->> 'frozen_at', '')::timestamptz,
943
+ rule_sources = coalesce(p_row -> 'rule_sources', rule_sources),
944
+ metadata = migration._merge_meta(metadata, v_meta),
945
+ updated_at = coalesce(nullif(p_row ->> 'updated_at', '')::timestamptz, now())
946
+ WHERE id = p_id;
947
+ END IF;
948
+
949
+ IF v_standalone THEN
950
+ PERFORM migration._audit(p_tenant, 'public.plg_clinical_requirements', p_id,
951
+ jsonb_build_object('reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END));
952
+ END IF;
953
+ RETURN jsonb_build_object('status', 'migrated', 'target_id', p_id,
954
+ 'reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END);
955
+ END $function$;
956
+
957
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
958
+ -- 6. A revis\xE3o do servi\xE7o, e os formul\xE1rios dela
959
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
960
+
961
+ CREATE OR REPLACE FUNCTION migration.upsert_clinical_service_revision(
962
+ p_tenant uuid, p_id uuid, p_row jsonb, p_args jsonb DEFAULT '{}'::jsonb
963
+ ) RETURNS jsonb
964
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
965
+ AS $function$
966
+ DECLARE
967
+ v_meta jsonb := coalesce(p_row -> 'metadata', '{}'::jsonb);
968
+ v_service uuid;
969
+ v_number integer;
970
+ v_existing uuid;
971
+ v_created boolean := false;
972
+ v_standalone boolean := migration._standalone();
973
+ BEGIN
974
+ IF v_standalone THEN PERFORM migration._assert_fence(p_tenant); PERFORM set_config('migration.writer', 'on', true); END IF;
975
+ IF p_id IS NULL THEN
976
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'state', 'reason', 'a service revision needs an id');
977
+ END IF;
978
+
979
+ BEGIN v_service := (p_row ->> 'service_id')::uuid; EXCEPTION WHEN OTHERS THEN v_service := NULL; END;
980
+ IF v_service IS NULL THEN
981
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'fk',
982
+ 'reason', 'a service revision needs the service it freezes');
983
+ END IF;
984
+ v_number := greatest(coalesce(nullif(p_row ->> 'revision_number', '')::integer, 1), 1);
985
+
986
+ SELECT tenant_id INTO v_existing FROM public.plg_clinical_service_revisions WHERE id = p_id;
987
+ IF v_existing IS NOT NULL AND v_existing <> p_tenant THEN
988
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'tenant',
989
+ 'reason', format('service revision %s already exists in another tenant', p_id));
990
+ END IF;
991
+
992
+ IF v_existing IS NULL THEN
993
+ INSERT INTO public.plg_clinical_service_revisions
994
+ (id, tenant_id, service_id, revision_number, price, duration_minutes, deadline_days,
995
+ metadata, created_at, updated_at)
996
+ VALUES
997
+ (p_id, p_tenant, v_service, v_number,
998
+ nullif(p_row ->> 'price', '')::numeric,
999
+ nullif(p_row ->> 'duration_minutes', '')::integer,
1000
+ nullif(p_row ->> 'deadline_days', '')::integer,
1001
+ v_meta,
1002
+ coalesce(nullif(p_row ->> 'created_at', '')::timestamptz, now()),
1003
+ coalesce(nullif(p_row ->> 'updated_at', '')::timestamptz, now()));
1004
+ v_created := true;
1005
+ ELSE
1006
+ UPDATE public.plg_clinical_service_revisions SET
1007
+ service_id = v_service,
1008
+ revision_number = v_number,
1009
+ price = nullif(p_row ->> 'price', '')::numeric,
1010
+ duration_minutes = nullif(p_row ->> 'duration_minutes', '')::integer,
1011
+ deadline_days = nullif(p_row ->> 'deadline_days', '')::integer,
1012
+ metadata = migration._merge_meta(metadata, v_meta),
1013
+ updated_at = coalesce(nullif(p_row ->> 'updated_at', '')::timestamptz, now())
1014
+ WHERE id = p_id;
1015
+ END IF;
1016
+
1017
+ IF v_standalone THEN
1018
+ PERFORM migration._audit(p_tenant, 'public.plg_clinical_service_revisions', p_id,
1019
+ jsonb_build_object('reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END));
1020
+ END IF;
1021
+ RETURN jsonb_build_object('status', 'migrated', 'target_id', p_id,
1022
+ 'reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END);
1023
+ END $function$;
1024
+
1025
+ -- O facet: acrescenta um formul\xE1rio ao jsonb da revis\xE3o. A chave de dedupe \xE9 o
1026
+ -- id da linha do V1, e \xE9 isso que faz a onda rodar duas vezes sem duplicar.
1027
+ CREATE OR REPLACE FUNCTION migration.upsert_clinical_revision_form(
1028
+ p_tenant uuid, p_id uuid, p_row jsonb, p_args jsonb DEFAULT '{}'::jsonb
1029
+ ) RETURNS jsonb
1030
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
1031
+ AS $function$
1032
+ DECLARE
1033
+ v_rev uuid;
1034
+ v_ref text := p_row ->> 'v1_ref';
1035
+ v_entry jsonb;
1036
+ v_standalone boolean := migration._standalone();
1037
+ BEGIN
1038
+ IF v_standalone THEN PERFORM migration._assert_fence(p_tenant); PERFORM set_config('migration.writer', 'on', true); END IF;
1039
+
1040
+ BEGIN v_rev := (p_row ->> 'revision_id')::uuid; EXCEPTION WHEN OTHERS THEN v_rev := NULL; END;
1041
+ IF v_rev IS NULL THEN
1042
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'fk',
1043
+ 'reason', 'a revision form needs the revision it belongs to');
1044
+ END IF;
1045
+ IF NOT EXISTS (SELECT 1 FROM public.plg_clinical_service_revisions r
1046
+ WHERE r.id = v_rev AND r.tenant_id = p_tenant) THEN
1047
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'fk',
1048
+ 'reason', 'the revision this form belongs to has not arrived yet');
1049
+ END IF;
1050
+
1051
+ v_entry := jsonb_build_object(
1052
+ 'v1_ref', v_ref,
1053
+ 'v1_form_template_ref', p_row ->> 'v1_form_template_ref');
1054
+
1055
+ UPDATE public.plg_clinical_service_revisions
1056
+ SET form_template_refs = (
1057
+ SELECT coalesce(jsonb_agg(e), '[]'::jsonb)
1058
+ FROM (SELECT e FROM jsonb_array_elements(form_template_refs) e
1059
+ WHERE e ->> 'v1_ref' IS DISTINCT FROM v_ref
1060
+ UNION ALL SELECT v_entry) s(e)),
1061
+ updated_at = now()
1062
+ WHERE id = v_rev;
1063
+
1064
+ RETURN jsonb_build_object('status', 'migrated', 'target_id', v_rev, 'reason', 'attached');
1065
+ END $function$;
1066
+
1067
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
1068
+ -- 7. O writer do desfecho
1069
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
1070
+
1071
+ CREATE OR REPLACE FUNCTION migration.upsert_clinical_prepaid_outcome(
1072
+ p_tenant uuid, p_id uuid, p_row jsonb, p_args jsonb DEFAULT '{}'::jsonb
1073
+ ) RETURNS jsonb
1074
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
1075
+ AS $function$
1076
+ DECLARE
1077
+ v_meta jsonb := coalesce(p_row -> 'metadata', '{}'::jsonb);
1078
+ v_outcome text := nullif(p_row ->> 'outcome', '');
1079
+ v_booking uuid;
1080
+ v_unit uuid;
1081
+ v_existing uuid;
1082
+ v_created boolean := false;
1083
+ v_standalone boolean := migration._standalone();
1084
+ BEGIN
1085
+ IF v_standalone THEN PERFORM migration._assert_fence(p_tenant); PERFORM set_config('migration.writer', 'on', true); END IF;
1086
+ IF p_id IS NULL THEN
1087
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'state', 'reason', 'an outcome needs an id');
1088
+ END IF;
1089
+ IF v_outcome IS NULL OR v_outcome NOT IN ('contracted','declined','postponed') THEN
1090
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'value',
1091
+ 'reason', format('outcome %L is not one of the three the V1 writes', v_outcome));
1092
+ END IF;
1093
+
1094
+ BEGIN v_booking := (p_row ->> 'booking_id')::uuid; EXCEPTION WHEN OTHERS THEN v_booking := NULL; END;
1095
+ IF v_booking IS NOT NULL THEN
1096
+ SELECT a.unit_id INTO v_unit FROM public.appointments a
1097
+ WHERE a.id = v_booking AND a.tenant_id = p_tenant;
1098
+ END IF;
1099
+
1100
+ SELECT tenant_id INTO v_existing FROM public.plg_clinical_prepaid_outcomes WHERE id = p_id;
1101
+ IF v_existing IS NOT NULL AND v_existing <> p_tenant THEN
1102
+ RETURN jsonb_build_object('status', 'quarantined', 'kind', 'tenant',
1103
+ 'reason', format('outcome %s already exists in another tenant', p_id));
1104
+ END IF;
1105
+
1106
+ IF v_existing IS NULL THEN
1107
+ INSERT INTO public.plg_clinical_prepaid_outcomes
1108
+ (id, tenant_id, unit_id, booking_id, order_item_id, outcome, reason, decided_at, metadata, created_at, updated_at)
1109
+ VALUES
1110
+ (p_id, p_tenant, v_unit, v_booking,
1111
+ nullif(p_row ->> 'order_item_id', '')::uuid,
1112
+ v_outcome, p_row ->> 'reason',
1113
+ coalesce(nullif(p_row ->> 'decided_at', '')::timestamptz, now()),
1114
+ v_meta, now(), now());
1115
+ v_created := true;
1116
+ ELSE
1117
+ UPDATE public.plg_clinical_prepaid_outcomes SET
1118
+ unit_id = coalesce(v_unit, unit_id),
1119
+ booking_id = coalesce(v_booking, booking_id),
1120
+ order_item_id = coalesce(nullif(p_row ->> 'order_item_id', '')::uuid, order_item_id),
1121
+ outcome = v_outcome,
1122
+ reason = CASE WHEN p_row ? 'reason' THEN p_row ->> 'reason' ELSE reason END,
1123
+ decided_at = coalesce(nullif(p_row ->> 'decided_at', '')::timestamptz, decided_at),
1124
+ metadata = migration._merge_meta(metadata, v_meta),
1125
+ updated_at = now()
1126
+ WHERE id = p_id;
1127
+ END IF;
1128
+
1129
+ IF v_standalone THEN
1130
+ PERFORM migration._audit(p_tenant, 'public.plg_clinical_prepaid_outcomes', p_id,
1131
+ jsonb_build_object('reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END));
1132
+ END IF;
1133
+ RETURN jsonb_build_object('status', 'migrated', 'target_id', p_id,
1134
+ 'reason', CASE WHEN v_created THEN 'created' ELSE 'updated' END);
1135
+ END $function$;
1136
+
1137
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
1138
+ -- 8. As seis linhas do de-para
1139
+ -- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
1140
+
1141
+ SET LOCAL migration.allowlist_unlock = 'on';
1142
+
1143
+ SELECT migration._allow(
1144
+ 'service_revisions', 'public.plg_clinical_service_revisions', 'clinical', 'clinical_service_revision',
1145
+ '{}'::jsonb, NULL::text[],
1146
+ jsonb_build_object(
1147
+ 'uuid', 'id',
1148
+ 'service_id', 'service_id@services',
1149
+ 'revision_number', 'revision_number',
1150
+ 'price', 'price',
1151
+ 'duration_minutes', 'duration_minutes',
1152
+ 'deadline_days', 'deadline_days',
1153
+ 'created_at', 'created_at',
1154
+ 'tenant_id', '-',
1155
+ 'id', 'jsonb:clinical.v1_ref'),
1156
+ 'A vers\xE3o congelada do servi\xE7o. Vem ANTES da sess\xE3o porque \xE9 ela que d\xE1 o '
1157
+ 'pre\xE7o e o prazo que valiam no dia da contrata\xE7\xE3o.'
1158
+ );
1159
+
1160
+ SELECT migration._allow(
1161
+ 'service_revision_forms', 'public.plg_clinical_service_revisions', 'clinical', 'clinical_revision_form',
1162
+ '{}'::jsonb, NULL::text[],
1163
+ jsonb_build_object(
1164
+ 'service_revision_id', 'revision_id@service_revisions',
1165
+ 'form_template_id', 'v1_form_template_ref',
1166
+ 'id', 'v1_ref',
1167
+ 'uuid', '-',
1168
+ 'service_id', '-',
1169
+ 'created_at', '-',
1170
+ 'tenant_id', '-'),
1171
+ '87 linhas em 110 revis\xF5es. N\xE3o tem tabela pr\xF3pria: entra no jsonb '
1172
+ '\`form_template_refs\` da revis\xE3o, e o writer \xE9 um facet que dedupe pelo id do '
1173
+ 'V1 \u2014 rodar a onda duas vezes n\xE3o duplica.'
1174
+ );
1175
+
1176
+ SELECT migration._allow(
1177
+ 'journey_executions', 'public.plg_clinical_sessions', 'clinical', 'clinical_session',
1178
+ '{}'::jsonb, NULL::text[],
1179
+ jsonb_build_object(
1180
+ 'uuid', 'id',
1181
+ 'journey_status', 'status',
1182
+ 'appointment_id', 'booking_id@appointments',
1183
+ 'appointment_service_id', 'booking_item_id@appointment_services',
1184
+ 'client_id', 'party_id@clients',
1185
+ 'professional_id', 'assignee_id@professionals',
1186
+ 'execution_professional_id', 'performed_by_id@professionals',
1187
+ 'service_id', 'service_id@services',
1188
+ 'invoice_item_id', 'order_item_id@invoice_items',
1189
+ 'quote_item_id', 'quote_item_id@quote_items',
1190
+ 'opportunity_id', 'deal_id@opportunities',
1191
+ 'parent_execution_id', 'parent_session_id@journey_executions',
1192
+ 'source_evaluation_execution_id', 'source_evaluation_id@journey_executions',
1193
+ 'unit_numeric_id', 'unit_id@companies',
1194
+ 'revision_number', 'revision_number',
1195
+ 'appointment_date', 'scheduled_for',
1196
+ 'execution_start_time', 'started_at',
1197
+ 'execution_end_time', 'ended_at',
1198
+ 'products_initialized', 'products_initialized',
1199
+ 'notes', 'notes',
1200
+ 'created_at', 'created_at',
1201
+ 'updated_at', 'updated_at',
1202
+ 'tenant_id', '-',
1203
+ 'product_id', '-',
1204
+ 'status', 'jsonb:clinical.v1_status',
1205
+ 'execution_photos', 'jsonb:clinical.v1_execution_photos',
1206
+ 'id', 'jsonb:clinical.v1_ref'),
1207
+ 'A sess\xE3o de execu\xE7\xE3o. \`journey_status\` \xE9 quem manda no estado \u2014 tem sete '
1208
+ 'palavras contra as quatro de \`status\`, e \xE9 a \xFAnica que separa or\xE7ado de '
1209
+ 'contratado; a outra fica em metadata. \`product_id\` sai: 0 de 233.950 '
1210
+ 'preenchidas. As fotos ficam em metadata at\xE9 virarem linhas de '
1211
+ 'public.documents, que \xE9 onde arquivo mora.'
1212
+ );
1213
+
1214
+ SELECT migration._allow(
1215
+ 'execution_products', 'public.plg_clinical_session_products', 'clinical', 'clinical_session_product',
1216
+ '{}'::jsonb, NULL::text[],
1217
+ jsonb_build_object(
1218
+ 'uuid', 'id',
1219
+ 'journey_execution_id', 'session_id@journey_executions',
1220
+ 'product_id', 'product_id@products',
1221
+ 'invoice_item_id', 'order_item_id@invoice_items',
1222
+ 'professional_id', 'assignee_id@professionals',
1223
+ 'used_unit_id', 'used_unit_id@measurement_units',
1224
+ 'unit_id', '-',
1225
+ 'default_quantity', 'default_quantity',
1226
+ 'used_quantity', 'used_quantity',
1227
+ 'execution_date', 'executed_on',
1228
+ 'is_audited', 'is_audited',
1229
+ 'audited_at', 'audited_at',
1230
+ 'audit_notes', 'audit_notes',
1231
+ 'audited_by_user_id', '-',
1232
+ 'created_at', 'created_at',
1233
+ 'updated_at', 'updated_at',
1234
+ 'tenant_id', '-',
1235
+ 'stock_deducted', '-',
1236
+ 'stock_movement_id', '-',
1237
+ 'stock_position_id', '-',
1238
+ 'position_allocations', '-',
1239
+ 'unit_label_allocations', '-',
1240
+ 'consumption_photos', 'jsonb:clinical.v1_consumption_photos',
1241
+ 'id', 'jsonb:clinical.v1_ref'),
1242
+ 'O produto consumido. As cinco colunas de baixa de estoque saem porque est\xE3o '
1243
+ 'VAZIAS: 0 de 117.015 no tenant 1. O consumo do V1 nunca chegou ao raz\xE3o \u2014 \xE9 '
1244
+ 'o que o Guia descreve na jornada auditoria-de-uso-e-estoque. A unidade vem '
1245
+ 'da sess\xE3o, no writer, e n\xE3o da coluna \`unit_id\` da origem.'
1246
+ );
1247
+
1248
+ SELECT migration._allow(
1249
+ 'execution_requirements', 'public.plg_clinical_requirements', 'clinical', 'clinical_requirement',
1250
+ '{}'::jsonb, NULL::text[],
1251
+ jsonb_build_object(
1252
+ 'journey_execution_id', 'session_id@journey_executions',
1253
+ 'appointment_id', 'booking_id@appointments',
1254
+ 'client_id', 'party_id@clients',
1255
+ 'service_id', 'service_id@services',
1256
+ 'kind', 'kind',
1257
+ 'scope', 'scope',
1258
+ 'status', 'status',
1259
+ 'blocks_start', 'blocks_start',
1260
+ 'blocks_finish', 'blocks_finish',
1261
+ 'resolved_table', 'subject_type',
1262
+ 'resolved_id', 'v1_resolved_ref',
1263
+ 'candidate_table', 'candidate_type',
1264
+ 'candidate_id', 'v1_candidate_ref',
1265
+ 'resolved_via', 'resolved_via',
1266
+ 'resolved_at', 'resolved_at',
1267
+ 'valid_until', 'valid_until',
1268
+ 'frozen_at', 'frozen_at',
1269
+ 'rule_sources', 'rule_sources',
1270
+ 'created_at', 'created_at',
1271
+ 'updated_at', 'updated_at',
1272
+ 'tenant_id', '-',
1273
+ 'ref_id', 'jsonb:clinical.v1_ref_id',
1274
+ 'id', 'jsonb:clinical.v1_ref'),
1275
+ 'O que trava come\xE7ar e terminar. Sem \`uuid\` na origem \u2014 o id do destino nasce '
1276
+ 'determin\xEDstico da chave num\xE9rica. \`resolved_table\`/\`resolved_id\` \xE9 refer\xEAncia '
1277
+ 'polim\xF3rfica e o \`@tabela\` do de-para \xE9 est\xE1tico, ent\xE3o quem resolve \xE9 o '
1278
+ 'writer, lendo o ledger com o nome que chegou na linha.'
1279
+ );
1280
+
1281
+ SELECT migration._allow(
1282
+ 'prepaid_item_outcomes', 'public.plg_clinical_prepaid_outcomes', 'clinical', 'clinical_prepaid_outcome',
1283
+ '{}'::jsonb, NULL::text[],
1284
+ jsonb_build_object(
1285
+ 'appointment_id', 'booking_id@appointments',
1286
+ 'invoice_item_id', 'order_item_id@invoice_items',
1287
+ 'outcome', 'outcome',
1288
+ 'reason', 'reason',
1289
+ 'decided_at', 'decided_at',
1290
+ 'decided_by', '-',
1291
+ 'tenant_id', '-',
1292
+ 'id', 'jsonb:clinical.v1_ref'),
1293
+ 'O desfecho do servi\xE7o contratado e n\xE3o executado no dia. \`decided_by\` \xE9 '
1294
+ 'usu\xE1rio do auth do V1, que n\xE3o atravessa \u2014 fica de fora em vez de virar uma '
1295
+ 'FK que aponta para nada.'
1296
+ );
1297
+
1298
+ RESET migration.allowlist_unlock;
1299
+
1300
+ REVOKE ALL ON FUNCTION migration._clinical_resolve(uuid, text, text) FROM PUBLIC, anon, authenticated;
1301
+ GRANT EXECUTE ON FUNCTION migration._clinical_resolve(uuid, text, text) TO service_role;
1302
+ DO $$
1303
+ DECLARE f text;
1304
+ BEGIN
1305
+ FOREACH f IN ARRAY ARRAY['upsert_clinical_session', 'upsert_clinical_session_product',
1306
+ 'upsert_clinical_requirement', 'upsert_clinical_service_revision',
1307
+ 'upsert_clinical_revision_form', 'upsert_clinical_prepaid_outcome'] LOOP
1308
+ EXECUTE format('REVOKE ALL ON FUNCTION migration.%I(uuid, uuid, jsonb, jsonb) FROM PUBLIC, anon, authenticated', f);
1309
+ EXECUTE format('GRANT EXECUTE ON FUNCTION migration.%I(uuid, uuid, jsonb, jsonb) TO service_role', f);
1310
+ END LOOP;
1311
+ END $$;
1312
+ `;
1313
+ var MIGRATION_003_A_PERMISSAO_SE_PERGUNTA_POR_UNIDADE_NAO_POR_LINHA = `-- A permiss\xE3o se pergunta por unidade, n\xE3o por linha.
1314
+ --
1315
+ -- A tela \`Estoque \u2192 Auditoria de uso\` estourava o \`statement_timeout\`. Medido
1316
+ -- no cluster, como \`authenticated\`, tenant Espa\xE7o Facial:
1317
+ --
1318
+ -- select * from v_inventory_usage_audit order by used_at desc limit 50
1319
+ -- \u2192 97.143 ms
1320
+ --
1321
+ -- A vista n\xE3o era a culpada. As duas tabelas que ela l\xEA j\xE1 eram lentas sozinhas:
1322
+ --
1323
+ -- select count(*) from plg_clinical_session_products 19.000 ms
1324
+ -- select count(*) from plg_clinical_sessions 22.500 ms
1325
+ --
1326
+ -- \u2500\u2500 A linha que custava \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1327
+ --
1328
+ -- A pol\xEDtica que a 001 escreveu chama \`app.has_permission('clinical.read',
1329
+ -- unit_id)\` \u2014 e \`unit_id\` \xE9 COLUNA, ent\xE3o a chamada \xE9 por LINHA. S\xE3o 116.911
1330
+ -- produtos consumidos e 233.556 sess\xF5es; o Espa\xE7o Facial tem 67 unidades.
1331
+ --
1332
+ -- \xC9 a mesma forma do defeito que o spine 121 corrigiu em \`people\`, e a mesma
1333
+ -- corre\xE7\xE3o: a pergunta n\xE3o muda dentro da unidade, ent\xE3o ela se faz uma vez
1334
+ -- POR UNIDADE. \`unit_id IN (subconsulta n\xE3o correlacionada)\` \xE9 resolvido pelo
1335
+ -- planejador como hash montado uma vez; a subconsulta percorre \`app.units\` do
1336
+ -- inquilino e aplica ali os dois predicados que antes rodavam por linha.
1337
+ --
1338
+ -- A reescrita \xE9 EQUIVALENTE por constru\xE7\xE3o, n\xE3o por argumento: s\xE3o os mesmos
1339
+ -- dois predicados (\`app.has_unit\` e \`app.has_permission\`) sobre os mesmos
1340
+ -- valores de \`unit_id\`, s\xF3 que avaliados uma vez por valor distinto em vez de
1341
+ -- uma vez por linha. A linha sem unidade continua decidida pela permiss\xE3o de
1342
+ -- inquilino, como antes.
1343
+ --
1344
+ -- Medido depois, com ROLLBACK, antes de escrever este arquivo:
1345
+ --
1346
+ -- plg_clinical_session_products 116.911 linhas 450 ms (era 19.000)
1347
+ -- plg_clinical_sessions 233.556 linhas 1.070 ms (era 22.500)
1348
+ -- auditoria de uso, 50 linhas 50 linhas 1.330 ms (era 97.143)
1349
+ --
1350
+ -- As contagens s\xE3o ID\xCANTICAS \xE0s de antes \u2014 \xE9 o teste que importa numa mudan\xE7a
1351
+ -- de pol\xEDtica, porque uma que fica r\xE1pida devolvendo menos linhas n\xE3o ficou
1352
+ -- r\xE1pida, ficou errada.
1353
+ --
1354
+ -- Idempotente.
1355
+
1356
+ DO $$
1357
+ DECLARE
1358
+ t text;
1359
+ v_unidade text := $q$unit_id IN (SELECT u.id FROM app.units u
1360
+ WHERE u.tenant_id = (SELECT app.current_tenant_id())
1361
+ AND app.has_unit(u.id)
1362
+ AND app.has_permission('clinical.read', u.id))$q$;
1363
+ BEGIN
1364
+ FOREACH t IN ARRAY ARRAY['plg_clinical_sessions', 'plg_clinical_session_products',
1365
+ 'plg_clinical_requirements', 'plg_clinical_prepaid_outcomes'] LOOP
1366
+ IF to_regclass('public.' || t) IS NULL THEN CONTINUE; END IF;
1367
+ EXECUTE format($f$ALTER POLICY %I ON public.%I USING (
1368
+ tenant_id = (SELECT app.current_tenant_id())
1369
+ AND (CASE WHEN unit_id IS NULL
1370
+ THEN (SELECT app.has_permission('clinical.read', NULL::uuid))
1371
+ ELSE %s END))$f$, t || '_authz_select', t, v_unidade);
1372
+ END LOOP;
1373
+ END $$;
1374
+
1375
+ -- \`plg_clinical_service_revisions\` fica como est\xE1: ela n\xE3o tem unidade \u2014 a
1376
+ -- revis\xE3o \xE9 do CAT\xC1LOGO, e o pre\xE7o congelado de um servi\xE7o vale na rede
1377
+ -- inteira. A pol\xEDtica dela j\xE1 decide uma vez por consulta.
1378
+
1379
+ -- A auditoria de uso ordena por data e corta em 50. Sem \xEDndice, isso \xE9 ordenar
1380
+ -- 116.911 linhas para jogar 116.861 fora.
1381
+ CREATE INDEX IF NOT EXISTS plg_clinical_session_products_executed_idx
1382
+ ON public.plg_clinical_session_products USING btree (tenant_id, executed_on DESC);
1383
+ `;
1384
+ var MIGRATION_004_A_REGUA_VOLTA_A_SER_APURADA = `-- ============================================================================
1385
+ -- A r\xE9gua do atendimento volta a ser APURADA
1386
+ --
1387
+ -- SINTOMA: 6.236 linhas de exig\xEAncia atravessaram do V1 e est\xE3o congeladas.
1388
+ -- Nada no V2 as recalcula: um atendimento novo nasce sem r\xE9gua, e um antigo
1389
+ -- nunca responde de novo "o que este servi\xE7o exigia". A r\xE9gua migrada \xE9 foto,
1390
+ -- n\xE3o motor.
1391
+ --
1392
+ -- O V1 resolve isso em duas fun\xE7\xF5es (\`materialize_execution_requirements\` e
1393
+ -- \`refresh_execution_requirements\`, migration 20260927130000). Esta migration \xE9
1394
+ -- o espelho delas sobre o modelo do V2, com tr\xEAs diferen\xE7as declaradas:
1395
+ --
1396
+ -- 1. CONTRATO E TERMO DE SESS\xC3O FICAM DE FORA. Os blocos d, e, f do V1
1397
+ -- dependem de \`contract_templates\` e \`generated_contracts\`, que o V2 n\xE3o
1398
+ -- modela. Emitir uma bola de contrato que nada pode resolver deixaria todo
1399
+ -- atendimento eternamente pendente \u2014 indicador errado \xE9 pior que nenhum.
1400
+ -- 2. O QUE A EXIG\xCANCIA PEDE ganha colunas. O V1 tem \`ref_id\` (o modelo de
1401
+ -- formul\xE1rio exigido); o ETL despejou isso em \`metadata.clinical.v1_ref_id\`
1402
+ -- e a tabela ficou sem discriminador \u2014 por isso h\xE1 1.378 grupos
1403
+ -- (session, kind) repetidos, que s\xE3o formul\xE1rios diferentes indistingu\xEDveis.
1404
+ -- \`ref_type\`/\`ref_id\` devolvem a pergunta; a chave \xFAnica cobre s\xF3 as linhas
1405
+ -- que este motor escreve, porque as migradas n\xE3o t\xEAm como ser desempatadas
1406
+ -- enquanto os modelos de formul\xE1rio n\xE3o chegarem.
1407
+ -- 3. DUAS BANDEIRAS DE SERVI\xC7O n\xE3o vieram do V1 (\`requires_evaluation\` e
1408
+ -- \`always_ask_used_products\`). Sem elas os blocos g e i ficariam mudos,
1409
+ -- ent\xE3o entram em \`products\` \u2014 onde o servi\xE7o mora no V2.
1410
+ --
1411
+ -- Modo: \`off\` (nada acontece) \xB7 \`shadow\` (grava e n\xE3o muda tela) \xB7 \`on\`.
1412
+ -- L\xEA-se de \`tenants.settings -> 'execution_requirements' ->> 'mode'\`.
1413
+ -- ============================================================================
1414
+
1415
+ -- \u2500\u2500\u2500 0. O que faltava para a pergunta caber \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1416
+
1417
+ ALTER TABLE public.products
1418
+ ADD COLUMN IF NOT EXISTS requires_evaluation boolean NOT NULL DEFAULT false,
1419
+ ADD COLUMN IF NOT EXISTS always_ask_used_products boolean NOT NULL DEFAULT false;
1420
+
1421
+ COMMENT ON COLUMN public.products.requires_evaluation IS
1422
+ 'Servi\xE7o que s\xF3 se executa depois de uma avalia\xE7\xE3o vinculada (bloco g da r\xE9gua).';
1423
+ COMMENT ON COLUMN public.products.always_ask_used_products IS
1424
+ 'Servi\xE7o que sempre pergunta os produtos usados, mesmo sem ficha t\xE9cnica (bloco i).';
1425
+
1426
+ ALTER TABLE public.plg_clinical_requirements
1427
+ ADD COLUMN IF NOT EXISTS ref_type text,
1428
+ ADD COLUMN IF NOT EXISTS ref_id uuid;
1429
+
1430
+ COMMENT ON COLUMN public.plg_clinical_requirements.ref_type IS
1431
+ 'O que a exig\xEAncia PEDE (form_template). N\xE3o confundir com subject_*, que \xE9 o que a RESOLVEU.';
1432
+
1433
+ -- Chave \xFAnica s\xF3 das linhas deste motor: as migradas perderam o discriminador
1434
+ -- (ver cabe\xE7alho) e colidiriam entre si.
1435
+ CREATE UNIQUE INDEX IF NOT EXISTS plg_clinical_requirements_engine_key
1436
+ ON public.plg_clinical_requirements (session_id, kind, (coalesce(ref_id, '00000000-0000-0000-0000-000000000000'::uuid)))
1437
+ WHERE metadata -> 'migration' IS NULL;
1438
+
1439
+ CREATE INDEX IF NOT EXISTS plg_clinical_requirements_booking_status
1440
+ ON public.plg_clinical_requirements (booking_id, status);
1441
+
1442
+ -- \u2500\u2500\u2500 1. O modo \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1443
+
1444
+ CREATE OR REPLACE FUNCTION public.clinical_requirements_mode(p_tenant uuid)
1445
+ RETURNS text LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO 'public'
1446
+ AS $fn$
1447
+ SELECT CASE lower(coalesce(t.settings -> 'execution_requirements' ->> 'mode', 'off'))
1448
+ WHEN 'shadow' THEN 'shadow'
1449
+ WHEN 'on' THEN 'on'
1450
+ ELSE 'off'
1451
+ END
1452
+ FROM public.tenants t WHERE t.id = p_tenant;
1453
+ $fn$;
1454
+
1455
+ -- \u2500\u2500\u2500 2. Uma linha, idempotente (o OR dos bloqueios \xE9 do V1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1456
+
1457
+ CREATE OR REPLACE FUNCTION public.clinical_requirement_upsert(
1458
+ p_tenant uuid, p_unit uuid, p_booking uuid, p_session uuid, p_party uuid, p_service uuid,
1459
+ p_kind text, p_scope text, p_ref_type text, p_ref_id uuid, p_rule text,
1460
+ p_blocks_start boolean, p_blocks_finish boolean)
1461
+ RETURNS integer LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public'
1462
+ AS $fn$
1463
+ DECLARE v_id uuid;
1464
+ BEGIN
1465
+ SELECT r.id INTO v_id FROM public.plg_clinical_requirements r
1466
+ WHERE r.session_id = p_session AND r.kind = p_kind
1467
+ AND coalesce(r.ref_id, '00000000-0000-0000-0000-000000000000'::uuid)
1468
+ = coalesce(p_ref_id, '00000000-0000-0000-0000-000000000000'::uuid)
1469
+ AND r.metadata -> 'migration' IS NULL;
1470
+
1471
+ IF v_id IS NULL THEN
1472
+ INSERT INTO public.plg_clinical_requirements (
1473
+ tenant_id, unit_id, booking_id, session_id, party_id, service_id,
1474
+ kind, scope, ref_type, ref_id, rule_sources, blocks_start, blocks_finish, status)
1475
+ VALUES (p_tenant, p_unit, p_booking, p_session, p_party, p_service,
1476
+ p_kind, p_scope, p_ref_type, p_ref_id, jsonb_build_array(p_rule),
1477
+ coalesce(p_blocks_start, false), coalesce(p_blocks_finish, false), 'pending');
1478
+ RETURN 1;
1479
+ END IF;
1480
+
1481
+ -- J\xE1 existe: soma a origem da regra e faz o OR dos bloqueios. Uma linha
1482
+ -- resolvida ou congelada n\xE3o volta a pendente por aqui.
1483
+ UPDATE public.plg_clinical_requirements r
1484
+ SET rule_sources = CASE WHEN r.rule_sources @> to_jsonb(p_rule) THEN r.rule_sources
1485
+ ELSE r.rule_sources || to_jsonb(p_rule) END,
1486
+ blocks_start = r.blocks_start OR coalesce(p_blocks_start, false),
1487
+ blocks_finish = r.blocks_finish OR coalesce(p_blocks_finish, false),
1488
+ status = CASE WHEN r.status = 'not_applicable' THEN 'pending' ELSE r.status END,
1489
+ updated_at = now()
1490
+ WHERE r.id = v_id AND r.frozen_at IS NULL;
1491
+ RETURN 0;
1492
+ END $fn$;
1493
+
1494
+ -- \u2500\u2500\u2500 3. Materializar as linhas em branco de UMA sess\xE3o \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1495
+
1496
+ CREATE OR REPLACE FUNCTION public.clinical_requirements_materialize(p_session uuid)
1497
+ RETURNS integer LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public'
1498
+ AS $fn$
1499
+ DECLARE
1500
+ s record; sv record; r record; cfg jsonb;
1501
+ v_mode text; v_n int := 0; v_booking_status text; v_rule text;
1502
+ v_is_revision boolean; v_has_parent boolean; v_rev_num int; v_kind text;
1503
+ BEGIN
1504
+ SELECT * INTO s FROM public.plg_clinical_sessions WHERE id = p_session;
1505
+ IF NOT FOUND OR s.booking_id IS NULL THEN RETURN 0; END IF;
1506
+
1507
+ v_mode := public.clinical_requirements_mode(s.tenant_id);
1508
+ IF v_mode = 'off' THEN RETURN 0; END IF;
1509
+
1510
+ SELECT a.status INTO v_booking_status FROM public.appointments a WHERE a.id = s.booking_id;
1511
+ -- Hist\xF3rico n\xE3o ganha linha: sess\xE3o j\xE1 executada em atendimento que n\xE3o est\xE1
1512
+ -- em curso \xE9 fato consumado (mesma regra do V1).
1513
+ IF s.status IN ('executed', 'invoiced') AND coalesce(v_booking_status, '') <> 'in_progress' THEN
1514
+ RETURN 0;
1515
+ END IF;
1516
+
1517
+ BEGIN
1518
+ SELECT p.service_kind, p.requires_evaluation, p.always_ask_used_products, p.category_id
1519
+ INTO sv FROM public.products p WHERE p.id = s.service_id;
1520
+ IF NOT FOUND THEN RETURN 0; END IF;
1521
+ v_kind := coalesce(sv.service_kind, 'standard');
1522
+
1523
+ -- QUEM \xC9 REVIS\xC3O. O V1 tem um booleano (\`is_revision\`) ao lado do n\xFAmero.
1524
+ -- No V2 sobrou s\xF3 o n\xFAmero \u2014 e o ETL gravou \`revision_number = 1\` em TODA
1525
+ -- sess\xE3o, ent\xE3o o n\xFAmero n\xE3o distingue nada: lido como "\xE9 revis\xE3o", ele
1526
+ -- transformou 54 de 54 sess\xF5es em revis\xE3o, tirou o item de fatura de 21
1527
+ -- delas e inventou v\xEDnculo de revis\xE3o em 43. O que de fato separa as duas
1528
+ -- coisas no V2 \xE9 o PAI: revis\xE3o aponta para a sess\xE3o original. Conferido
1529
+ -- contra as 288 exig\xEAncias migradas destes mesmos atendimentos: o V1
1530
+ -- gravou \`invoice_item\` exatamente nas 21 sess\xF5es \`standard\` sem pai, e
1531
+ -- \`revision_link\` exatamente nas 8 de \`return\` mais as 3 \`standard\` com pai.
1532
+ v_rev_num := coalesce(s.revision_number, 0);
1533
+ v_has_parent := s.parent_session_id IS NOT NULL;
1534
+ v_is_revision := v_has_parent OR v_kind = 'return';
1535
+
1536
+ cfg := coalesce((SELECT t.settings -> 'evaluation_flow' FROM public.tenants t WHERE t.id = s.tenant_id), '{}'::jsonb);
1537
+ IF jsonb_typeof(cfg) <> 'object' THEN cfg := '{}'::jsonb; END IF;
1538
+
1539
+ -- a) Formul\xE1rios universais do tenant \u2014 escopo atendimento.
1540
+ FOR r IN SELECT ft.id FROM public.plg_forms_templates ft
1541
+ WHERE ft.tenant_id = s.tenant_id AND ft.is_active AND coalesce(ft.is_deleted, false) = false
1542
+ AND coalesce(ft.required_on_attendance, false)
1543
+ LOOP
1544
+ v_n := v_n + public.clinical_requirement_upsert(s.tenant_id, s.unit_id, s.booking_id, s.id,
1545
+ s.party_id, s.service_id, 'form', 'attendance', 'form_template', r.id,
1546
+ 'forms_templates.required_on_attendance', false, false);
1547
+ END LOOP;
1548
+
1549
+ IF NOT v_has_parent THEN
1550
+ -- b) Formul\xE1rios do servi\xE7o.
1551
+ FOR r IN SELECT sd.template_id, coalesce(sd.requirement_scope, 'attendance') AS scope
1552
+ FROM public.plg_forms_service_defaults sd
1553
+ JOIN public.plg_forms_templates ft ON ft.id = sd.template_id AND ft.is_active
1554
+ WHERE sd.product_id = s.service_id AND sd.tenant_id = s.tenant_id
1555
+ LOOP
1556
+ v_n := v_n + public.clinical_requirement_upsert(s.tenant_id, s.unit_id, s.booking_id, s.id,
1557
+ s.party_id, s.service_id, 'form',
1558
+ CASE WHEN r.scope = 'service' THEN 'service' ELSE 'attendance' END,
1559
+ 'form_template', r.template_id, 'forms_service_defaults', false, false);
1560
+ END LOOP;
1561
+ ELSE
1562
+ -- c) Formul\xE1rios da revis\xE3o, pelo n\xFAmero dela. No V2 os modelos da revis\xE3o
1563
+ -- moram numa lista dentro da pr\xF3pria revis\xE3o.
1564
+ FOR r IN SELECT (e.value #>> '{}')::uuid AS template_id
1565
+ FROM public.plg_clinical_service_revisions rev,
1566
+ LATERAL jsonb_array_elements(coalesce(rev.form_template_refs, '[]'::jsonb)) e
1567
+ WHERE rev.tenant_id = s.tenant_id AND rev.service_id = s.service_id
1568
+ AND rev.revision_number = v_rev_num
1569
+ AND (e.value #>> '{}') ~ '^[0-9a-f-]{36}$'
1570
+ LOOP
1571
+ v_n := v_n + public.clinical_requirement_upsert(s.tenant_id, s.unit_id, s.booking_id, s.id,
1572
+ s.party_id, s.service_id, 'form', 'service', 'form_template', r.template_id,
1573
+ 'clinical_service_revisions.form_template_refs', false, false);
1574
+ END LOOP;
1575
+ END IF;
1576
+
1577
+ -- d, e, f) CONTRATO e TERMO DE SESS\xC3O: fora, por falta de modelo no V2.
1578
+ -- Ver o cabe\xE7alho desta migration.
1579
+
1580
+ -- g) Avalia\xE7\xE3o vinculada.
1581
+ IF v_kind = 'standard' THEN
1582
+ IF coalesce(sv.requires_evaluation, false) THEN
1583
+ v_n := v_n + public.clinical_requirement_upsert(s.tenant_id, s.unit_id, s.booking_id, s.id,
1584
+ s.party_id, s.service_id, 'evaluation', 'service', NULL, NULL,
1585
+ 'products.requires_evaluation', false, false);
1586
+ ELSIF coalesce((cfg ->> 'require_evaluation_for_kind_service')::boolean, false) THEN
1587
+ v_n := v_n + public.clinical_requirement_upsert(s.tenant_id, s.unit_id, s.booking_id, s.id,
1588
+ s.party_id, s.service_id, 'evaluation', 'service', NULL, NULL,
1589
+ 'evaluation_flow.require_evaluation_for_kind_service', false, false);
1590
+ END IF;
1591
+ END IF;
1592
+
1593
+ -- h) Revis\xE3o vinculada ao servi\xE7o original: trava come\xE7ar E terminar.
1594
+ IF v_is_revision AND coalesce((cfg ->> 'revision_link_required')::boolean, false) THEN
1595
+ v_n := v_n + public.clinical_requirement_upsert(s.tenant_id, s.unit_id, s.booking_id, s.id,
1596
+ s.party_id, s.service_id, 'revision_link', 'service', NULL, NULL,
1597
+ 'evaluation_flow.revision_link_required', true, true);
1598
+ END IF;
1599
+
1600
+ -- i) Produtos utilizados: ficha t\xE9cnica, "sempre perguntar", ou j\xE1 lan\xE7ado.
1601
+ v_rule := NULL;
1602
+ IF EXISTS (SELECT 1 FROM public.plg_inventory_recipes rc
1603
+ WHERE rc.product_id = s.service_id AND rc.tenant_id = s.tenant_id
1604
+ AND coalesce(rc.is_active, true)) THEN
1605
+ v_rule := 'inventory_recipes';
1606
+ ELSIF coalesce(sv.always_ask_used_products, false) THEN
1607
+ v_rule := 'products.always_ask_used_products';
1608
+ ELSIF EXISTS (SELECT 1 FROM public.plg_clinical_session_products sp
1609
+ WHERE sp.session_id = s.id
1610
+ OR (s.order_item_id IS NOT NULL AND sp.order_item_id = s.order_item_id)) THEN
1611
+ v_rule := 'clinical_session_products';
1612
+ END IF;
1613
+ IF v_rule IS NOT NULL THEN
1614
+ v_n := v_n + public.clinical_requirement_upsert(s.tenant_id, s.unit_id, s.booking_id, s.id,
1615
+ s.party_id, s.service_id, 'products', 'service', NULL, NULL, v_rule, false, false);
1616
+ END IF;
1617
+
1618
+ -- j) Item de fatura: servi\xE7o comum, n\xE3o-revis\xE3o.
1619
+ IF v_kind = 'standard' AND NOT v_has_parent THEN
1620
+ v_n := v_n + public.clinical_requirement_upsert(s.tenant_id, s.unit_id, s.booking_id, s.id,
1621
+ s.party_id, s.service_id, 'invoice_item', 'service', NULL, NULL, 'billing', false, false);
1622
+ END IF;
1623
+ EXCEPTION WHEN others THEN
1624
+ -- Nunca derruba quem chama: a fonte (a sess\xE3o) n\xE3o pode falhar por causa da r\xE9gua.
1625
+ RAISE WARNING 'clinical_requirements_materialize(%): %', p_session, sqlerrm;
1626
+ RETURN 0;
1627
+ END;
1628
+ RETURN v_n;
1629
+ END $fn$;
1630
+
1631
+ -- \u2500\u2500\u2500 4. Reapurar as linhas de UM atendimento \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1632
+
1633
+ CREATE OR REPLACE FUNCTION public.clinical_requirements_refresh(p_booking uuid, p_final boolean DEFAULT false)
1634
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public'
1635
+ AS $fn$
1636
+ DECLARE
1637
+ a record; v_mode text; v_now timestamptz := now(); v_eval jsonb;
1638
+ n_mat int := 0; n_reopen int := 0;
1639
+ -- \`v_sessao\`, n\xE3o \`r\`: plpgsql resolve o nome da VARI\xC1VEL antes do apelido da
1640
+ -- tabela, ent\xE3o um \`record r\` declarado aqui sequestra todo \`r.coluna\` dos
1641
+ -- UPDATEs abaixo \u2014 e o erro que sai \xE9 "record r has no field booking_id".
1642
+ v_sessao record;
1643
+ BEGIN
1644
+ SELECT ap.id, ap.tenant_id, ap.party_id, ap.status INTO a
1645
+ FROM public.appointments ap WHERE ap.id = p_booking;
1646
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
1647
+
1648
+ v_mode := public.clinical_requirements_mode(a.tenant_id);
1649
+ IF v_mode = 'off' THEN RETURN jsonb_build_object('ok', true, 'mode', v_mode, 'skipped', true); END IF;
1650
+
1651
+ p_final := coalesce(p_final, false) AND a.status = 'completed';
1652
+
1653
+ BEGIN
1654
+ PERFORM pg_advisory_xact_lock(hashtextextended('clinical_req:' || p_booking::text, 0));
1655
+ IF a.status = 'completed' AND NOT p_final THEN
1656
+ RETURN jsonb_build_object('ok', true, 'mode', v_mode, 'frozen', true);
1657
+ END IF;
1658
+
1659
+ -- 1) Materializa o que falta (sess\xE3o nova, ficha t\xE9cnica criada depois).
1660
+ FOR v_sessao IN SELECT cs.id FROM public.plg_clinical_sessions cs WHERE cs.booking_id = p_booking
1661
+ LOOP
1662
+ n_mat := n_mat + public.clinical_requirements_materialize(v_sessao.id);
1663
+ END LOOP;
1664
+
1665
+ v_eval := coalesce((SELECT t.settings -> 'evaluation_flow' FROM public.tenants t WHERE t.id = a.tenant_id), '{}'::jsonb);
1666
+ IF jsonb_typeof(v_eval) <> 'object' THEN v_eval := '{}'::jsonb; END IF;
1667
+
1668
+ -- 1b) Regra que saiu da configura\xE7\xE3o para de bloquear (o upsert reabre se voltar).
1669
+ UPDATE public.plg_clinical_requirements r
1670
+ SET status = 'not_applicable', candidate_type = NULL, candidate_id = NULL, updated_at = v_now
1671
+ WHERE r.booking_id = p_booking AND r.status = 'pending' AND r.frozen_at IS NULL
1672
+ AND r.metadata -> 'migration' IS NULL
1673
+ AND ((r.kind = 'revision_link' AND NOT coalesce((v_eval ->> 'revision_link_required')::boolean, false))
1674
+ OR (r.kind = 'evaluation'
1675
+ AND r.rule_sources = '["evaluation_flow.require_evaluation_for_kind_service"]'::jsonb
1676
+ AND NOT coalesce((v_eval ->> 'require_evaluation_for_kind_service')::boolean, false)));
1677
+
1678
+ -- 2) Reabre o que perdeu a fonte. Linha congelada n\xE3o se mexe.
1679
+ UPDATE public.plg_clinical_requirements r
1680
+ SET status = 'pending', subject_type = NULL, subject_id = NULL, resolved_via = NULL,
1681
+ resolved_at = NULL, valid_until = NULL, updated_at = v_now
1682
+ WHERE r.booking_id = p_booking AND r.status = 'resolved' AND r.frozen_at IS NULL
1683
+ AND ((r.subject_type = 'documents' AND NOT EXISTS (SELECT 1 FROM public.documents d WHERE d.id = r.subject_id))
1684
+ OR (r.subject_type = 'clinical_sessions' AND NOT EXISTS (SELECT 1 FROM public.plg_clinical_sessions x WHERE x.id = r.subject_id))
1685
+ OR (r.subject_type = 'items' AND NOT EXISTS (SELECT 1 FROM public.items oi WHERE oi.id = r.subject_id)));
1686
+ GET DIAGNOSTICS n_reopen = ROW_COUNT;
1687
+
1688
+ -- 3) Formul\xE1rio universal: a \xFAltima resposta do cliente, em qualquer
1689
+ -- atendimento, ainda dentro da validade do modelo.
1690
+ UPDATE public.plg_clinical_requirements r
1691
+ SET status = 'resolved', subject_type = 'documents', subject_id = x.id,
1692
+ resolved_via = CASE WHEN x.subject_id = p_booking THEN 'attendance' ELSE 'auto_client' END,
1693
+ resolved_at = v_now,
1694
+ valid_until = CASE WHEN x.validity_days IS NULL THEN NULL
1695
+ ELSE x.eff + make_interval(days => x.validity_days) END,
1696
+ updated_at = v_now
1697
+ FROM (SELECT DISTINCT ON (fd.template_id) d.id, fd.template_id, d.subject_id,
1698
+ coalesce(d.updated_at, d.created_at) AS eff, ft.validity_days
1699
+ FROM public.plg_forms_documents fd
1700
+ JOIN public.documents d ON d.id = fd.document_id
1701
+ JOIN public.plg_forms_templates ft ON ft.id = fd.template_id
1702
+ WHERE d.person_id = a.party_id AND d.tenant_id = a.tenant_id
1703
+ ORDER BY fd.template_id, coalesce(d.updated_at, d.created_at) DESC) x
1704
+ WHERE r.booking_id = p_booking AND r.status = 'pending' AND r.kind = 'form'
1705
+ AND r.scope = 'attendance' AND r.ref_id = x.template_id
1706
+ AND r.rule_sources @> '["forms_templates.required_on_attendance"]'::jsonb
1707
+ AND (x.validity_days IS NULL OR x.eff + make_interval(days => x.validity_days) > v_now);
1708
+
1709
+ -- 4) Demais formul\xE1rios: qualquer resposta DESTE atendimento com o modelo.
1710
+ UPDATE public.plg_clinical_requirements r
1711
+ SET status = 'resolved', subject_type = 'documents', subject_id = x.id,
1712
+ resolved_via = 'attendance', resolved_at = v_now, updated_at = v_now
1713
+ FROM (SELECT DISTINCT ON (fd.template_id, coalesce(fd.product_id, '00000000-0000-0000-0000-000000000000'::uuid))
1714
+ d.id, fd.template_id, fd.product_id
1715
+ FROM public.plg_forms_documents fd
1716
+ JOIN public.documents d ON d.id = fd.document_id
1717
+ WHERE d.subject_type = 'appointment' AND d.subject_id = p_booking
1718
+ ORDER BY fd.template_id, coalesce(fd.product_id, '00000000-0000-0000-0000-000000000000'::uuid),
1719
+ coalesce(d.updated_at, d.created_at) DESC) x
1720
+ WHERE r.booking_id = p_booking AND r.status = 'pending' AND r.kind = 'form'
1721
+ AND r.ref_id = x.template_id
1722
+ AND NOT (r.rule_sources @> '["forms_templates.required_on_attendance"]'::jsonb)
1723
+ AND (x.product_id IS NULL OR r.scope = 'attendance' OR x.product_id = r.service_id);
1724
+
1725
+ -- 5) Avalia\xE7\xE3o vinculada: a sess\xE3o aponta a avalia\xE7\xE3o que a autorizou.
1726
+ UPDATE public.plg_clinical_requirements r
1727
+ SET status = 'resolved', subject_type = 'clinical_sessions', subject_id = x.eval_id,
1728
+ resolved_via = CASE WHEN x.same_booking THEN 'attendance' ELSE 'auto_client' END,
1729
+ resolved_at = v_now, updated_at = v_now
1730
+ FROM (SELECT r2.id AS req_id, e.id AS eval_id, (e.booking_id = p_booking) AS same_booking
1731
+ FROM public.plg_clinical_requirements r2
1732
+ JOIN public.plg_clinical_sessions cs ON cs.id = r2.session_id
1733
+ JOIN public.plg_clinical_sessions e ON e.id = cs.source_evaluation_id
1734
+ WHERE r2.booking_id = p_booking AND r2.kind = 'evaluation' AND r2.frozen_at IS NULL
1735
+ AND (r2.status = 'pending' OR (r2.status = 'resolved' AND r2.resolved_via = 'legacy_grace'))) x
1736
+ WHERE r.id = x.req_id;
1737
+
1738
+ -- 5b) Gra\xE7a legada: o cliente j\xE1 tem atendimento conclu\xEDdo com servi\xE7o de
1739
+ -- avalia\xE7\xE3o. \xC9 a mesma concess\xE3o do V1, e vai marcada como tal.
1740
+ UPDATE public.plg_clinical_requirements r
1741
+ SET status = 'resolved', subject_type = 'appointments', subject_id = x.booking_id,
1742
+ resolved_via = 'legacy_grace', resolved_at = v_now, updated_at = v_now
1743
+ FROM (SELECT ap.id AS booking_id
1744
+ FROM public.appointments ap
1745
+ JOIN public.appointment_items ai ON ai.booking_id = ap.id
1746
+ JOIN public.products p ON p.id = ai.service_id AND p.service_kind = 'evaluation'
1747
+ WHERE ap.party_id = a.party_id AND ap.tenant_id = a.tenant_id AND ap.status = 'completed'
1748
+ ORDER BY ap.starts_at DESC NULLS LAST LIMIT 1) x
1749
+ WHERE r.booking_id = p_booking AND r.status = 'pending' AND r.kind = 'evaluation';
1750
+
1751
+ -- 6) Revis\xE3o vinculada ao servi\xE7o original.
1752
+ UPDATE public.plg_clinical_requirements r
1753
+ SET status = 'resolved', subject_type = 'clinical_sessions', subject_id = cs.parent_session_id,
1754
+ resolved_via = 'attendance', resolved_at = v_now, updated_at = v_now
1755
+ FROM public.plg_clinical_sessions cs
1756
+ WHERE cs.id = r.session_id AND r.booking_id = p_booking
1757
+ AND r.status = 'pending' AND r.kind = 'revision_link'
1758
+ AND cs.parent_session_id IS NOT NULL
1759
+ AND EXISTS (SELECT 1 FROM public.plg_clinical_sessions p WHERE p.id = cs.parent_session_id);
1760
+
1761
+ -- 7) Produtos: a sess\xE3o declara que foram conferidos.
1762
+ UPDATE public.plg_clinical_requirements r
1763
+ SET status = 'resolved', subject_type = 'clinical_sessions', subject_id = cs.id,
1764
+ resolved_via = 'attendance', resolved_at = v_now, updated_at = v_now
1765
+ FROM public.plg_clinical_sessions cs
1766
+ WHERE cs.id = r.session_id AND r.booking_id = p_booking
1767
+ AND r.status = 'pending' AND r.kind = 'products'
1768
+ AND coalesce(cs.products_initialized, false);
1769
+
1770
+ -- 8) Item de pedido vinculado. A linha do pedido no V2 \xE9 \`public.items\` \u2014
1771
+ -- n\xE3o existe \`order_items\`; o pedido \xE9 o documento e o item \xE9 dele.
1772
+ UPDATE public.plg_clinical_requirements r
1773
+ SET status = 'resolved', subject_type = 'items', subject_id = oi.id,
1774
+ resolved_via = 'attendance', resolved_at = v_now, updated_at = v_now
1775
+ FROM public.plg_clinical_sessions cs
1776
+ JOIN public.items oi ON oi.id = cs.order_item_id
1777
+ WHERE cs.id = r.session_id AND r.booking_id = p_booking
1778
+ AND r.status = 'pending' AND r.kind = 'invoice_item';
1779
+
1780
+ -- 9) Congelamento: s\xF3 na \xFAltima passada, com o atendimento conclu\xEDdo.
1781
+ IF p_final THEN
1782
+ UPDATE public.plg_clinical_requirements
1783
+ SET frozen_at = coalesce(frozen_at, v_now), updated_at = v_now
1784
+ WHERE booking_id = p_booking;
1785
+ END IF;
1786
+
1787
+ RETURN jsonb_build_object(
1788
+ 'ok', true, 'mode', v_mode, 'materialized', n_mat, 'reopened', n_reopen,
1789
+ 'pending', (SELECT count(*) FROM public.plg_clinical_requirements WHERE booking_id = p_booking AND status = 'pending'),
1790
+ 'resolved', (SELECT count(*) FROM public.plg_clinical_requirements WHERE booking_id = p_booking AND status = 'resolved'),
1791
+ 'frozen', p_final);
1792
+ EXCEPTION WHEN others THEN
1793
+ RAISE WARNING 'clinical_requirements_refresh(%): %', p_booking, sqlerrm;
1794
+ RETURN jsonb_build_object('ok', false, 'error', sqlerrm);
1795
+ END;
1796
+ END $fn$;
1797
+
1798
+ -- \u2500\u2500\u2500 5. Quem pode chamar \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1799
+ -- Escrita s\xF3 pelas fun\xE7\xF5es (definer). O app chama o refresh; o resto \xE9 interno.
1800
+
1801
+ REVOKE ALL ON FUNCTION public.clinical_requirement_upsert(uuid, uuid, uuid, uuid, uuid, uuid, text, text, text, uuid, text, boolean, boolean) FROM public, anon, authenticated;
1802
+ REVOKE ALL ON FUNCTION public.clinical_requirements_materialize(uuid) FROM public, anon, authenticated;
1803
+ GRANT EXECUTE ON FUNCTION public.clinical_requirements_mode(uuid) TO authenticated;
1804
+ GRANT EXECUTE ON FUNCTION public.clinical_requirements_refresh(uuid, boolean) TO authenticated;
1805
+ `;
1806
+ var MIGRATION_005_COMECAR_O_ATENDIMENTO_E_UM_GESTO_SO = `-- ============================================================================
1807
+ -- Come\xE7ar o atendimento \xE9 UM gesto \u2014 e uma transa\xE7\xE3o s\xF3
1808
+ --
1809
+ -- No V1, "Iniciar Atendimento" grava tr\xEAs coisas no mesmo instante: o
1810
+ -- agendamento vira \`in_progress\`, a execu\xE7\xE3o de cada servi\xE7o nasce, e a r\xE9gua \xE9
1811
+ -- materializada (\`rpc/refresh_execution_requirements\`). Se qualquer uma falhar
1812
+ -- sozinha o atendimento fica meio aberto: status trocado sem r\xE9gua, ou r\xE9gua
1813
+ -- sem sess\xE3o \u2014 e a tela mostra uma bola que n\xE3o pertence a nada.
1814
+ --
1815
+ -- Por isso \xE9 uma fun\xE7\xE3o e n\xE3o tr\xEAs chamadas do app. A recep\xE7\xE3o e o profissional
1816
+ -- podem apertar o bot\xE3o ao mesmo tempo, e o segundo n\xE3o pode duplicar sess\xE3o.
1817
+ --
1818
+ -- QUEM PODE: o V1 s\xF3 monta a r\xE9gua para quem est\xE1 VINCULADO A UM PROFISSIONAL,
1819
+ -- e s\xF3 enxerga o atendimento DELE com aquele cliente. Aqui a regra \xE9 a mesma \u2014
1820
+ -- e a recusa \xE9 FALADA (\`reason\`), n\xE3o silenciosa: a tela precisa dizer por que
1821
+ -- o bot\xE3o n\xE3o serve, em vez de sumir com ele.
1822
+ -- ============================================================================
1823
+
1824
+ CREATE OR REPLACE FUNCTION public.clinical_attendance_start(p_booking uuid)
1825
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
1826
+ AS $fn$
1827
+ DECLARE
1828
+ a record; v_person uuid; v_created int := 0; v_item record; v_refresh jsonb;
1829
+ BEGIN
1830
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.party_id, ap.assignee_id, ap.status, ap.starts_at
1831
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
1832
+ IF NOT FOUND THEN
1833
+ RETURN jsonb_build_object('ok', false, 'reason', 'not_found');
1834
+ END IF;
1835
+
1836
+ -- A pessoa por tr\xE1s do login. Nulo = login sem ficha (o dono que criou o
1837
+ -- espa\xE7o, a licen\xE7a de suporte): v\xEA tudo, atende ningu\xE9m.
1838
+ v_person := public.current_person_id();
1839
+ IF v_person IS NULL THEN
1840
+ RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional');
1841
+ END IF;
1842
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
1843
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
1844
+ END IF;
1845
+ -- Atender o que n\xE3o \xE9 de hoje abriria um atendimento paralelo ao agendado \u2014
1846
+ -- o mesmo motivo que fez o V1 trocar o bot\xE3o conforme o dia.
1847
+ IF a.starts_at::date <> (now() AT TIME ZONE 'America/Sao_Paulo')::date THEN
1848
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_de_hoje');
1849
+ END IF;
1850
+ IF a.status IN ('completed', 'cancelled', 'no_show') THEN
1851
+ RETURN jsonb_build_object('ok', false, 'reason', 'ja_encerrado', 'status', a.status);
1852
+ END IF;
1853
+
1854
+ -- Uma sess\xE3o por servi\xE7o do agendamento. \`booking_item_id\` \xE9 a chave de
1855
+ -- idempot\xEAncia: apertar duas vezes (ou duas pessoas ao mesmo tempo) n\xE3o
1856
+ -- duplica nada.
1857
+ FOR v_item IN
1858
+ SELECT ai.id, ai.service_id, ai.assignee_id
1859
+ FROM public.appointment_items ai
1860
+ WHERE ai.booking_id = p_booking
1861
+ LOOP
1862
+ INSERT INTO public.plg_clinical_sessions (
1863
+ tenant_id, unit_id, status, booking_id, booking_item_id, party_id,
1864
+ assignee_id, performed_by_id, service_id, scheduled_for, started_at)
1865
+ SELECT a.tenant_id, a.unit_id, 'in_service', a.id, v_item.id, a.party_id,
1866
+ coalesce(v_item.assignee_id, a.assignee_id), v_person, v_item.service_id,
1867
+ a.starts_at, now()
1868
+ WHERE NOT EXISTS (
1869
+ SELECT 1 FROM public.plg_clinical_sessions cs
1870
+ WHERE cs.booking_id = p_booking AND cs.booking_item_id = v_item.id);
1871
+ IF FOUND THEN v_created := v_created + 1; END IF;
1872
+ END LOOP;
1873
+
1874
+ UPDATE public.appointments
1875
+ SET status = 'in_progress', updated_at = now()
1876
+ WHERE id = p_booking AND status <> 'in_progress';
1877
+
1878
+ v_refresh := public.clinical_requirements_refresh(p_booking);
1879
+
1880
+ RETURN jsonb_build_object(
1881
+ 'ok', true,
1882
+ 'sessoes_criadas', v_created,
1883
+ 'sessoes', (SELECT count(*) FROM public.plg_clinical_sessions WHERE booking_id = p_booking),
1884
+ 'regua', v_refresh);
1885
+ END $fn$;
1886
+
1887
+ GRANT EXECUTE ON FUNCTION public.clinical_attendance_start(uuid) TO authenticated;
1888
+ `;
1889
+ var MIGRATION_006_CONTRATAR_NAO_E_PAGAR = `-- ============================================================================
1890
+ -- CONTRATAR n\xE3o \xE9 PAGAR
1891
+ --
1892
+ -- O passo mais delicado do turno do injetor, e a demonstra\xE7\xE3o do V1 para nele
1893
+ -- para explicar: *"Mas at\xE9 ent\xE3o ele n\xE3o pagou ainda? N\xE3o pagou \u2014 mas ele vai
1894
+ -- executar."* Contratar cria a D\xCDVIDA; receber \xE9 papel da recep\xE7\xE3o, em outra
1895
+ -- tela e outro momento.
1896
+ --
1897
+ -- No V1 isto grava \`generated_contracts\` + \`invoices\` + \`invoice_items\`. No V2
1898
+ -- o documento \xE9 o PEDIDO, e h\xE1 uma porta s\xF3 para abri-lo: \`order_create\` \u2014 a
1899
+ -- mesma que o PDV, o totem e a agenda usam. Nada aqui escreve uma linha de
1900
+ -- fatura \xE0 m\xE3o; a cobran\xE7a nasce depois, quando o atendimento fecha.
1901
+ --
1902
+ -- Por que uma fun\xE7\xE3o e n\xE3o tr\xEAs chamadas do app: contratar \xE9 abrir o pedido,
1903
+ -- ligar cada sess\xE3o \xE0 sua linha e reapurar a r\xE9gua. Pedido aberto com a sess\xE3o
1904
+ -- solta \xE9 um atendimento que cobra e n\xE3o sabe o que executou.
1905
+ -- ============================================================================
1906
+
1907
+ CREATE OR REPLACE FUNCTION public.clinical_contract_services(p_booking uuid, p_lines jsonb)
1908
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
1909
+ AS $fn$
1910
+ DECLARE
1911
+ a record; v_person uuid; v_order uuid; v_line jsonb; v_item uuid; v_n int := 0;
1912
+ v_rpc_lines jsonb := '[]'::jsonb; v_idx int := 0;
1913
+ BEGIN
1914
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.party_id, ap.assignee_id, ap.status, ap.order_id
1915
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
1916
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
1917
+
1918
+ v_person := public.current_person_id();
1919
+ IF v_person IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional'); END IF;
1920
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
1921
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
1922
+ END IF;
1923
+ IF a.status <> 'in_progress' THEN
1924
+ RETURN jsonb_build_object('ok', false, 'reason', 'atendimento_nao_esta_em_curso');
1925
+ END IF;
1926
+ IF jsonb_typeof(p_lines) <> 'array' OR jsonb_array_length(p_lines) = 0 THEN
1927
+ RETURN jsonb_build_object('ok', false, 'reason', 'nada_marcado');
1928
+ END IF;
1929
+
1930
+ -- As linhas, no formato que \`order_create\` j\xE1 entende.
1931
+ FOR v_line IN SELECT * FROM jsonb_array_elements(p_lines)
1932
+ LOOP
1933
+ v_rpc_lines := v_rpc_lines || jsonb_build_object(
1934
+ 'product_id', v_line ->> 'service_id',
1935
+ 'name', v_line ->> 'name',
1936
+ 'quantity', coalesce((v_line ->> 'quantity')::numeric, 1),
1937
+ 'unit_price', coalesce((v_line ->> 'unit_price')::numeric, 0),
1938
+ 'sort_order', v_idx);
1939
+ v_idx := v_idx + 1;
1940
+ END LOOP;
1941
+
1942
+ -- O pedido do atendimento. \`idempotency_key\` pelo agendamento: dois toques
1943
+ -- no "Contratar" n\xE3o abrem duas contas para a mesma visita.
1944
+ IF a.order_id IS NULL THEN
1945
+ v_order := public.order_create(
1946
+ p_kind => 'appointment',
1947
+ p_lines => v_rpc_lines,
1948
+ p_party_id => a.party_id,
1949
+ p_unit_id => a.unit_id,
1950
+ p_status => 'scheduled',
1951
+ p_assignee_id => a.assignee_id,
1952
+ p_metadata => jsonb_build_object('agenda', jsonb_build_object('booking_id', p_booking), 'source', 'clinical:contratacao'),
1953
+ p_idempotency_key => 'clinical-contract:' || p_booking::text);
1954
+ UPDATE public.appointments SET order_id = v_order, updated_at = now() WHERE id = p_booking;
1955
+ ELSE
1956
+ -- Pedido j\xE1 existe (a agenda abriu na marca\xE7\xE3o): acrescenta o que falta.
1957
+ v_order := a.order_id;
1958
+ v_idx := coalesce((SELECT max(i.sort_order) + 1 FROM public.items i WHERE i.order_id = v_order), 0);
1959
+ FOR v_line IN SELECT * FROM jsonb_array_elements(p_lines)
1960
+ LOOP
1961
+ INSERT INTO public.items (tenant_id, unit_id, order_id, product_id, name, quantity, unit_price, total, sort_order)
1962
+ VALUES (a.tenant_id, a.unit_id, v_order, (v_line ->> 'service_id')::uuid, v_line ->> 'name',
1963
+ coalesce((v_line ->> 'quantity')::numeric, 1),
1964
+ coalesce((v_line ->> 'unit_price')::numeric, 0),
1965
+ coalesce((v_line ->> 'quantity')::numeric, 1) * coalesce((v_line ->> 'unit_price')::numeric, 0),
1966
+ v_idx);
1967
+ v_idx := v_idx + 1;
1968
+ END LOOP;
1969
+ END IF;
1970
+
1971
+ -- Cada sess\xE3o passa a apontar a SUA linha. Sem isto o pedido cobra e o
1972
+ -- atendimento n\xE3o sabe o que executou \u2014 e a bola "Conta do atendimento"
1973
+ -- nunca fecha, porque \xE9 exatamente este v\xEDnculo que ela procura.
1974
+ UPDATE public.plg_clinical_sessions cs
1975
+ SET order_item_id = i.id,
1976
+ status = CASE WHEN cs.status IN ('quoted', 'pending', 'scheduled') THEN 'contracted' ELSE cs.status END,
1977
+ updated_at = now()
1978
+ FROM public.items i
1979
+ WHERE cs.booking_id = p_booking
1980
+ AND cs.order_item_id IS NULL
1981
+ AND i.order_id = v_order
1982
+ AND i.product_id = cs.service_id
1983
+ AND NOT EXISTS (SELECT 1 FROM public.plg_clinical_sessions o
1984
+ WHERE o.order_item_id = i.id AND o.id <> cs.id);
1985
+ GET DIAGNOSTICS v_n = ROW_COUNT;
1986
+
1987
+ RETURN jsonb_build_object(
1988
+ 'ok', true, 'order_id', v_order, 'sessoes_ligadas', v_n,
1989
+ 'total', (SELECT coalesce(sum(i.total), 0) FROM public.items i WHERE i.order_id = v_order),
1990
+ 'regua', public.clinical_requirements_refresh(p_booking));
1991
+ END $fn$;
1992
+
1993
+ GRANT EXECUTE ON FUNCTION public.clinical_contract_services(uuid, jsonb) TO authenticated;
1994
+ `;
1995
+ var MIGRATION_007_FINALIZAR_ACENDE_O_BALCAO = `-- ============================================================================
1996
+ -- FINALIZAR acende o balc\xE3o
1997
+ --
1998
+ -- O \xFAltimo gesto do profissional \xE9 o PRIMEIRO da recep\xE7\xE3o. No V1, o instante em
1999
+ -- que o atendimento vai para \`completed\` sem \`checkout_confirmed_at\` acende o
2000
+ -- rodap\xE9 do balc\xE3o \u2014 com contador, pulso e bipe.
2001
+ --
2002
+ -- Duas decis\xF5es do V1 que v\xEAm junto, e que s\xE3o o oposto uma da outra:
2003
+ --
2004
+ -- \xB7 o aviso de servi\xE7os n\xE3o executados AVISA E DEIXA PASSAR. Travar criaria
2005
+ -- um atendimento sem sa\xEDda pela interface; quem n\xE3o executou cancela o item
2006
+ -- na conta do cliente. Por isso \`p_force\`: a primeira chamada devolve a
2007
+ -- lista, a segunda executa.
2008
+ -- \xB7 a exig\xEAncia que bloqueia TERMINAR (\`blocks_finish\`) \xE9 outra coisa, e essa
2009
+ -- trava de verdade \u2014 \xE9 o termo de sess\xE3o do V1, que existe para n\xE3o haver
2010
+ -- execu\xE7\xE3o sem assinatura.
2011
+ --
2012
+ -- E o que N\xC3O se grava aqui: \`checkout_confirmed_at\`. Ele \xE9 da recep\xE7\xE3o, e \xE9 o
2013
+ -- que tira o cart\xE3o da fila \u2014 receber e conferir s\xE3o duas coisas.
2014
+ -- ============================================================================
2015
+
2016
+ CREATE OR REPLACE FUNCTION public.clinical_attendance_finish(p_booking uuid, p_force boolean DEFAULT false)
2017
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2018
+ AS $fn$
2019
+ DECLARE
2020
+ a record; v_person uuid; v_bloqueia jsonb; v_nao_executados jsonb;
2021
+ v_avisados int := 0; v_total numeric := 0; v_cliente text;
2022
+ BEGIN
2023
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.party_id, ap.assignee_id, ap.status, ap.order_id
2024
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
2025
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
2026
+
2027
+ v_person := public.current_person_id();
2028
+ IF v_person IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional'); END IF;
2029
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
2030
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
2031
+ END IF;
2032
+ IF a.status <> 'in_progress' THEN
2033
+ RETURN jsonb_build_object('ok', false, 'reason', 'atendimento_nao_esta_em_curso');
2034
+ END IF;
2035
+
2036
+ -- A trava de verdade: exig\xEAncia que impede TERMINAR.
2037
+ SELECT coalesce(jsonb_agg(jsonb_build_object('kind', r.kind, 'service_id', r.service_id)), '[]'::jsonb)
2038
+ INTO v_bloqueia
2039
+ FROM public.plg_clinical_requirements r
2040
+ WHERE r.booking_id = p_booking AND r.blocks_finish AND r.status = 'pending';
2041
+ IF jsonb_array_length(v_bloqueia) > 0 THEN
2042
+ RETURN jsonb_build_object('ok', false, 'reason', 'exigencia_bloqueia', 'itens', v_bloqueia);
2043
+ END IF;
2044
+
2045
+ -- O aviso que n\xE3o trava: servi\xE7os contratados e ainda n\xE3o executados.
2046
+ SELECT coalesce(jsonb_agg(p.name ORDER BY p.name), '[]'::jsonb) INTO v_nao_executados
2047
+ FROM public.plg_clinical_sessions cs
2048
+ JOIN public.products p ON p.id = cs.service_id
2049
+ WHERE cs.booking_id = p_booking AND cs.status <> 'executed';
2050
+ IF jsonb_array_length(v_nao_executados) > 0 AND NOT coalesce(p_force, false) THEN
2051
+ RETURN jsonb_build_object('ok', false, 'reason', 'servicos_nao_executados', 'itens', v_nao_executados);
2052
+ END IF;
2053
+
2054
+ -- "Finalizar agora registra estes servi\xE7os como executados" \u2014 texto do V1.
2055
+ UPDATE public.plg_clinical_sessions
2056
+ SET status = 'executed', ended_at = coalesce(ended_at, now()), updated_at = now()
2057
+ WHERE booking_id = p_booking AND status <> 'executed';
2058
+
2059
+ UPDATE public.appointments
2060
+ SET status = 'completed', updated_at = now()
2061
+ WHERE id = p_booking;
2062
+
2063
+ -- Congela a trilha: depois de encerrado, a r\xE9gua n\xE3o se reapura.
2064
+ PERFORM public.clinical_requirements_refresh(p_booking, true);
2065
+
2066
+ SELECT coalesce(sum(i.total), 0) INTO v_total FROM public.items i WHERE i.order_id = a.order_id;
2067
+ SELECT pe.name INTO v_cliente FROM public.people pe WHERE pe.id = a.party_id;
2068
+
2069
+ -- O BALC\xC3O ACENDE.
2070
+ --
2071
+ -- Quem recebe: a recep\xE7\xE3o da conta. Onde n\xE3o houver ningu\xE9m com o papel de
2072
+ -- recep\xE7\xE3o \u2014 e \xE9 o caso do tenant migrado, com 0 membros nele \u2014, cai para
2073
+ -- gerente e dono. Um aviso que n\xE3o chega a ningu\xE9m deixaria a conta parada
2074
+ -- sem que nada na tela dissesse por qu\xEA.
2075
+ WITH alvo AS (
2076
+ SELECT m.user_id
2077
+ FROM app.memberships m
2078
+ JOIN app.roles r ON r.id = m.role_id
2079
+ WHERE m.tenant_id = a.tenant_id AND coalesce(m.active, true)
2080
+ AND r.key IN ('recepcao', 'reception')
2081
+ UNION ALL
2082
+ SELECT m.user_id
2083
+ FROM app.memberships m
2084
+ JOIN app.roles r ON r.id = m.role_id
2085
+ WHERE m.tenant_id = a.tenant_id AND coalesce(m.active, true)
2086
+ AND r.key IN ('owner', 'manager')
2087
+ AND NOT EXISTS (
2088
+ SELECT 1 FROM app.memberships m2 JOIN app.roles r2 ON r2.id = m2.role_id
2089
+ WHERE m2.tenant_id = a.tenant_id AND coalesce(m2.active, true)
2090
+ AND r2.key IN ('recepcao', 'reception'))
2091
+ )
2092
+ INSERT INTO public.notifications (tenant_id, user_id, title, body, type, link, subject_type, subject_id)
2093
+ SELECT a.tenant_id, alvo.user_id,
2094
+ 'Checkout pendente',
2095
+ coalesce(v_cliente, 'Cliente') || ' terminou o atendimento'
2096
+ -- O dinheiro escrito como o Brasil escreve. \`to_char\` usa o
2097
+ -- \`lc_numeric\` do BANCO para o grupo e a v\xEDrgula, e o cluster est\xE1
2098
+ -- em C: sa\xEDa "R$ 999.00" no aviso de uma recep\xE7\xE3o brasileira. A
2099
+ -- troca \xE9 feita \xE0 m\xE3o para n\xE3o depender de locale nenhum.
2100
+ || CASE WHEN v_total > 0 THEN ' \xB7 R$ ' ||
2101
+ replace(replace(replace(to_char(v_total, 'FM999G999G999D00'), ',', '\xA7'), '.', ','), '\xA7', '.')
2102
+ ELSE '' END,
2103
+ 'checkout_pendente', '#/checkin', 'appointment', p_booking
2104
+ FROM alvo
2105
+ ON CONFLICT (user_id, subject_type, subject_id, type) WHERE subject_id IS NOT NULL DO NOTHING;
2106
+ GET DIAGNOSTICS v_avisados = ROW_COUNT;
2107
+
2108
+ RETURN jsonb_build_object(
2109
+ 'ok', true, 'avisados', v_avisados, 'total', v_total,
2110
+ 'executados', (SELECT count(*) FROM public.plg_clinical_sessions WHERE booking_id = p_booking AND status = 'executed'));
2111
+ END $fn$;
2112
+
2113
+ GRANT EXECUTE ON FUNCTION public.clinical_attendance_finish(uuid, boolean) TO authenticated;
2114
+ `;
2115
+ var MIGRATION_008_CONFERIR_NAO_E_RECEBER = `-- ============================================================================
2116
+ -- CONFERIR n\xE3o \xE9 RECEBER
2117
+ --
2118
+ -- O V1 \xE9 expl\xEDcito: *"Receber move dinheiro; concluir checkout \xE9 a recep\xE7\xE3o
2119
+ -- dizendo 'conferi a sess\xE3o'. O cart\xE3o fica na fila enquanto houver valor em
2120
+ -- aberto OU checkout por confirmar."* S\xE3o duas coisas, e junt\xE1-las numa s\xF3
2121
+ -- faria a fila esvaziar quando o dinheiro entra \u2014 mesmo que ningu\xE9m tenha
2122
+ -- olhado o que foi executado.
2123
+ --
2124
+ -- \`checkout_confirmed_at\` mora no \`metadata->'agenda'\` do agendamento, que \xE9
2125
+ -- onde o ETL do V1 o deixou: 332 atendimentos migrados j\xE1 o carregam ali.
2126
+ -- Escrever numa coluna nova faria o hist\xF3rico e o presente responderem em
2127
+ -- lugares diferentes.
2128
+ -- ============================================================================
2129
+
2130
+ CREATE OR REPLACE FUNCTION public.clinical_checkout_confirm(p_booking uuid)
2131
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2132
+ AS $fn$
2133
+ DECLARE
2134
+ a record; v_person uuid; v_aberto numeric := 0;
2135
+ BEGIN
2136
+ SELECT ap.id, ap.tenant_id, ap.status, ap.order_id, ap.metadata
2137
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
2138
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
2139
+
2140
+ -- Quem confere \xE9 quem est\xE1 no balc\xE3o. Diferente de iniciar o atendimento,
2141
+ -- aqui N\xC3O se exige ser o profissional do agendamento: conferir \xE9 da
2142
+ -- recep\xE7\xE3o, e a recep\xE7\xE3o n\xE3o atende ningu\xE9m.
2143
+ IF auth.uid() IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_sessao'); END IF;
2144
+ v_person := public.current_person_id();
2145
+
2146
+ IF a.status <> 'completed' THEN
2147
+ RETURN jsonb_build_object('ok', false, 'reason', 'atendimento_nao_terminou');
2148
+ END IF;
2149
+ IF a.metadata -> 'agenda' ->> 'checkout_confirmed_at' IS NOT NULL THEN
2150
+ RETURN jsonb_build_object('ok', true, 'ja_confirmado', true);
2151
+ END IF;
2152
+
2153
+ -- S\xF3 o ramo \`agenda\` \xE9 reescrito, e ele \xE9 reescrito a partir do que j\xE1
2154
+ -- estava l\xE1: o \`||\` sobre o objeto inteiro apagaria o que o ETL do V1
2155
+ -- deixou no metadata do agendamento.
2156
+ UPDATE public.appointments ap
2157
+ SET metadata = coalesce(ap.metadata, '{}'::jsonb)
2158
+ || jsonb_build_object('agenda',
2159
+ coalesce(ap.metadata -> 'agenda', '{}'::jsonb)
2160
+ || jsonb_build_object(
2161
+ 'checkout_confirmed_at', to_jsonb(now()),
2162
+ 'checkout_confirmed_by', to_jsonb(coalesce(v_person::text, auth.uid()::text)))),
2163
+ updated_at = now()
2164
+ WHERE ap.id = p_booking;
2165
+
2166
+ -- O aviso cumpriu o papel dele. Deix\xE1-lo n\xE3o lido faria o sino cobrar uma
2167
+ -- confer\xEAncia que j\xE1 aconteceu.
2168
+ UPDATE public.notifications
2169
+ SET read = true
2170
+ WHERE subject_type = 'appointment' AND subject_id = p_booking AND NOT read;
2171
+
2172
+ SELECT coalesce(sum(i.total), 0) INTO v_aberto FROM public.items i WHERE i.order_id = a.order_id;
2173
+
2174
+ RETURN jsonb_build_object('ok', true, 'total', v_aberto);
2175
+ END $fn$;
2176
+
2177
+ GRANT EXECUTE ON FUNCTION public.clinical_checkout_confirm(uuid) TO authenticated;
2178
+ `;
2179
+ var MIGRATION_009_O_BOTAO_DE_COBRAR_COBRA = `-- ============================================================================
2180
+ -- O bot\xE3o de cobrar COBRA
2181
+ --
2182
+ -- SINTOMA, visto na tela: a conta do cliente mostra "Este atendimento ainda n\xE3o
2183
+ -- tem cobran\xE7a \xB7 **Gerar recebimento**", e o clique n\xE3o faz nada. Nenhum
2184
+ -- movimento nasce, nenhuma mensagem aparece. O bot\xE3o existe porque o painel o
2185
+ -- oferece, e quem o liga \xE9 o APP hospedeiro \u2014 que neste app n\xE3o liga.
2186
+ --
2187
+ -- Bot\xE3o morto \xE9 pior que bot\xE3o ausente: quem clica confia no bot\xE3o.
2188
+ --
2189
+ -- O caminho do dinheiro no V2 \xE9 um s\xF3: o receb\xEDvel \xE9 levantado quando o PEDIDO
2190
+ -- FECHA (\`orders_raise_receivable_on_close\`). Ent\xE3o cobrar \xE9 fechar o pedido do
2191
+ -- atendimento \u2014 e n\xE3o escrever fatura \xE0 m\xE3o, que \xE9 o que a regra do SDK pro\xEDbe.
2192
+ --
2193
+ -- \xC9 aqui, e n\xE3o na contrata\xE7\xE3o, porque o V1 separa as duas coisas: contratar
2194
+ -- cria a d\xEDvida; cobrar \xE9 da recep\xE7\xE3o, depois de conferir o que foi executado.
2195
+ -- ============================================================================
2196
+
2197
+ CREATE OR REPLACE FUNCTION public.clinical_checkout_charge(p_booking uuid)
2198
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2199
+ AS $fn$
2200
+ DECLARE
2201
+ a record; v_linhas int; v_total numeric; v_mov int;
2202
+ BEGIN
2203
+ SELECT ap.id, ap.tenant_id, ap.status, ap.order_id INTO a
2204
+ FROM public.appointments ap WHERE ap.id = p_booking;
2205
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
2206
+ IF auth.uid() IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_sessao'); END IF;
2207
+
2208
+ IF a.order_id IS NULL THEN
2209
+ RETURN jsonb_build_object('ok', false, 'reason', 'nada_contratado');
2210
+ END IF;
2211
+
2212
+ SELECT count(*), coalesce(sum(i.total), 0) INTO v_linhas, v_total
2213
+ FROM public.items i WHERE i.order_id = a.order_id;
2214
+ IF v_linhas = 0 THEN
2215
+ RETURN jsonb_build_object('ok', false, 'reason', 'nada_contratado');
2216
+ END IF;
2217
+
2218
+ -- Idempotente: o pedido j\xE1 fechado devolve o que existe, sem levantar um
2219
+ -- segundo receb\xEDvel para a mesma visita.
2220
+ SELECT count(*) INTO v_mov FROM public.plg_financial_movements m WHERE m.invoice_id = a.order_id;
2221
+ IF v_mov > 0 THEN
2222
+ RETURN jsonb_build_object('ok', true, 'ja_cobrado', true, 'total', v_total);
2223
+ END IF;
2224
+
2225
+ UPDATE public.orders SET status = 'completed', updated_at = now()
2226
+ WHERE id = a.order_id AND status <> 'completed';
2227
+
2228
+ SELECT count(*) INTO v_mov FROM public.plg_financial_movements m WHERE m.invoice_id = a.order_id;
2229
+ RETURN jsonb_build_object('ok', true, 'total', v_total, 'movimentos', v_mov);
2230
+ END $fn$;
2231
+
2232
+ GRANT EXECUTE ON FUNCTION public.clinical_checkout_charge(uuid) TO authenticated;
2233
+ `;
2234
+ var MIGRATION_010_A_INDICACAO_VAI_PARA_O_FUNIL = `-- ============================================================================
2235
+ -- A INDICA\xC7\xC3O vai para o funil
2236
+ --
2237
+ -- O V1 escreve, na pr\xF3pria tela da avalia\xE7\xE3o: *"Indique procedimentos ou
2238
+ -- produtos para o cliente \u2014 eles alimentam as recomenda\xE7\xF5es do CRM e a etapa de
2239
+ -- or\xE7amento."* E a rede confirma: concluir a avalia\xE7\xE3o faz \`POST
2240
+ -- opportunity_recommendations\`.
2241
+ --
2242
+ -- **Indica\xE7\xE3o n\xE3o \xE9 venda.** \xC9 o que o profissional recomenda; virar cobran\xE7a \xE9
2243
+ -- outra decis\xE3o, do paciente, na contrata\xE7\xE3o. As duas palavras existem
2244
+ -- separadas no V1 porque separam dois momentos e duas responsabilidades.
2245
+ --
2246
+ -- No V2 a cesta do interesse pende de um NEG\xD3CIO (\`plg_crm_deal_interests.
2247
+ -- deal_id\` \xE9 NOT NULL). Ent\xE3o a avalia\xE7\xE3o abre \u2014 ou reaproveita \u2014 um neg\xF3cio do
2248
+ -- cliente e pendura ali o que foi indicado. \xC9 o mesmo desenho do V1, com o
2249
+ -- vocabul\xE1rio do V2: a indica\xE7\xE3o nasce no atendimento e vive no funil.
2250
+ -- ============================================================================
2251
+
2252
+ CREATE OR REPLACE FUNCTION public.clinical_evaluation_complete(p_booking uuid, p_lines jsonb DEFAULT '[]'::jsonb)
2253
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2254
+ AS $fn$
2255
+ DECLARE
2256
+ a record; v_person uuid; v_deal uuid; v_line jsonb; v_interest uuid;
2257
+ v_n int := 0; v_resolvidas int := 0; v_cliente text;
2258
+ BEGIN
2259
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.party_id, ap.assignee_id, ap.status
2260
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
2261
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
2262
+
2263
+ v_person := public.current_person_id();
2264
+ IF v_person IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional'); END IF;
2265
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
2266
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
2267
+ END IF;
2268
+ IF a.status <> 'in_progress' THEN
2269
+ RETURN jsonb_build_object('ok', false, 'reason', 'atendimento_nao_esta_em_curso');
2270
+ END IF;
2271
+
2272
+ IF jsonb_typeof(p_lines) = 'array' AND jsonb_array_length(p_lines) > 0 THEN
2273
+ SELECT pe.name INTO v_cliente FROM public.people pe WHERE pe.id = a.party_id;
2274
+
2275
+ -- O neg\xF3cio do cliente. Reaproveita o que estiver aberto: duas avalia\xE7\xF5es
2276
+ -- no mesmo m\xEAs s\xE3o a mesma conversa, e abrir um funil por atendimento faria
2277
+ -- o quadro do CRM virar hist\xF3rico de agenda.
2278
+ SELECT d.id INTO v_deal FROM public.plg_crm_deals d
2279
+ WHERE d.tenant_id = a.tenant_id AND d.contact_id = a.party_id AND d.status = 'open'
2280
+ ORDER BY d.created_at DESC LIMIT 1;
2281
+
2282
+ IF v_deal IS NULL THEN
2283
+ INSERT INTO public.plg_crm_deals (tenant_id, unit_id, title, contact_id, assigned_to_id, metadata)
2284
+ VALUES (a.tenant_id, a.unit_id,
2285
+ 'Avalia\xE7\xE3o \u2014 ' || coalesce(v_cliente, 'cliente'), a.party_id, a.assignee_id,
2286
+ jsonb_build_object('source', 'clinical:avaliacao', 'booking_id', p_booking))
2287
+ RETURNING id INTO v_deal;
2288
+ END IF;
2289
+
2290
+ FOR v_line IN SELECT * FROM jsonb_array_elements(p_lines)
2291
+ LOOP
2292
+ -- Idempotente por (neg\xF3cio, produto): indicar duas vezes o mesmo
2293
+ -- procedimento \xE9 corrigir a quantidade, n\xE3o criar uma segunda indica\xE7\xE3o.
2294
+ SELECT i.id INTO v_interest FROM public.plg_crm_deal_interests i
2295
+ WHERE i.deal_id = v_deal AND i.product_id = (v_line ->> 'service_id')::uuid;
2296
+
2297
+ IF v_interest IS NULL THEN
2298
+ INSERT INTO public.plg_crm_deal_interests
2299
+ (tenant_id, unit_id, deal_id, product_id, quantity, origin, status, notes, metadata)
2300
+ VALUES (a.tenant_id, a.unit_id, v_deal, (v_line ->> 'service_id')::uuid,
2301
+ greatest(coalesce((v_line ->> 'quantity')::numeric, 1), 1),
2302
+ 'indication', 'open', nullif(v_line ->> 'notes', ''),
2303
+ jsonb_build_object('source', 'clinical:avaliacao', 'booking_id', p_booking))
2304
+ RETURNING id INTO v_interest;
2305
+ v_n := v_n + 1;
2306
+ ELSE
2307
+ UPDATE public.plg_crm_deal_interests
2308
+ SET quantity = greatest(coalesce((v_line ->> 'quantity')::numeric, 1), 1), updated_at = now()
2309
+ WHERE id = v_interest;
2310
+ END IF;
2311
+
2312
+ INSERT INTO public.plg_crm_deal_interest_appointments (tenant_id, unit_id, appointment_id, interest_id)
2313
+ SELECT a.tenant_id, a.unit_id, p_booking, v_interest
2314
+ WHERE NOT EXISTS (SELECT 1 FROM public.plg_crm_deal_interest_appointments x
2315
+ WHERE x.appointment_id = p_booking AND x.interest_id = v_interest);
2316
+ END LOOP;
2317
+ END IF;
2318
+
2319
+ -- A bola da avalia\xE7\xE3o fecha apontando a SESS\xC3O em que ela aconteceu. O V1
2320
+ -- resolve pelo v\xEDnculo com a execu\xE7\xE3o da avalia\xE7\xE3o; aqui a avalia\xE7\xE3o \xE9 este
2321
+ -- atendimento, e o que ela deixa registrado \xE9 o que ele indicou.
2322
+ UPDATE public.plg_clinical_requirements r
2323
+ SET status = 'resolved', subject_type = 'clinical_sessions', subject_id = r.session_id,
2324
+ resolved_via = 'attendance', resolved_at = now(), updated_at = now()
2325
+ WHERE r.booking_id = p_booking AND r.kind = 'evaluation' AND r.status = 'pending'
2326
+ AND r.frozen_at IS NULL AND r.session_id IS NOT NULL;
2327
+ GET DIAGNOSTICS v_resolvidas = ROW_COUNT;
2328
+
2329
+ RETURN jsonb_build_object('ok', true, 'deal_id', v_deal, 'indicacoes', v_n, 'bolas_fechadas', v_resolvidas);
2330
+ END $fn$;
2331
+
2332
+ GRANT EXECUTE ON FUNCTION public.clinical_evaluation_complete(uuid, jsonb) TO authenticated;
2333
+ `;
2334
+ var MIGRATION_011_INTERESSE_E_INDICACAO_NA_MESMA_LINHA = `-- ============================================================================
2335
+ -- INTERESSE e INDICA\xC7\xC3O na MESMA LINHA
2336
+ --
2337
+ -- O desfecho do desenho do V1, e a captura que o documenta mostra a linha
2338
+ -- inteira:
2339
+ --
2340
+ -- \xC1cido Hialur\xF4nico \u2014 R$ 999,00
2341
+ -- Interesse do cliente \xB7 Indicado pelo profissional
2342
+ --
2343
+ -- S\xE3o tr\xEAs palavras e tr\xEAs momentos: **interesse** \xE9 o que o cliente pediu ao
2344
+ -- marcar; **indica\xE7\xE3o** \xE9 o que o profissional recomendou na avalia\xE7\xE3o;
2345
+ -- **contrata\xE7\xE3o** \xE9 o que virou cobran\xE7a. O mesmo servi\xE7o pode carregar as duas
2346
+ -- primeiras \u2014 e a\xED ele aparece UMA vez, com as duas origens somadas no r\xF3tulo.
2347
+ --
2348
+ -- Duas linhas para o mesmo procedimento fariam a recep\xE7\xE3o cobrar duas vezes; e
2349
+ -- esconder a origem faria o paciente ouvir "o senhor pediu" sobre algo que foi
2350
+ -- recomendado. Por isso a fus\xE3o \xE9 do BANCO, e n\xE3o de cada tela que precisar
2351
+ -- dela.
2352
+ -- ============================================================================
2353
+
2354
+ CREATE OR REPLACE FUNCTION public.clinical_contract_candidates(p_booking uuid)
2355
+ RETURNS TABLE (
2356
+ service_id uuid,
2357
+ name text,
2358
+ price numeric,
2359
+ quantity numeric,
2360
+ from_interest boolean,
2361
+ from_indication boolean,
2362
+ already_contracted boolean
2363
+ ) LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO 'public', 'app'
2364
+ AS $fn$
2365
+ WITH alvo AS (
2366
+ SELECT ap.id, ap.tenant_id, ap.party_id, ap.order_id FROM public.appointments ap WHERE ap.id = p_booking
2367
+ ),
2368
+ -- O que o cliente pediu ao marcar.
2369
+ interesse AS (
2370
+ SELECT ai.service_id, max(ai.name) AS name, max(ai.price) AS price, count(*)::numeric AS qtd
2371
+ FROM public.appointment_items ai, alvo
2372
+ WHERE ai.booking_id = alvo.id AND ai.service_id IS NOT NULL
2373
+ GROUP BY ai.service_id
2374
+ ),
2375
+ -- O que o profissional recomendou \u2014 deste atendimento ou do neg\xF3cio aberto
2376
+ -- do cliente, que \xE9 onde a avalia\xE7\xE3o pendura o que indicou.
2377
+ indicacao AS (
2378
+ SELECT i.product_id AS service_id, max(i.quantity) AS qtd
2379
+ FROM public.plg_crm_deal_interests i
2380
+ JOIN public.plg_crm_deals d ON d.id = i.deal_id, alvo
2381
+ WHERE i.tenant_id = alvo.tenant_id AND i.status = 'open'
2382
+ AND (d.contact_id = alvo.party_id
2383
+ OR EXISTS (SELECT 1 FROM public.plg_crm_deal_interest_appointments x
2384
+ WHERE x.interest_id = i.id AND x.appointment_id = alvo.id))
2385
+ GROUP BY i.product_id
2386
+ ),
2387
+ -- O que j\xE1 virou cobran\xE7a nesta visita: aparece marcado, n\xE3o some \u2014 sumir
2388
+ -- faria a lista mentir sobre o que foi combinado.
2389
+ contratado AS (
2390
+ SELECT it.product_id AS service_id FROM public.items it, alvo
2391
+ WHERE alvo.order_id IS NOT NULL AND it.order_id = alvo.order_id AND it.product_id IS NOT NULL
2392
+ )
2393
+ SELECT
2394
+ coalesce(i.service_id, n.service_id) AS service_id,
2395
+ coalesce(i.name, p.name) AS name,
2396
+ coalesce(nullif(i.price, 0), p.price, 0) AS price,
2397
+ greatest(coalesce(i.qtd, 0), coalesce(n.qtd, 0), 1) AS quantity,
2398
+ i.service_id IS NOT NULL AS from_interest,
2399
+ n.service_id IS NOT NULL AS from_indication,
2400
+ EXISTS (SELECT 1 FROM contratado c WHERE c.service_id = coalesce(i.service_id, n.service_id)) AS already_contracted
2401
+ FROM interesse i
2402
+ FULL OUTER JOIN indicacao n ON n.service_id = i.service_id
2403
+ LEFT JOIN public.products p ON p.id = coalesce(i.service_id, n.service_id)
2404
+ ORDER BY 2;
2405
+ $fn$;
2406
+
2407
+ GRANT EXECUTE ON FUNCTION public.clinical_contract_candidates(uuid) TO authenticated;
2408
+ `;
2409
+ var MIGRATION_012_O_QUE_FOI_USADO_ESPERA_APROVACAO = `-- ============================================================================
2410
+ -- O QUE FOI USADO espera aprova\xE7\xE3o
2411
+ --
2412
+ -- A bola de produtos do V1, e a frase que a define: *"Ele vem tudo pra c\xE1
2413
+ -- primeiro. Vem pra aprova\xE7\xE3o de dispensa."* **Nada baixa aqui.** O consumo
2414
+ -- declarado pelo profissional cai na fila da Auditoria de Uso, e \xE9 l\xE1 que
2415
+ -- algu\xE9m confirma \u2014 ou corrige a quantidade lan\xE7ada errada.
2416
+ --
2417
+ -- Registrar consumo baixando estoque na hora seria transformar a mem\xF3ria de
2418
+ -- quem atende em movimento cont\xE1bil sem confer\xEAncia, que \xE9 exatamente o que a
2419
+ -- auditoria existe para evitar.
2420
+ --
2421
+ -- \`is_audited = false\` \xE9 o estado inicial, e \xE9 o que p\xF5e a linha na fila.
2422
+ -- ============================================================================
2423
+
2424
+ CREATE OR REPLACE FUNCTION public.clinical_products_record(p_booking uuid, p_lines jsonb DEFAULT '[]'::jsonb)
2425
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2426
+ AS $fn$
2427
+ DECLARE
2428
+ a record; v_person uuid; v_line jsonb; v_session uuid; v_n int := 0; v_marcadas int := 0;
2429
+ BEGIN
2430
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.assignee_id, ap.status
2431
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
2432
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
2433
+
2434
+ v_person := public.current_person_id();
2435
+ IF v_person IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional'); END IF;
2436
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
2437
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
2438
+ END IF;
2439
+ IF a.status <> 'in_progress' THEN
2440
+ RETURN jsonb_build_object('ok', false, 'reason', 'atendimento_nao_esta_em_curso');
2441
+ END IF;
2442
+
2443
+ FOR v_line IN SELECT * FROM jsonb_array_elements(coalesce(p_lines, '[]'::jsonb))
2444
+ LOOP
2445
+ -- A sess\xE3o do SERVI\xC7O que consumiu. O V1 desenha um bloco por servi\xE7o
2446
+ -- justamente porque a mesma seringa gasta em procedimentos diferentes, e
2447
+ -- juntar tudo num monte perde de qual execu\xE7\xE3o veio.
2448
+ SELECT cs.id INTO v_session FROM public.plg_clinical_sessions cs
2449
+ WHERE cs.booking_id = p_booking AND cs.service_id = (v_line ->> 'service_id')::uuid
2450
+ ORDER BY cs.created_at LIMIT 1;
2451
+ IF v_session IS NULL THEN CONTINUE; END IF;
2452
+
2453
+ INSERT INTO public.plg_clinical_session_products
2454
+ (tenant_id, unit_id, session_id, product_id, assignee_id, used_quantity, used_unit_id, executed_on, is_audited)
2455
+ SELECT a.tenant_id, a.unit_id, v_session, (v_line ->> 'product_id')::uuid, v_person,
2456
+ greatest(coalesce((v_line ->> 'quantity')::numeric, 1), 0),
2457
+ nullif(v_line ->> 'unit_id', '')::uuid, current_date, false
2458
+ WHERE NOT EXISTS (
2459
+ SELECT 1 FROM public.plg_clinical_session_products sp
2460
+ WHERE sp.session_id = v_session AND sp.product_id = (v_line ->> 'product_id')::uuid);
2461
+ IF FOUND THEN
2462
+ v_n := v_n + 1;
2463
+ ELSE
2464
+ UPDATE public.plg_clinical_session_products
2465
+ SET used_quantity = greatest(coalesce((v_line ->> 'quantity')::numeric, 1), 0), updated_at = now()
2466
+ WHERE session_id = v_session AND product_id = (v_line ->> 'product_id')::uuid AND NOT is_audited;
2467
+ END IF;
2468
+ END LOOP;
2469
+
2470
+ -- Conferido \xE9 conferido, mesmo que n\xE3o tenha sido usado nada: "n\xE3o usei
2471
+ -- produto neste procedimento" \xE9 uma resposta, e sem poder d\xE1-la a bola ficaria
2472
+ -- pendente para sempre em quem n\xE3o gasta insumo.
2473
+ UPDATE public.plg_clinical_sessions
2474
+ SET products_initialized = true, updated_at = now()
2475
+ WHERE booking_id = p_booking AND coalesce(products_initialized, false) = false;
2476
+ GET DIAGNOSTICS v_marcadas = ROW_COUNT;
2477
+
2478
+ RETURN jsonb_build_object(
2479
+ 'ok', true, 'lancados', v_n, 'sessoes_conferidas', v_marcadas,
2480
+ 'regua', public.clinical_requirements_refresh(p_booking));
2481
+ END $fn$;
2482
+
2483
+ GRANT EXECUTE ON FUNCTION public.clinical_products_record(uuid, jsonb) TO authenticated;
2484
+ `;
2485
+ var MIGRATION_013_O_QUE_COUBER_HOJE = `-- ============================================================================
2486
+ -- O QUE COUBER HOJE
2487
+ --
2488
+ -- *"Marque os servi\xE7os que ser\xE3o executados agora. Os demais ficam contratados
2489
+ -- para execu\xE7\xE3o em outro atendimento."* \xC9 o di\xE1logo que o V1 abre depois da
2490
+ -- contrata\xE7\xE3o, e ele existe por causa de uma frase da demonstra\xE7\xE3o: *"o labial
2491
+ -- veio com uma festa amanh\xE3, n\xE3o quero ficar com o l\xE1bio roxo"*.
2492
+ --
2493
+ -- \xC9 este passo que separa **contratado** de **executado** \u2014 e \xE9 dele que nasce
2494
+ -- o saldo *a executar* na conta do cliente. Sem ele, contratar tr\xEAs sess\xF5es
2495
+ -- significaria executar tr\xEAs sess\xF5es no mesmo dia, o que n\xE3o \xE9 como uma cl\xEDnica
2496
+ -- funciona.
2497
+ --
2498
+ -- O que N\xC3O se executa hoje n\xE3o vira pend\xEAncia do atendimento: fica contratado,
2499
+ -- pago ou a pagar, esperando outra data.
2500
+ -- ============================================================================
2501
+
2502
+ CREATE OR REPLACE FUNCTION public.clinical_execute_services(p_booking uuid, p_service_ids uuid[])
2503
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2504
+ AS $fn$
2505
+ DECLARE
2506
+ a record; v_person uuid; v_executadas int := 0; v_adiadas int := 0;
2507
+ BEGIN
2508
+ SELECT ap.id, ap.assignee_id, ap.status INTO a FROM public.appointments ap WHERE ap.id = p_booking;
2509
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
2510
+
2511
+ v_person := public.current_person_id();
2512
+ IF v_person IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional'); END IF;
2513
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
2514
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
2515
+ END IF;
2516
+ IF a.status <> 'in_progress' THEN
2517
+ RETURN jsonb_build_object('ok', false, 'reason', 'atendimento_nao_esta_em_curso');
2518
+ END IF;
2519
+
2520
+ UPDATE public.plg_clinical_sessions cs
2521
+ SET status = 'executed', ended_at = coalesce(cs.ended_at, now()), updated_at = now()
2522
+ WHERE cs.booking_id = p_booking
2523
+ AND cs.service_id = ANY (coalesce(p_service_ids, ARRAY[]::uuid[]))
2524
+ AND cs.status <> 'executed';
2525
+ GET DIAGNOSTICS v_executadas = ROW_COUNT;
2526
+
2527
+ -- O que ficou de fora volta a CONTRATADO \u2014 e n\xE3o a pendente: foi combinado e
2528
+ -- continua combinado, s\xF3 que para outra data. Desmarcar depois de ter
2529
+ -- executado por engano \xE9 o caso que esta linha resolve.
2530
+ UPDATE public.plg_clinical_sessions cs
2531
+ SET status = 'contracted', ended_at = NULL, updated_at = now()
2532
+ WHERE cs.booking_id = p_booking
2533
+ AND NOT (cs.service_id = ANY (coalesce(p_service_ids, ARRAY[]::uuid[])))
2534
+ AND cs.status = 'executed';
2535
+ GET DIAGNOSTICS v_adiadas = ROW_COUNT;
2536
+
2537
+ RETURN jsonb_build_object('ok', true, 'executadas', v_executadas, 'adiadas', v_adiadas);
2538
+ END $fn$;
2539
+
2540
+ GRANT EXECUTE ON FUNCTION public.clinical_execute_services(uuid, uuid[]) TO authenticated;
2541
+ `;
2542
+ var MIGRATION_014_O_PAGO_A_EXECUTAR_DEIXA_DE_SER_INVISIVEL = `-- ============================================================================
2543
+ -- O "PAGO A EXECUTAR" deixa de ser invis\xEDvel
2544
+ --
2545
+ -- O tipo \`ClientAccount\` do financeiro traz este coment\xE1rio, escrito quando o
2546
+ -- porte come\xE7ou:
2547
+ --
2548
+ -- "\`paidToExecute\` (o 'pago a executar' do V1) \xE9 o valor j\xE1 recebido de
2549
+ -- servi\xE7o ainda n\xE3o prestado: num sal\xE3o isso \xE9 PASSIVO, n\xE3o receita. Fica
2550
+ -- opcional porque o V2 ainda n\xE3o tem o eixo de EXECU\xC7\xC3O \u2014 modela pagamento e
2551
+ -- n\xE3o modela entrega \u2014, e um zero fixo ali mentiria sobre uma d\xEDvida."
2552
+ --
2553
+ -- O eixo passou a existir: \`plg_clinical_sessions.status\` separa **contratado**
2554
+ -- de **executado**, e a etapa "o que couber hoje" \xE9 quem move uma para a outra.
2555
+ -- Ent\xE3o a conta pode responder \u2014 e a regra de honestidade se inverte: agora
2556
+ -- OMITIR o n\xFAmero esconderia a d\xEDvida.
2557
+ --
2558
+ -- A vista \xE9 do plugin cl\xEDnico porque o dado \xE9 dele. O financeiro l\xEA se ela
2559
+ -- existir; onde o prontu\xE1rio n\xE3o est\xE1 instalado, a conta continua sem o cart\xE3o,
2560
+ -- que \xE9 a resposta certa para quem n\xE3o tem execu\xE7\xE3o para acompanhar.
2561
+ -- ============================================================================
2562
+
2563
+ CREATE OR REPLACE VIEW public.v_clinical_to_execute AS
2564
+ WITH sessao AS (
2565
+ SELECT
2566
+ cs.tenant_id,
2567
+ cs.party_id,
2568
+ cs.order_item_id,
2569
+ cs.status,
2570
+ i.order_id,
2571
+ coalesce(i.total, 0) AS item_total
2572
+ FROM public.plg_clinical_sessions cs
2573
+ JOIN public.items i ON i.id = cs.order_item_id
2574
+ WHERE cs.party_id IS NOT NULL
2575
+ AND cs.status IN ('contracted', 'quoted', 'in_service', 'scheduled', 'pending')
2576
+ ),
2577
+ -- Quanto do PEDIDO j\xE1 foi recebido, em propor\xE7\xE3o: o pagamento \xE9 por parcela e
2578
+ -- n\xE3o por item, ent\xE3o a fatia paga de cada item \xE9 a fatia paga do pedido.
2579
+ pago AS (
2580
+ SELECT m.invoice_id AS order_id,
2581
+ sum(coalesce(m.paid_amount, 0)) AS pago,
2582
+ nullif(sum(coalesce(m.amount, 0)), 0) AS total
2583
+ FROM public.plg_financial_movements m
2584
+ WHERE m.direction = 'credit'
2585
+ GROUP BY m.invoice_id
2586
+ )
2587
+ SELECT
2588
+ s.tenant_id,
2589
+ s.party_id,
2590
+ sum(s.item_total * coalesce(p.pago / p.total, 0))::numeric(14,2) AS paid_to_execute,
2591
+ sum(s.item_total * (1 - coalesce(p.pago / p.total, 0)))::numeric(14,2) AS open_to_execute,
2592
+ count(*)::int AS sessions_to_execute
2593
+ FROM sessao s
2594
+ LEFT JOIN pago p ON p.order_id = s.order_id
2595
+ GROUP BY s.tenant_id, s.party_id;
2596
+
2597
+ COMMENT ON VIEW public.v_clinical_to_execute IS
2598
+ 'O que o cliente j\xE1 contratou e ainda N\xC3O foi executado, separado em pago e em aberto. O "pago a executar" do V1 \xE9 passivo: dinheiro recebido de servi\xE7o que a casa ainda deve prestar.';
2599
+
2600
+ GRANT SELECT ON public.v_clinical_to_execute TO authenticated;
2601
+ `;
2602
+ var MIGRATION_015_A_REVISAO_APONTA_O_QUE_REVISA = `-- ============================================================================
2603
+ -- A REVIS\xC3O aponta O QUE ela revisa
2604
+ --
2605
+ -- Revis\xE3o \xE9 o retorno de um procedimento que j\xE1 foi feito \u2014 e ela s\xF3 significa
2606
+ -- alguma coisa se disser DE QUAL. Sem o v\xEDnculo, o hist\xF3rico do paciente fica
2607
+ -- com um "Revis\xE3o" solto, e ningu\xE9m consegue responder, meses depois, o que foi
2608
+ -- revisado nem se ainda estava no prazo.
2609
+ --
2610
+ -- Por isso a exig\xEAncia \`revision_link\` do V1 \xE9 a \xFAnica que trava as DUAS pontas:
2611
+ -- \`blocks_start\` e \`blocks_finish\`. N\xE3o se come\xE7a uma revis\xE3o sem saber do qu\xEA,
2612
+ -- e n\xE3o se encerra sem ter dito.
2613
+ --
2614
+ -- O modal do V1 mudou em 21/09 (\`2e1a119ef\`): passou a listar **todo servi\xE7o
2615
+ -- executado**, com o **prazo \xE0 vista**, em vez de s\xF3 os candidatos filtrados \u2014
2616
+ -- porque quem atende sabe reconhecer o procedimento na lista, e um filtro
2617
+ -- silencioso esconde justamente o caso fora do padr\xE3o.
2618
+ -- ============================================================================
2619
+
2620
+ CREATE OR REPLACE FUNCTION public.clinical_revision_candidates(p_booking uuid)
2621
+ RETURNS TABLE (
2622
+ session_id uuid,
2623
+ service_id uuid,
2624
+ service_name text,
2625
+ executed_on timestamptz,
2626
+ deadline_days integer,
2627
+ days_since integer,
2628
+ within_deadline boolean
2629
+ ) LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO 'public', 'app'
2630
+ AS $fn$
2631
+ WITH alvo AS (
2632
+ SELECT ap.tenant_id, ap.party_id FROM public.appointments ap WHERE ap.id = p_booking
2633
+ )
2634
+ SELECT
2635
+ cs.id,
2636
+ cs.service_id,
2637
+ p.name,
2638
+ coalesce(cs.ended_at, cs.scheduled_for) AS executed_on,
2639
+ rev.deadline_days,
2640
+ (current_date - coalesce(cs.ended_at, cs.scheduled_for)::date)::int AS days_since,
2641
+ -- Prazo ausente n\xE3o vira "fora do prazo": vira SEM prazo, e a tela diz isso.
2642
+ CASE WHEN rev.deadline_days IS NULL THEN NULL
2643
+ ELSE (current_date - coalesce(cs.ended_at, cs.scheduled_for)::date) <= rev.deadline_days
2644
+ END AS within_deadline
2645
+ FROM public.plg_clinical_sessions cs
2646
+ JOIN alvo a ON a.tenant_id = cs.tenant_id AND a.party_id = cs.party_id
2647
+ LEFT JOIN public.products p ON p.id = cs.service_id
2648
+ LEFT JOIN LATERAL (
2649
+ SELECT r.deadline_days FROM public.plg_clinical_service_revisions r
2650
+ WHERE r.tenant_id = cs.tenant_id AND r.service_id = cs.service_id
2651
+ ORDER BY r.revision_number LIMIT 1
2652
+ ) rev ON true
2653
+ WHERE cs.status = 'executed'
2654
+ AND cs.booking_id IS DISTINCT FROM p_booking
2655
+ ORDER BY coalesce(cs.ended_at, cs.scheduled_for) DESC NULLS LAST
2656
+ LIMIT 50;
2657
+ $fn$;
2658
+
2659
+ CREATE OR REPLACE FUNCTION public.clinical_link_revision(p_session uuid, p_parent_session uuid)
2660
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2661
+ AS $fn$
2662
+ DECLARE
2663
+ s record; v_person uuid; v_booking uuid;
2664
+ BEGIN
2665
+ SELECT cs.id, cs.booking_id, cs.tenant_id, cs.party_id INTO s
2666
+ FROM public.plg_clinical_sessions cs WHERE cs.id = p_session;
2667
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
2668
+
2669
+ v_person := public.current_person_id();
2670
+ IF v_person IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional'); END IF;
2671
+
2672
+ -- O original tem de ser do MESMO paciente. Revisar o procedimento de outra
2673
+ -- pessoa n\xE3o \xE9 engano de digita\xE7\xE3o: \xE9 prontu\xE1rio trocado.
2674
+ IF NOT EXISTS (
2675
+ SELECT 1 FROM public.plg_clinical_sessions p
2676
+ WHERE p.id = p_parent_session AND p.party_id = s.party_id AND p.tenant_id = s.tenant_id
2677
+ ) THEN
2678
+ RETURN jsonb_build_object('ok', false, 'reason', 'original_de_outro_paciente');
2679
+ END IF;
2680
+
2681
+ UPDATE public.plg_clinical_sessions
2682
+ SET parent_session_id = p_parent_session, updated_at = now()
2683
+ WHERE id = p_session;
2684
+
2685
+ v_booking := s.booking_id;
2686
+ RETURN jsonb_build_object('ok', true, 'regua', public.clinical_requirements_refresh(v_booking));
2687
+ END $fn$;
2688
+
2689
+ GRANT EXECUTE ON FUNCTION public.clinical_revision_candidates(uuid) TO authenticated;
2690
+ GRANT EXECUTE ON FUNCTION public.clinical_link_revision(uuid, uuid) TO authenticated;
2691
+ `;
2692
+ var MIGRATION_016_A_COMPRA_ANTECIPADA_NAO_TEM_AGENDAMENTO_ATRAS = `-- ============================================================================
2693
+ -- A COMPRA ANTECIPADA n\xE3o tem agendamento atr\xE1s
2694
+ --
2695
+ -- O caso que a demonstra\xE7\xE3o do V1 narra: *"T\xE1 na promo\xE7\xE3o, vou comprar esse
2696
+ -- Botox e deixar guardado."* A recep\xE7\xE3o abre **Contas a Receber \u2192 Inserir**,
2697
+ -- escolhe o servi\xE7o, aplica o desconto combinado e recebe \u2014 **sem agendamento,
2698
+ -- sem contrato e sem proposta**. O V1 \xE9 expl\xEDcito: *"N\xE3o precisa de contrato?
2699
+ -- N\xE3o. N\xE3o precisa de proposta? N\xE3o."*
2700
+ --
2701
+ -- O efeito aparece na CONTA DA CLIENTE: um item **a executar**, pago, esperando
2702
+ -- o dia. \xC9 por isso que ele \xE9 passivo \u2014 a casa recebeu e ainda deve prestar \u2014,
2703
+ -- e \xE9 por isso que ele precisa nascer como SESS\xC3O: sem sess\xE3o, "a executar" n\xE3o
2704
+ -- existe como estado, e o dinheiro entraria como receita de um servi\xE7o que
2705
+ -- ningu\xE9m fez.
2706
+ --
2707
+ -- Sess\xE3o sem \`booking_id\` \xE9 o que distingue esta compra de um atendimento: ela
2708
+ -- ainda n\xE3o tem dia. Ganha um quando for agendada.
2709
+ -- ============================================================================
2710
+
2711
+ CREATE OR REPLACE FUNCTION public.clinical_prepay_services(p_party uuid, p_lines jsonb)
2712
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2713
+ AS $fn$
2714
+ DECLARE
2715
+ v_tenant uuid; v_unit uuid; v_order uuid; v_line jsonb;
2716
+ v_rpc_lines jsonb := '[]'::jsonb; v_idx int := 0; v_sessoes int := 0; v_total numeric;
2717
+ BEGIN
2718
+ IF auth.uid() IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_sessao'); END IF;
2719
+ v_tenant := app.current_tenant_id();
2720
+ IF v_tenant IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_tenant'); END IF;
2721
+ IF NOT EXISTS (SELECT 1 FROM public.people p WHERE p.id = p_party AND p.tenant_id = v_tenant) THEN
2722
+ RETURN jsonb_build_object('ok', false, 'reason', 'cliente_nao_encontrado');
2723
+ END IF;
2724
+ IF jsonb_typeof(p_lines) <> 'array' OR jsonb_array_length(p_lines) = 0 THEN
2725
+ RETURN jsonb_build_object('ok', false, 'reason', 'nada_escolhido');
2726
+ END IF;
2727
+
2728
+ v_unit := app.requested_unit();
2729
+
2730
+ FOR v_line IN SELECT * FROM jsonb_array_elements(p_lines)
2731
+ LOOP
2732
+ v_rpc_lines := v_rpc_lines || jsonb_build_object(
2733
+ 'product_id', v_line ->> 'service_id',
2734
+ 'name', v_line ->> 'name',
2735
+ 'quantity', greatest(coalesce((v_line ->> 'quantity')::numeric, 1), 1),
2736
+ 'unit_price', greatest(coalesce((v_line ->> 'unit_price')::numeric, 0), 0),
2737
+ 'sort_order', v_idx);
2738
+ v_idx := v_idx + 1;
2739
+ END LOOP;
2740
+
2741
+ v_order := public.order_create(
2742
+ p_kind => 'sale',
2743
+ p_lines => v_rpc_lines,
2744
+ p_party_id => p_party,
2745
+ p_unit_id => v_unit,
2746
+ -- Nasce CONFIRMADO e fecha logo abaixo, em dois tempos \u2014 e isso n\xE3o \xE9
2747
+ -- cerim\xF4nia: o gatilho que levanta o receb\xEDvel \xE9 \`AFTER UPDATE OF status\`,
2748
+ -- ent\xE3o um pedido criado j\xE1 \`completed\` **vende sem cobrar**. Medido: a
2749
+ -- primeira vers\xE3o desta fun\xE7\xE3o criou a compra fechada e a conta ficou com
2750
+ -- "a executar" e ZERO cobran\xE7a.
2751
+ -- (\`scheduled\` nem \xE9 aceito para \`sale\`: o contrato de estados do pedido
2752
+ -- permite draft, confirmed, completed e cancelled.)
2753
+ p_status => 'confirmed',
2754
+ p_metadata => jsonb_build_object('source', 'clinical:compra-antecipada'),
2755
+ p_idempotency_key => NULL);
2756
+
2757
+ -- Uma sess\xE3o por item, SEM dia. \xC9 ela que sustenta o "a executar" na conta \u2014
2758
+ -- e o que permite, quando o dia chegar, amarrar a execu\xE7\xE3o ao que j\xE1 foi pago.
2759
+ INSERT INTO public.plg_clinical_sessions
2760
+ (tenant_id, unit_id, status, party_id, service_id, order_item_id)
2761
+ SELECT v_tenant, v_unit, 'contracted', p_party, i.product_id, i.id
2762
+ FROM public.items i
2763
+ WHERE i.order_id = v_order AND i.product_id IS NOT NULL;
2764
+ GET DIAGNOSTICS v_sessoes = ROW_COUNT;
2765
+
2766
+ -- O fechamento, agora como UPDATE: \xE9 ele que dispara
2767
+ -- \`orders_raise_receivable_on_close\` e faz nascer a conta a receber.
2768
+ UPDATE public.orders SET status = 'completed', updated_at = now() WHERE id = v_order;
2769
+
2770
+ SELECT coalesce(sum(i.total), 0) INTO v_total FROM public.items i WHERE i.order_id = v_order;
2771
+
2772
+ RETURN jsonb_build_object('ok', true, 'order_id', v_order, 'sessoes', v_sessoes, 'total', v_total);
2773
+ END $fn$;
2774
+
2775
+ GRANT EXECUTE ON FUNCTION public.clinical_prepay_services(uuid, jsonb) TO authenticated;
2776
+ `;
2777
+ var MIGRATION_017_O_QUE_JA_FOI_PAGO_NAO_SE_COBRA_DE_NOVO = `-- ============================================================================
2778
+ -- O QUE J\xC1 FOI PAGO n\xE3o se cobra de novo
2779
+ --
2780
+ -- A compra antecipada deixa uma sess\xE3o **sem dia**: o Botox comprado na
2781
+ -- promo\xE7\xE3o, esperando. Quando o dia chega, o atendimento come\xE7ava criando uma
2782
+ -- sess\xE3o NOVA para o mesmo servi\xE7o \u2014 e a\xED a cliente tinha duas: a que pagou e a
2783
+ -- que acabou de ser aberta. A primeira ficava "a executar" para sempre, e a
2784
+ -- segunda entrava na contrata\xE7\xE3o como se nada tivesse sido pago.
2785
+ --
2786
+ -- \xC9 a mesma pessoa, o mesmo servi\xE7o e o mesmo dinheiro. Ent\xE3o o in\xEDcio do
2787
+ -- atendimento ADOTA a sess\xE3o que j\xE1 existe: ela ganha o dia, o profissional e o
2788
+ -- item do agendamento, e deixa de pender na conta.
2789
+ --
2790
+ -- A escolha \xE9 a mais ANTIGA: quem comprou duas vezes executa primeiro o que
2791
+ -- comprou primeiro \u2014 e \xE9 isso que faz o saldo andar em vez de envelhecer.
2792
+ -- ============================================================================
2793
+
2794
+ CREATE OR REPLACE FUNCTION public.clinical_attendance_start(p_booking uuid)
2795
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2796
+ AS $fn$
2797
+ DECLARE
2798
+ a record; v_person uuid; v_created int := 0; v_adotadas int := 0;
2799
+ v_item record; v_refresh jsonb; v_antiga uuid;
2800
+ BEGIN
2801
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.party_id, ap.assignee_id, ap.status, ap.starts_at
2802
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
2803
+ IF NOT FOUND THEN
2804
+ RETURN jsonb_build_object('ok', false, 'reason', 'not_found');
2805
+ END IF;
2806
+
2807
+ v_person := public.current_person_id();
2808
+ IF v_person IS NULL THEN
2809
+ RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional');
2810
+ END IF;
2811
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
2812
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
2813
+ END IF;
2814
+ IF a.starts_at::date <> (now() AT TIME ZONE 'America/Sao_Paulo')::date THEN
2815
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_de_hoje');
2816
+ END IF;
2817
+ IF a.status IN ('completed', 'cancelled', 'no_show') THEN
2818
+ RETURN jsonb_build_object('ok', false, 'reason', 'ja_encerrado', 'status', a.status);
2819
+ END IF;
2820
+
2821
+ FOR v_item IN
2822
+ SELECT ai.id, ai.service_id, ai.assignee_id
2823
+ FROM public.appointment_items ai
2824
+ WHERE ai.booking_id = p_booking
2825
+ LOOP
2826
+ -- J\xE1 existe sess\xE3o para este item? (dois toques, duas pessoas ao mesmo tempo)
2827
+ CONTINUE WHEN EXISTS (
2828
+ SELECT 1 FROM public.plg_clinical_sessions cs
2829
+ WHERE cs.booking_id = p_booking AND cs.booking_item_id = v_item.id);
2830
+
2831
+ -- O QUE FOI COMPRADO ANTES E AINDA N\xC3O SAIU: adota em vez de criar.
2832
+ SELECT cs.id INTO v_antiga
2833
+ FROM public.plg_clinical_sessions cs
2834
+ WHERE cs.tenant_id = a.tenant_id
2835
+ AND cs.party_id = a.party_id
2836
+ AND cs.service_id = v_item.service_id
2837
+ AND cs.booking_id IS NULL
2838
+ AND cs.status IN ('contracted', 'quoted', 'pending')
2839
+ ORDER BY cs.created_at
2840
+ LIMIT 1;
2841
+
2842
+ IF v_antiga IS NOT NULL THEN
2843
+ UPDATE public.plg_clinical_sessions
2844
+ SET booking_id = p_booking,
2845
+ booking_item_id = v_item.id,
2846
+ unit_id = coalesce(a.unit_id, unit_id),
2847
+ assignee_id = coalesce(v_item.assignee_id, a.assignee_id),
2848
+ performed_by_id = v_person,
2849
+ status = 'in_service',
2850
+ scheduled_for = a.starts_at,
2851
+ started_at = coalesce(started_at, now()),
2852
+ updated_at = now()
2853
+ WHERE id = v_antiga;
2854
+ v_adotadas := v_adotadas + 1;
2855
+ ELSE
2856
+ INSERT INTO public.plg_clinical_sessions (
2857
+ tenant_id, unit_id, status, booking_id, booking_item_id, party_id,
2858
+ assignee_id, performed_by_id, service_id, scheduled_for, started_at)
2859
+ VALUES (a.tenant_id, a.unit_id, 'in_service', a.id, v_item.id, a.party_id,
2860
+ coalesce(v_item.assignee_id, a.assignee_id), v_person, v_item.service_id,
2861
+ a.starts_at, now());
2862
+ v_created := v_created + 1;
2863
+ END IF;
2864
+ END LOOP;
2865
+
2866
+ UPDATE public.appointments
2867
+ SET status = 'in_progress', updated_at = now()
2868
+ WHERE id = p_booking AND status <> 'in_progress';
2869
+
2870
+ v_refresh := public.clinical_requirements_refresh(p_booking);
2871
+
2872
+ RETURN jsonb_build_object(
2873
+ 'ok', true,
2874
+ 'sessoes_criadas', v_created,
2875
+ 'sessoes_adotadas', v_adotadas,
2876
+ 'sessoes', (SELECT count(*) FROM public.plg_clinical_sessions WHERE booking_id = p_booking),
2877
+ 'regua', v_refresh);
2878
+ END $fn$;
2879
+
2880
+ GRANT EXECUTE ON FUNCTION public.clinical_attendance_start(uuid) TO authenticated;
2881
+ `;
2882
+ var MIGRATION_018_O_QUE_FOI_CONTRATADO_VIRA_SESSAO = `-- O que foi contratado vira SESS\xC3O, mesmo sem agendamento atr\xE1s dele.
2883
+ --
2884
+ -- A 006 s\xF3 LIGAVA sess\xF5es j\xE1 existentes \xE0s linhas do pedido. Servi\xE7o indicado
2885
+ -- na avalia\xE7\xE3o e contratado na hora n\xE3o tem sess\xE3o nenhuma para ligar: a conta
2886
+ -- ficava com "Botox Full Face \xB7 2 \xB7 R$ 2.798,00" e o prontu\xE1rio n\xE3o sabia que
2887
+ -- havia dois Botox a executar. O dinheiro entrava e a execu\xE7\xE3o sumia \u2014 nem na
2888
+ -- r\xE9gua, nem em \`v_clinical_to_execute\`, nem no di\xE1logo de "Executar".
2889
+ --
2890
+ -- Uma sess\xE3o POR UNIDADE, porque \xE9 assim que a execu\xE7\xE3o acontece: dois Botox
2891
+ -- contratados s\xE3o duas idas \xE0 cadeira, e executar um hoje n\xE3o pode fechar o
2892
+ -- outro. O \`booking_id\` \xE9 o do atendimento onde foi contratado \u2014 quem n\xE3o for
2893
+ -- executado hoje continua \`contracted\`, que \xE9 o estado de "a executar".
2894
+
2895
+ CREATE OR REPLACE FUNCTION public.clinical_sessions_for_order(p_booking uuid, p_order uuid)
2896
+ RETURNS integer
2897
+ LANGUAGE plpgsql
2898
+ SECURITY DEFINER
2899
+ SET search_path TO ''
2900
+ AS $fn$
2901
+ DECLARE
2902
+ a public.appointments%ROWTYPE;
2903
+ v_item record;
2904
+ v_faltam integer;
2905
+ v_k integer;
2906
+ v_total integer := 0;
2907
+ BEGIN
2908
+ SELECT * INTO a FROM public.appointments WHERE id = p_booking;
2909
+ IF NOT FOUND THEN RETURN 0; END IF;
2910
+
2911
+ FOR v_item IN
2912
+ SELECT i.id, i.product_id, i.quantity,
2913
+ (SELECT count(*) FROM public.plg_clinical_sessions s WHERE s.order_item_id = i.id) AS ja
2914
+ FROM public.items i
2915
+ WHERE i.order_id = p_order
2916
+ AND i.product_id IS NOT NULL
2917
+ LOOP
2918
+ -- Servi\xE7o, n\xE3o produto: o que se executa numa cadeira.
2919
+ CONTINUE WHEN NOT EXISTS (
2920
+ SELECT 1 FROM public.products p
2921
+ WHERE p.id = v_item.product_id AND p.kind = 'service');
2922
+
2923
+ v_faltam := greatest(0, ceil(coalesce(v_item.quantity, 1))::integer - v_item.ja::integer);
2924
+ FOR v_k IN 1 .. v_faltam LOOP
2925
+ INSERT INTO public.plg_clinical_sessions
2926
+ (tenant_id, unit_id, status, booking_id, party_id, assignee_id, service_id, order_item_id, metadata)
2927
+ VALUES
2928
+ (a.tenant_id, a.unit_id, 'contracted', p_booking, a.party_id, a.assignee_id,
2929
+ v_item.product_id, v_item.id,
2930
+ jsonb_build_object('source', 'clinical_contract_services'));
2931
+ v_total := v_total + 1;
2932
+ END LOOP;
2933
+ END LOOP;
2934
+
2935
+ RETURN v_total;
2936
+ END $fn$;
2937
+
2938
+ GRANT EXECUTE ON FUNCTION public.clinical_sessions_for_order(uuid, uuid) TO authenticated;
2939
+
2940
+
2941
+ CREATE OR REPLACE FUNCTION public.clinical_contract_services(p_booking uuid, p_lines jsonb)
2942
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
2943
+ AS $fn$
2944
+ DECLARE
2945
+ a record; v_person uuid; v_order uuid; v_line jsonb; v_item uuid; v_n int := 0;
2946
+ v_rpc_lines jsonb := '[]'::jsonb; v_idx int := 0;
2947
+ BEGIN
2948
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.party_id, ap.assignee_id, ap.status, ap.order_id
2949
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
2950
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
2951
+
2952
+ v_person := public.current_person_id();
2953
+ IF v_person IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional'); END IF;
2954
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
2955
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
2956
+ END IF;
2957
+ IF a.status <> 'in_progress' THEN
2958
+ RETURN jsonb_build_object('ok', false, 'reason', 'atendimento_nao_esta_em_curso');
2959
+ END IF;
2960
+ IF jsonb_typeof(p_lines) <> 'array' OR jsonb_array_length(p_lines) = 0 THEN
2961
+ RETURN jsonb_build_object('ok', false, 'reason', 'nada_marcado');
2962
+ END IF;
2963
+
2964
+ -- As linhas, no formato que \`order_create\` j\xE1 entende.
2965
+ FOR v_line IN SELECT * FROM jsonb_array_elements(p_lines)
2966
+ LOOP
2967
+ v_rpc_lines := v_rpc_lines || jsonb_build_object(
2968
+ 'product_id', v_line ->> 'service_id',
2969
+ 'name', v_line ->> 'name',
2970
+ 'quantity', coalesce((v_line ->> 'quantity')::numeric, 1),
2971
+ 'unit_price', coalesce((v_line ->> 'unit_price')::numeric, 0),
2972
+ 'sort_order', v_idx);
2973
+ v_idx := v_idx + 1;
2974
+ END LOOP;
2975
+
2976
+ -- O pedido do atendimento. \`idempotency_key\` pelo agendamento: dois toques
2977
+ -- no "Contratar" n\xE3o abrem duas contas para a mesma visita.
2978
+ IF a.order_id IS NULL THEN
2979
+ v_order := public.order_create(
2980
+ p_kind => 'appointment',
2981
+ p_lines => v_rpc_lines,
2982
+ p_party_id => a.party_id,
2983
+ p_unit_id => a.unit_id,
2984
+ p_status => 'scheduled',
2985
+ p_assignee_id => a.assignee_id,
2986
+ p_metadata => jsonb_build_object('agenda', jsonb_build_object('booking_id', p_booking), 'source', 'clinical:contratacao'),
2987
+ p_idempotency_key => 'clinical-contract:' || p_booking::text);
2988
+ UPDATE public.appointments SET order_id = v_order, updated_at = now() WHERE id = p_booking;
2989
+ ELSE
2990
+ -- Pedido j\xE1 existe (a agenda abriu na marca\xE7\xE3o): acrescenta o que falta.
2991
+ v_order := a.order_id;
2992
+ v_idx := coalesce((SELECT max(i.sort_order) + 1 FROM public.items i WHERE i.order_id = v_order), 0);
2993
+ FOR v_line IN SELECT * FROM jsonb_array_elements(p_lines)
2994
+ LOOP
2995
+ INSERT INTO public.items (tenant_id, unit_id, order_id, product_id, name, quantity, unit_price, total, sort_order)
2996
+ VALUES (a.tenant_id, a.unit_id, v_order, (v_line ->> 'service_id')::uuid, v_line ->> 'name',
2997
+ coalesce((v_line ->> 'quantity')::numeric, 1),
2998
+ coalesce((v_line ->> 'unit_price')::numeric, 0),
2999
+ coalesce((v_line ->> 'quantity')::numeric, 1) * coalesce((v_line ->> 'unit_price')::numeric, 0),
3000
+ v_idx);
3001
+ v_idx := v_idx + 1;
3002
+ END LOOP;
3003
+ END IF;
3004
+
3005
+ -- Cada sess\xE3o passa a apontar a SUA linha. Sem isto o pedido cobra e o
3006
+ -- atendimento n\xE3o sabe o que executou \u2014 e a bola "Conta do atendimento"
3007
+ -- nunca fecha, porque \xE9 exatamente este v\xEDnculo que ela procura.
3008
+ UPDATE public.plg_clinical_sessions cs
3009
+ SET order_item_id = i.id,
3010
+ status = CASE WHEN cs.status IN ('quoted', 'pending', 'scheduled') THEN 'contracted' ELSE cs.status END,
3011
+ updated_at = now()
3012
+ FROM public.items i
3013
+ WHERE cs.booking_id = p_booking
3014
+ AND cs.order_item_id IS NULL
3015
+ AND i.order_id = v_order
3016
+ AND i.product_id = cs.service_id
3017
+ AND NOT EXISTS (SELECT 1 FROM public.plg_clinical_sessions o
3018
+ WHERE o.order_item_id = i.id AND o.id <> cs.id);
3019
+ GET DIAGNOSTICS v_n = ROW_COUNT;
3020
+
3021
+ -- O que foi contratado e n\xE3o tinha sess\xE3o ganha a sua (018).
3022
+ PERFORM public.clinical_sessions_for_order(p_booking, v_order);
3023
+
3024
+ RETURN jsonb_build_object(
3025
+ 'ok', true, 'order_id', v_order, 'sessoes_ligadas', v_n,
3026
+ 'total', (SELECT coalesce(sum(i.total), 0) FROM public.items i WHERE i.order_id = v_order),
3027
+ 'regua', public.clinical_requirements_refresh(p_booking));
3028
+ END $fn$;
3029
+
3030
+ GRANT EXECUTE ON FUNCTION public.clinical_contract_services(uuid, jsonb) TO authenticated;
3031
+ `;
3032
+ var MIGRATION_019_ADIAR_E_UMA_ESCOLHA = `-- Adiar \xE9 uma escolha, e encerrar n\xE3o pode desfaz\xEA-la.
3033
+ --
3034
+ -- O "Executar neste atendimento" existe para dizer o que sai HOJE; o resto
3035
+ -- fica contratado para outro dia. Mas o \`Finalizar\` marcava como executada
3036
+ -- TODA sess\xE3o do agendamento \u2014 inclusive a que acabara de ser adiada. O
3037
+ -- servi\xE7o sumia do "a executar" da conta e a cliente ficava com um
3038
+ -- procedimento pago que ningu\xE9m fez, e que o sistema jurava ter feito.
3039
+ --
3040
+ -- O aviso de encerramento tinha o mesmo v\xEDcio: cobrava por servi\xE7os que a
3041
+ -- pessoa tinha acabado de dizer que ficariam para depois.
3042
+ --
3043
+ -- Agora as duas coisas olham para \`in_service\` \u2014 o que entrou na sala. O que
3044
+ -- est\xE1 em \`contracted\` \xE9 trabalho futuro e atravessa o encerramento intacto.
3045
+
3046
+ CREATE OR REPLACE FUNCTION public.clinical_attendance_finish(p_booking uuid, p_force boolean DEFAULT false)
3047
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
3048
+ AS $fn$
3049
+ DECLARE
3050
+ a record; v_person uuid; v_bloqueia jsonb; v_nao_executados jsonb;
3051
+ v_avisados int := 0; v_total numeric := 0; v_cliente text;
3052
+ BEGIN
3053
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.party_id, ap.assignee_id, ap.status, ap.order_id
3054
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
3055
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
3056
+
3057
+ v_person := public.current_person_id();
3058
+ IF v_person IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional'); END IF;
3059
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
3060
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
3061
+ END IF;
3062
+ IF a.status <> 'in_progress' THEN
3063
+ RETURN jsonb_build_object('ok', false, 'reason', 'atendimento_nao_esta_em_curso');
3064
+ END IF;
3065
+
3066
+ -- A trava de verdade: exig\xEAncia que impede TERMINAR.
3067
+ SELECT coalesce(jsonb_agg(jsonb_build_object('kind', r.kind, 'service_id', r.service_id)), '[]'::jsonb)
3068
+ INTO v_bloqueia
3069
+ FROM public.plg_clinical_requirements r
3070
+ WHERE r.booking_id = p_booking AND r.blocks_finish AND r.status = 'pending';
3071
+ IF jsonb_array_length(v_bloqueia) > 0 THEN
3072
+ RETURN jsonb_build_object('ok', false, 'reason', 'exigencia_bloqueia', 'itens', v_bloqueia);
3073
+ END IF;
3074
+
3075
+ -- O aviso que n\xE3o trava: o que ENTROU NA SALA e n\xE3o foi confirmado.
3076
+ --
3077
+ -- "Fica para outra data" \xE9 uma escolha, n\xE3o um esquecimento: sess\xE3o em
3078
+ -- \`contracted\` \xE9 trabalho futuro, j\xE1 na conta, e n\xE3o tem por que ser
3079
+ -- cobrada no aviso nem executada \xE0 for\xE7a ao encerrar.
3080
+ SELECT coalesce(jsonb_agg(p.name ORDER BY p.name), '[]'::jsonb) INTO v_nao_executados
3081
+ FROM public.plg_clinical_sessions cs
3082
+ JOIN public.products p ON p.id = cs.service_id
3083
+ WHERE cs.booking_id = p_booking AND cs.status = 'in_service';
3084
+ IF jsonb_array_length(v_nao_executados) > 0 AND NOT coalesce(p_force, false) THEN
3085
+ RETURN jsonb_build_object('ok', false, 'reason', 'servicos_nao_executados', 'itens', v_nao_executados);
3086
+ END IF;
3087
+
3088
+ -- "Finalizar agora registra estes servi\xE7os como executados" \u2014 texto do V1,
3089
+ -- e vale para os que estavam EM EXECU\xC7\xC3O. O que foi adiado continua
3090
+ -- contratado: marc\xE1-lo executado sumiria com ele do "a executar" da conta
3091
+ -- sem que a cliente tivesse recebido nada.
3092
+ UPDATE public.plg_clinical_sessions
3093
+ SET status = 'executed', ended_at = coalesce(ended_at, now()), updated_at = now()
3094
+ WHERE booking_id = p_booking AND status = 'in_service';
3095
+
3096
+ UPDATE public.appointments
3097
+ SET status = 'completed', updated_at = now()
3098
+ WHERE id = p_booking;
3099
+
3100
+ -- Congela a trilha: depois de encerrado, a r\xE9gua n\xE3o se reapura.
3101
+ PERFORM public.clinical_requirements_refresh(p_booking, true);
3102
+
3103
+ SELECT coalesce(sum(i.total), 0) INTO v_total FROM public.items i WHERE i.order_id = a.order_id;
3104
+ SELECT pe.name INTO v_cliente FROM public.people pe WHERE pe.id = a.party_id;
3105
+
3106
+ -- O BALC\xC3O ACENDE.
3107
+ --
3108
+ -- Quem recebe: a recep\xE7\xE3o da conta. Onde n\xE3o houver ningu\xE9m com o papel de
3109
+ -- recep\xE7\xE3o \u2014 e \xE9 o caso do tenant migrado, com 0 membros nele \u2014, cai para
3110
+ -- gerente e dono. Um aviso que n\xE3o chega a ningu\xE9m deixaria a conta parada
3111
+ -- sem que nada na tela dissesse por qu\xEA.
3112
+ WITH alvo AS (
3113
+ SELECT m.user_id
3114
+ FROM app.memberships m
3115
+ JOIN app.roles r ON r.id = m.role_id
3116
+ WHERE m.tenant_id = a.tenant_id AND coalesce(m.active, true)
3117
+ AND r.key IN ('recepcao', 'reception')
3118
+ UNION ALL
3119
+ SELECT m.user_id
3120
+ FROM app.memberships m
3121
+ JOIN app.roles r ON r.id = m.role_id
3122
+ WHERE m.tenant_id = a.tenant_id AND coalesce(m.active, true)
3123
+ AND r.key IN ('owner', 'manager')
3124
+ AND NOT EXISTS (
3125
+ SELECT 1 FROM app.memberships m2 JOIN app.roles r2 ON r2.id = m2.role_id
3126
+ WHERE m2.tenant_id = a.tenant_id AND coalesce(m2.active, true)
3127
+ AND r2.key IN ('recepcao', 'reception'))
3128
+ )
3129
+ INSERT INTO public.notifications (tenant_id, user_id, title, body, type, link, subject_type, subject_id)
3130
+ SELECT a.tenant_id, alvo.user_id,
3131
+ 'Checkout pendente',
3132
+ coalesce(v_cliente, 'Cliente') || ' terminou o atendimento'
3133
+ -- O dinheiro escrito como o Brasil escreve. \`to_char\` usa o
3134
+ -- \`lc_numeric\` do BANCO para o grupo e a v\xEDrgula, e o cluster est\xE1
3135
+ -- em C: sa\xEDa "R$ 999.00" no aviso de uma recep\xE7\xE3o brasileira. A
3136
+ -- troca \xE9 feita \xE0 m\xE3o para n\xE3o depender de locale nenhum.
3137
+ || CASE WHEN v_total > 0 THEN ' \xB7 R$ ' ||
3138
+ replace(replace(replace(to_char(v_total, 'FM999G999G999D00'), ',', '\xA7'), '.', ','), '\xA7', '.')
3139
+ ELSE '' END,
3140
+ 'checkout_pendente', '#/checkin', 'appointment', p_booking
3141
+ FROM alvo
3142
+ ON CONFLICT (user_id, subject_type, subject_id, type) WHERE subject_id IS NOT NULL DO NOTHING;
3143
+ GET DIAGNOSTICS v_avisados = ROW_COUNT;
3144
+
3145
+ RETURN jsonb_build_object(
3146
+ 'ok', true, 'avisados', v_avisados, 'total', v_total,
3147
+ 'executados', (SELECT count(*) FROM public.plg_clinical_sessions WHERE booking_id = p_booking AND status = 'executed'));
3148
+ END $fn$;
3149
+
3150
+ GRANT EXECUTE ON FUNCTION public.clinical_attendance_finish(uuid, boolean) TO authenticated;
3151
+ `;
3152
+ var MIGRATION_020_COBRAR_UM_AGENDAMENTO_SEM_PEDIDO_LEVANTA_O_PEDIDO = `-- ============================================================================
3153
+ -- Cobrar um agendamento SEM pedido levanta o pedido primeiro
3154
+ --
3155
+ -- SINTOMA, visto na tela (23-09, Juliane): a aba Financeiro acende o vermelho
3156
+ -- do V1 ("atendimento de hoje sem cobran\xE7a levantada"), mas a conta n\xE3o
3157
+ -- oferece caminho nenhum \u2014 o agendamento veio da MIGRA\xC7\xC3O do V1 com
3158
+ -- \`order_id\` nulo, e a linha do servi\xE7o mora em \`appointment_items\`, n\xE3o em
3159
+ -- \`items\`. O V1 nunca teve esse beco: "Gerar Recebimento" l\xE1 CRIA a fatura a
3160
+ -- partir dos servi\xE7os do agendamento.
3161
+ --
3162
+ -- A tradu\xE7\xE3o para o V2 respeita o caminho \xFAnico do dinheiro: a cobran\xE7a n\xE3o
3163
+ -- escreve fatura \u2014 ela LEVANTA O PEDIDO pela porta do n\xFAcleo (\`order_create\`,
3164
+ -- a mesma que \`agenda_booking_create\` usa) com as linhas COM PRE\xC7O dos
3165
+ -- \`appointment_items\`, amarra o pedido ao agendamento e segue o fechamento
3166
+ -- normal (\`orders_raise_receivable_on_close\`).
3167
+ --
3168
+ -- Linha sem pre\xE7o n\xE3o vira pedido: revis\xE3o e avalia\xE7\xE3o gratuitas continuam
3169
+ -- sem cobran\xE7a, e a recusa \`nada_contratado\` continua falando por elas.
3170
+ -- ============================================================================
3171
+
3172
+ CREATE OR REPLACE FUNCTION public.clinical_checkout_charge(p_booking uuid)
3173
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
3174
+ AS $fn$
3175
+ DECLARE
3176
+ a record; v_linhas int; v_total numeric; v_mov int; v_lines jsonb; v_order uuid;
3177
+ BEGIN
3178
+ SELECT ap.id, ap.tenant_id, ap.kind, ap.status, ap.order_id,
3179
+ ap.party_id, ap.assignee_id, ap.unit_id
3180
+ INTO a
3181
+ FROM public.appointments ap WHERE ap.id = p_booking;
3182
+ IF NOT FOUND THEN RETURN jsonb_build_object('ok', false, 'reason', 'not_found'); END IF;
3183
+ IF auth.uid() IS NULL THEN RETURN jsonb_build_object('ok', false, 'reason', 'sem_sessao'); END IF;
3184
+ -- O agendamento de OUTRA conta n\xE3o existe para esta sess\xE3o.
3185
+ IF a.tenant_id IS DISTINCT FROM app.current_tenant_id() THEN
3186
+ RETURN jsonb_build_object('ok', false, 'reason', 'not_found');
3187
+ END IF;
3188
+
3189
+ IF a.order_id IS NULL THEN
3190
+ -- As linhas com pre\xE7o do agendamento migrado. Sem nenhuma, n\xE3o h\xE1 o que
3191
+ -- cobrar \u2014 e isso \xE9 um estado leg\xEDtimo (revis\xE3o, avalia\xE7\xE3o gratuita).
3192
+ SELECT jsonb_agg(jsonb_build_object(
3193
+ 'service_id', ai.service_id,
3194
+ 'name', ai.name,
3195
+ 'quantity', 1,
3196
+ 'unit_price', ai.price,
3197
+ 'sort_order', ai.sort_order,
3198
+ 'duration_minutes', ai.duration_minutes,
3199
+ 'assignee_id', coalesce(ai.assignee_id, a.assignee_id)
3200
+ ) ORDER BY ai.sort_order)
3201
+ INTO v_lines
3202
+ FROM public.appointment_items ai
3203
+ WHERE ai.booking_id = a.id AND coalesce(ai.price, 0) > 0;
3204
+
3205
+ IF v_lines IS NULL THEN
3206
+ RETURN jsonb_build_object('ok', false, 'reason', 'nada_contratado');
3207
+ END IF;
3208
+
3209
+ v_order := public.order_create(
3210
+ p_kind => coalesce(a.kind, 'appointment'),
3211
+ p_lines => v_lines,
3212
+ p_party_id => a.party_id,
3213
+ p_unit_id => a.unit_id,
3214
+ p_status => 'scheduled',
3215
+ p_assignee_id => a.assignee_id,
3216
+ p_metadata => jsonb_build_object('source', 'clinical_checkout_charge', 'booking_id', a.id));
3217
+
3218
+ UPDATE public.appointments SET order_id = v_order, updated_at = now() WHERE id = a.id;
3219
+ a.order_id := v_order;
3220
+ END IF;
3221
+
3222
+ SELECT count(*), coalesce(sum(i.total), 0) INTO v_linhas, v_total
3223
+ FROM public.items i WHERE i.order_id = a.order_id;
3224
+ IF v_linhas = 0 THEN
3225
+ RETURN jsonb_build_object('ok', false, 'reason', 'nada_contratado');
3226
+ END IF;
3227
+
3228
+ -- Idempotente: o pedido j\xE1 fechado devolve o que existe, sem levantar um
3229
+ -- segundo receb\xEDvel para a mesma visita.
3230
+ SELECT count(*) INTO v_mov FROM public.plg_financial_movements m WHERE m.invoice_id = a.order_id;
3231
+ IF v_mov > 0 THEN
3232
+ RETURN jsonb_build_object('ok', true, 'ja_cobrado', true, 'total', v_total);
3233
+ END IF;
3234
+
3235
+ UPDATE public.orders SET status = 'completed', updated_at = now()
3236
+ WHERE id = a.order_id AND status <> 'completed';
3237
+
3238
+ SELECT count(*) INTO v_mov FROM public.plg_financial_movements m WHERE m.invoice_id = a.order_id;
3239
+ RETURN jsonb_build_object('ok', true, 'total', v_total, 'movimentos', v_mov);
3240
+ END $fn$;
3241
+
3242
+ GRANT EXECUTE ON FUNCTION public.clinical_checkout_charge(uuid) TO authenticated;
3243
+ `;
3244
+ var MIGRATION_021_AGENDAMENTO_NASCIDO_NO_V2_TAMBEM_TEM_REGUA = `-- ============================================================================
3245
+ -- O AGENDAMENTO NASCIDO NO V2 TAMB\xC9M TEM R\xC9GUA
3246
+ --
3247
+ -- O Iniciar atendimento percorre \`appointment_items\` \u2014 a linha do agendamento
3248
+ -- do V1, onde as 314 mil linhas migradas moram. S\xF3 que o Novo Agendamento do
3249
+ -- V2 grava as linhas pelo caminho do PEDIDO (\`agenda_booking_create\` \u2192
3250
+ -- \`orders\` + \`items\`), e nunca escreve \`appointment_items\`. Resultado, visto
3251
+ -- na tela em 23/09: o bot\xE3o vira "Em atendimento", e a r\xE9gua nasce VAZIA \u2014
3252
+ -- zero sess\xF5es, zero exig\xEAncias, bolas nenhuma. Todo agendamento criado pela
3253
+ -- pr\xF3pria UI do V2 ca\xEDa nisso; s\xF3 os migrados do V1 funcionavam.
3254
+ --
3255
+ -- O conserto MATERIALIZA a linha do agendamento na hora de come\xE7ar: se o
3256
+ -- agendamento tem pedido e ainda n\xE3o tem \`appointment_items\`, elas nascem das
3257
+ -- linhas do pedido \u2014 e o resto do fluxo (sess\xF5es, FK de \`booking_item_id\`,
3258
+ -- r\xE9gua, produtos por servi\xE7o) continua lendo o modelo que sempre leu.
3259
+ -- Idempotente: s\xF3 insere quando n\xE3o h\xE1 linha nenhuma para o agendamento.
3260
+ -- ============================================================================
3261
+
3262
+ CREATE OR REPLACE FUNCTION public.clinical_attendance_start(p_booking uuid)
3263
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public', 'app'
3264
+ AS $fn$
3265
+ DECLARE
3266
+ a record; v_person uuid; v_created int := 0; v_adotadas int := 0;
3267
+ v_item record; v_refresh jsonb; v_antiga uuid;
3268
+ BEGIN
3269
+ SELECT ap.id, ap.tenant_id, ap.unit_id, ap.party_id, ap.assignee_id, ap.status,
3270
+ ap.starts_at, ap.order_id
3271
+ INTO a FROM public.appointments ap WHERE ap.id = p_booking;
3272
+ IF NOT FOUND THEN
3273
+ RETURN jsonb_build_object('ok', false, 'reason', 'not_found');
3274
+ END IF;
3275
+
3276
+ v_person := public.current_person_id();
3277
+ IF v_person IS NULL THEN
3278
+ RETURN jsonb_build_object('ok', false, 'reason', 'sem_ficha_de_profissional');
3279
+ END IF;
3280
+ IF a.assignee_id IS DISTINCT FROM v_person THEN
3281
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_seu_atendimento');
3282
+ END IF;
3283
+ IF a.starts_at::date <> (now() AT TIME ZONE 'America/Sao_Paulo')::date THEN
3284
+ RETURN jsonb_build_object('ok', false, 'reason', 'nao_e_de_hoje');
3285
+ END IF;
3286
+ IF a.status IN ('completed', 'cancelled', 'no_show') THEN
3287
+ RETURN jsonb_build_object('ok', false, 'reason', 'ja_encerrado', 'status', a.status);
3288
+ END IF;
3289
+
3290
+ -- Agendamento nascido no V2: as linhas vivem no pedido. Materializa a linha
3291
+ -- do agendamento \u2014 uma vez s\xF3 \u2014 para o resto do fluxo ter onde se pendurar.
3292
+ IF a.order_id IS NOT NULL
3293
+ AND NOT EXISTS (SELECT 1 FROM public.appointment_items ai WHERE ai.booking_id = a.id) THEN
3294
+ INSERT INTO public.appointment_items (
3295
+ tenant_id, unit_id, booking_id, service_id, name, price,
3296
+ duration_minutes, assignee_id, sort_order)
3297
+ -- \`coalesce(product_id, service_id)\`: o \`order_create\` grava o servi\xE7o em
3298
+ -- \`service_id\`; a edi\xE7\xE3o pela agenda grava em \`product_id\` (spine 190).
3299
+ -- As duas gera\xE7\xF5es de linha existem no banco.
3300
+ SELECT a.tenant_id, a.unit_id, a.id, coalesce(it.product_id, it.service_id),
3301
+ it.name, it.unit_price,
3302
+ it.duration_minutes, coalesce(it.assignee_id, a.assignee_id),
3303
+ coalesce(it.sort_order, 0)
3304
+ FROM public.items it
3305
+ WHERE it.order_id = a.order_id;
3306
+ END IF;
3307
+
3308
+ FOR v_item IN
3309
+ SELECT ai.id, ai.service_id, ai.assignee_id
3310
+ FROM public.appointment_items ai
3311
+ WHERE ai.booking_id = p_booking
3312
+ LOOP
3313
+ -- J\xE1 existe sess\xE3o para este item? (dois toques, duas pessoas ao mesmo tempo)
3314
+ CONTINUE WHEN EXISTS (
3315
+ SELECT 1 FROM public.plg_clinical_sessions cs
3316
+ WHERE cs.booking_id = p_booking AND cs.booking_item_id = v_item.id);
3317
+
3318
+ -- O QUE FOI COMPRADO ANTES E AINDA N\xC3O SAIU: adota em vez de criar.
3319
+ SELECT cs.id INTO v_antiga
3320
+ FROM public.plg_clinical_sessions cs
3321
+ WHERE cs.tenant_id = a.tenant_id
3322
+ AND cs.party_id = a.party_id
3323
+ AND cs.service_id = v_item.service_id
3324
+ AND cs.booking_id IS NULL
3325
+ AND cs.status IN ('contracted', 'quoted', 'pending')
3326
+ ORDER BY cs.created_at
3327
+ LIMIT 1;
3328
+
3329
+ IF v_antiga IS NOT NULL THEN
3330
+ UPDATE public.plg_clinical_sessions
3331
+ SET booking_id = p_booking,
3332
+ booking_item_id = v_item.id,
3333
+ unit_id = coalesce(a.unit_id, unit_id),
3334
+ assignee_id = coalesce(v_item.assignee_id, a.assignee_id),
3335
+ performed_by_id = v_person,
3336
+ status = 'in_service',
3337
+ scheduled_for = a.starts_at,
3338
+ started_at = coalesce(started_at, now()),
3339
+ updated_at = now()
3340
+ WHERE id = v_antiga;
3341
+ v_adotadas := v_adotadas + 1;
3342
+ ELSE
3343
+ INSERT INTO public.plg_clinical_sessions (
3344
+ tenant_id, unit_id, status, booking_id, booking_item_id, party_id,
3345
+ assignee_id, performed_by_id, service_id, scheduled_for, started_at)
3346
+ VALUES (a.tenant_id, a.unit_id, 'in_service', a.id, v_item.id, a.party_id,
3347
+ coalesce(v_item.assignee_id, a.assignee_id), v_person, v_item.service_id,
3348
+ a.starts_at, now());
3349
+ v_created := v_created + 1;
3350
+ END IF;
3351
+ END LOOP;
3352
+
3353
+ UPDATE public.appointments
3354
+ SET status = 'in_progress', updated_at = now()
3355
+ WHERE id = p_booking AND status <> 'in_progress';
3356
+
3357
+ v_refresh := public.clinical_requirements_refresh(p_booking);
3358
+
3359
+ RETURN jsonb_build_object(
3360
+ 'ok', true,
3361
+ 'sessoes_criadas', v_created,
3362
+ 'sessoes_adotadas', v_adotadas,
3363
+ 'sessoes', (SELECT count(*) FROM public.plg_clinical_sessions WHERE booking_id = p_booking),
3364
+ 'regua', v_refresh);
3365
+ END $fn$;
3366
+
3367
+ GRANT EXECUTE ON FUNCTION public.clinical_attendance_start(uuid) TO authenticated;
3368
+ `;
3369
+ var MIGRATION_022_A_VISTA_DO_QUE_EXECUTAR_RESPEITA_A_CERCA = `-- ============================================================================
3370
+ -- THE "TO EXECUTE" VIEW READS WITH THE CALLER'S PRIVILEGES
3371
+ --
3372
+ -- \`v_clinical_to_execute\` was created in 014 without \`security_invoker\`, so it
3373
+ -- ran with the privileges of the role that OWNS it, and a view owned by a
3374
+ -- privileged role does not apply the row policies of the tables beneath it.
3375
+ -- \`plg_clinical_sessions\`, \`items\` and \`plg_financial_movements\` are all
3376
+ -- tenant-scoped with RLS; read through this view, they were not.
3377
+ --
3378
+ -- Not theoretical: the view answers, per party, how much a patient has already
3379
+ -- PAID for procedures not yet performed. Without the fence that is every
3380
+ -- clinic's prepaid balance, to anyone holding any session.
3381
+ --
3382
+ -- \u2500\u2500 why nobody saw it \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
3383
+ --
3384
+ -- N16 of the posture suite grades exactly this ("every public view over a
3385
+ -- tenant_id table is security_invoker"), and it stayed green throughout:
3386
+ -- plugin-clinical was never listed in \`packages/db/chain.json\`, so its objects
3387
+ -- were never built on the bench and never graded. The plugin reached a live
3388
+ -- pool on 2026-09-22 and no board at all. Putting it in the chain is what made
3389
+ -- the suite fail, on the first run, in the expected place.
3390
+ --
3391
+ -- \u2500\u2500 why a new file, and not an edit to 014 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
3392
+ --
3393
+ -- 014 is in \`public._migrations\` on a live pool with checksum 6f04df24cdb2,
3394
+ -- and the ledger treats a changed checksum on an applied file as a HARD STOP
3395
+ -- (cli/src/lib/ledger.ts). Editing it in place would not fix the view \u2014 it
3396
+ -- would stop \`fayz db apply\` on every cluster that already ran it.
3397
+ --
3398
+ -- The body below is 014's, copied unchanged. \`CREATE OR REPLACE VIEW\` refuses
3399
+ -- a different column list, and the only thing that may differ here is who the
3400
+ -- row filter runs as.
3401
+ -- ============================================================================
3402
+
3403
+ CREATE OR REPLACE VIEW public.v_clinical_to_execute WITH (security_invoker = true) AS
3404
+ WITH sessao AS (
3405
+ SELECT
3406
+ cs.tenant_id,
3407
+ cs.party_id,
3408
+ cs.order_item_id,
3409
+ cs.status,
3410
+ i.order_id,
3411
+ coalesce(i.total, 0) AS item_total
3412
+ FROM public.plg_clinical_sessions cs
3413
+ JOIN public.items i ON i.id = cs.order_item_id
3414
+ WHERE cs.party_id IS NOT NULL
3415
+ AND cs.status IN ('contracted', 'quoted', 'in_service', 'scheduled', 'pending')
3416
+ ),
3417
+ -- Quanto do PEDIDO j\xE1 foi recebido, em propor\xE7\xE3o: o pagamento \xE9 por parcela e
3418
+ -- n\xE3o por item, ent\xE3o a fatia paga de cada item \xE9 a fatia paga do pedido.
3419
+ pago AS (
3420
+ SELECT m.invoice_id AS order_id,
3421
+ sum(coalesce(m.paid_amount, 0)) AS pago,
3422
+ nullif(sum(coalesce(m.amount, 0)), 0) AS total
3423
+ FROM public.plg_financial_movements m
3424
+ WHERE m.direction = 'credit'
3425
+ GROUP BY m.invoice_id
3426
+ )
3427
+ SELECT
3428
+ s.tenant_id,
3429
+ s.party_id,
3430
+ sum(s.item_total * coalesce(p.pago / p.total, 0))::numeric(14,2) AS paid_to_execute,
3431
+ sum(s.item_total * (1 - coalesce(p.pago / p.total, 0)))::numeric(14,2) AS open_to_execute,
3432
+ count(*)::int AS sessions_to_execute
3433
+ FROM sessao s
3434
+ LEFT JOIN pago p ON p.order_id = s.order_id
3435
+ GROUP BY s.tenant_id, s.party_id;
3436
+ `;
3437
+ var MIGRATIONS = [
3438
+ { id: "001_o_atendimento_clinico_tem_onde_morar", sql: MIGRATION_001_O_ATENDIMENTO_CLINICO_TEM_ONDE_MORAR },
3439
+ { id: "002_o_prontuario_do_v1_atravessa", sql: MIGRATION_002_O_PRONTUARIO_DO_V1_ATRAVESSA },
3440
+ { id: "003_a_permissao_se_pergunta_por_unidade_nao_por_linha", sql: MIGRATION_003_A_PERMISSAO_SE_PERGUNTA_POR_UNIDADE_NAO_POR_LINHA },
3441
+ { id: "004_a_regua_volta_a_ser_apurada", sql: MIGRATION_004_A_REGUA_VOLTA_A_SER_APURADA },
3442
+ { id: "005_comecar_o_atendimento_e_um_gesto_so", sql: MIGRATION_005_COMECAR_O_ATENDIMENTO_E_UM_GESTO_SO },
3443
+ { id: "006_contratar_nao_e_pagar", sql: MIGRATION_006_CONTRATAR_NAO_E_PAGAR },
3444
+ { id: "007_finalizar_acende_o_balcao", sql: MIGRATION_007_FINALIZAR_ACENDE_O_BALCAO },
3445
+ { id: "008_conferir_nao_e_receber", sql: MIGRATION_008_CONFERIR_NAO_E_RECEBER },
3446
+ { id: "009_o_botao_de_cobrar_cobra", sql: MIGRATION_009_O_BOTAO_DE_COBRAR_COBRA },
3447
+ { id: "010_a_indicacao_vai_para_o_funil", sql: MIGRATION_010_A_INDICACAO_VAI_PARA_O_FUNIL },
3448
+ { id: "011_interesse_e_indicacao_na_mesma_linha", sql: MIGRATION_011_INTERESSE_E_INDICACAO_NA_MESMA_LINHA },
3449
+ { id: "012_o_que_foi_usado_espera_aprovacao", sql: MIGRATION_012_O_QUE_FOI_USADO_ESPERA_APROVACAO },
3450
+ { id: "013_o_que_couber_hoje", sql: MIGRATION_013_O_QUE_COUBER_HOJE },
3451
+ { id: "014_o_pago_a_executar_deixa_de_ser_invisivel", sql: MIGRATION_014_O_PAGO_A_EXECUTAR_DEIXA_DE_SER_INVISIVEL },
3452
+ { id: "015_a_revisao_aponta_o_que_revisa", sql: MIGRATION_015_A_REVISAO_APONTA_O_QUE_REVISA },
3453
+ { id: "016_a_compra_antecipada_nao_tem_agendamento_atras", sql: MIGRATION_016_A_COMPRA_ANTECIPADA_NAO_TEM_AGENDAMENTO_ATRAS },
3454
+ { id: "017_o_que_ja_foi_pago_nao_se_cobra_de_novo", sql: MIGRATION_017_O_QUE_JA_FOI_PAGO_NAO_SE_COBRA_DE_NOVO },
3455
+ { id: "018_o_que_foi_contratado_vira_sessao", sql: MIGRATION_018_O_QUE_FOI_CONTRATADO_VIRA_SESSAO },
3456
+ { id: "019_adiar_e_uma_escolha", sql: MIGRATION_019_ADIAR_E_UMA_ESCOLHA },
3457
+ { id: "020_cobrar_um_agendamento_sem_pedido_levanta_o_pedido", sql: MIGRATION_020_COBRAR_UM_AGENDAMENTO_SEM_PEDIDO_LEVANTA_O_PEDIDO },
3458
+ { id: "021_agendamento_nascido_no_v2_tambem_tem_regua", sql: MIGRATION_021_AGENDAMENTO_NASCIDO_NO_V2_TAMBEM_TEM_REGUA },
3459
+ { id: "022_a_vista_do_que_executar_respeita_a_cerca", sql: MIGRATION_022_A_VISTA_DO_QUE_EXECUTAR_RESPEITA_A_CERCA }
3460
+ ];
3461
+
3462
+ // src/index.ts
3463
+ function createClinicalPlugin(_options = {}) {
3464
+ return definePlugin({
3465
+ id: "clinical",
3466
+ name: "Prontu\xE1rio",
3467
+ icon: "Stethoscope",
3468
+ version: "0.1.0",
3469
+ apiVersion: 1,
3470
+ scope: "addon",
3471
+ defaultEnabled: false,
3472
+ dependencies: ["agenda"],
3473
+ navigation: [],
3474
+ routes: [],
3475
+ migrations: MIGRATIONS.map((entry) => ({
3476
+ id: `clinical-${entry.id}`,
3477
+ version: "1.0.0",
3478
+ sql: entry.sql,
3479
+ description: "A sess\xE3o cl\xEDnica, o consumo de produto, as exig\xEAncias de execu\xE7\xE3o e a revis\xE3o do servi\xE7o."
3480
+ }))
3481
+ });
3482
+ }
3483
+ var src_default = createClinicalPlugin;
3484
+
3485
+ export { createClinicalPlugin, src_default as default };
3486
+ //# sourceMappingURL=index.js.map
3487
+ //# sourceMappingURL=index.js.map