@fayz-ai/plugin-clinical 0.4.14 → 0.4.16

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