evo360-types 1.3.764 → 1.3.768

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,385 @@
1
+ // Tipos do evo-docs — feat-312 "Anexos unificados".
2
+ // Schemas zod correspondentes ficam em src/apps/evo-docs/zod-schemas.ts; estes tipos são
3
+ // escritos à mão e mantidos em paralelo (convenção do projeto: `apps/` = zod, `types/` =
4
+ // interfaces TS). Contrato: hub-medica-docs/features/feat-312-anexos-unificados/plan.md
5
+ // (§2.1 entidade, §2.3 evento de indexação, §2.4 mapa kind → base_category, §2.7 API).
6
+
7
+ import type {
8
+ ExternalObjectType,
9
+ IExternalLink,
10
+ IExternalLinkRelation,
11
+ IFireDoc,
12
+ ITag,
13
+ } from "../shared";
14
+ import { ExternalObjectTypeEnum } from "../shared";
15
+ import type { MessageDirection } from "../evo-chat/thread-message";
16
+ import type { PatientAttachmentBaseCategory } from "../evo-med/dic";
17
+ import { PatientAttachmentBaseCategoryEnum } from "../evo-med/dic";
18
+
19
+ export * from "./fb_collections";
20
+
21
+ // ───────── Enums ─────────
22
+
23
+ /** De onde o anexo veio. Fonte A = upload da ficha; B = chat; C = e-mail. */
24
+ export const AttachmentSourceKindEnum = {
25
+ PatientUpload: "patient_upload",
26
+ AppointmentUpload: "appointment_upload",
27
+ ChatMessage: "chat_message",
28
+ EmailMessage: "email_message",
29
+ /** Reservado, sem escritor na v1 (D5: entra num 2º momento). */
30
+ HistoryImport: "history_import",
31
+ /** Reservado, sem escritor na v1. */
32
+ PlatformGenerated: "platform_generated",
33
+ } as const;
34
+
35
+ export type AttachmentSourceKind =
36
+ (typeof AttachmentSourceKindEnum)[keyof typeof AttachmentSourceKindEnum];
37
+
38
+ /** Fontes que são troca de mensagem: nelas `source.direction` é obrigatório (Q9). */
39
+ export const ATTACHMENT_MESSAGE_SOURCE_KINDS = [
40
+ AttachmentSourceKindEnum.ChatMessage,
41
+ AttachmentSourceKindEnum.EmailMessage,
42
+ ] as const;
43
+
44
+ /** Recebido × enviado pela clínica (Q9). `null` em upload da ficha. */
45
+ export const AttachmentDirectionEnum = {
46
+ Inbound: "inbound",
47
+ Outbound: "outbound",
48
+ } as const;
49
+
50
+ export type AttachmentDirection =
51
+ (typeof AttachmentDirectionEnum)[keyof typeof AttachmentDirectionEnum];
52
+
53
+ /** Quem decidiu a categoria vigente. Humano nunca é sobrescrito pela IA. */
54
+ export const AttachmentClassificationSourceEnum = {
55
+ Human: "human",
56
+ Hubia: "hubia",
57
+ None: "none",
58
+ } as const;
59
+
60
+ export type AttachmentClassificationSource =
61
+ (typeof AttachmentClassificationSourceEnum)[keyof typeof AttachmentClassificationSourceEnum];
62
+
63
+ export const AttachmentMediaKindEnum = {
64
+ Image: "image",
65
+ Document: "document",
66
+ Audio: "audio",
67
+ Video: "video",
68
+ Other: "other",
69
+ } as const;
70
+
71
+ export type AttachmentMediaKind =
72
+ (typeof AttachmentMediaKindEnum)[keyof typeof AttachmentMediaKindEnum];
73
+
74
+ /** Tipos de sujeito aceitos em `externalLinks` do anexo (subconjunto de ExternalObjectTypeEnum). */
75
+ export const ATTACHMENT_SUBJECT_TYPES = [
76
+ ExternalObjectTypeEnum.MedPatient,
77
+ ExternalObjectTypeEnum.CrmLead,
78
+ ExternalObjectTypeEnum.MedAppointment,
79
+ ExternalObjectTypeEnum.ChatContact,
80
+ ] as const;
81
+
82
+ export type AttachmentSubjectType = (typeof ATTACHMENT_SUBJECT_TYPES)[number];
83
+
84
+ /** Raízes aceitas em `GET /attachments?subject=type:id` (§2.6). `chat_contact` não é raiz. */
85
+ export const ATTACHMENT_LIST_ROOT_TYPES = [
86
+ ExternalObjectTypeEnum.MedPatient,
87
+ ExternalObjectTypeEnum.CrmLead,
88
+ ExternalObjectTypeEnum.MedAppointment,
89
+ ] as const;
90
+
91
+ export type AttachmentListRootType = (typeof ATTACHMENT_LIST_ROOT_TYPES)[number];
92
+
93
+ export function isAttachmentSubjectType(type: unknown): type is AttachmentSubjectType {
94
+ return (
95
+ typeof type === "string" &&
96
+ (ATTACHMENT_SUBJECT_TYPES as readonly string[]).indexOf(type) >= 0
97
+ );
98
+ }
99
+
100
+ /** Chave de `externalLinkKeys`: `"type:id"`. */
101
+ export function attachmentSubjectKey(type: ExternalObjectType | string, id: string): string {
102
+ return `${type}:${id}`;
103
+ }
104
+
105
+ // ───────── Entidade ─────────
106
+
107
+ /** Snapshot de quem agiu (padrão de `IPatientAttachment.uploadedBy`), servido em JSON. */
108
+ export interface IAttachmentActor {
109
+ userId: string;
110
+ displayName: string;
111
+ }
112
+
113
+ export interface IAttachmentSource {
114
+ kind: AttachmentSourceKind;
115
+ /** Valores conhecidos: 'hub-waba' | 'hub-instagram' | 'amazon-ses' | 'smtp' | 'evo-med'. Não é enum fechado. */
116
+ provider?: string | null;
117
+ channel_id?: string | null;
118
+ /** 'whatsapp' | 'instagram' | 'email'. */
119
+ channel_type?: string | null;
120
+ department_id?: string | null;
121
+ /** A mensagem mora em threads/{thread_id}/messages/{message_id}. */
122
+ thread_id?: string | null;
123
+ message_id?: string | null;
124
+ ticket_id?: string | null;
125
+ /** Posição no `attachments[]` do e-mail; 0 para `media`. */
126
+ message_index?: number | null;
127
+ /** Obrigatório em chat/e-mail (Q9); null em upload da ficha. */
128
+ direction?: AttachmentDirection | null;
129
+ email?: { subject?: string | null; from?: string | null } | null;
130
+ /** Operador (outbound humano) ou quem subiu na ficha. */
131
+ uploaded_by?: IAttachmentActor | null;
132
+ /** Ordenação da listagem. */
133
+ occurred_at: Date;
134
+ }
135
+
136
+ export interface IAttachmentFile {
137
+ /** Ausente quando `blocked` (só `quarantine_uri`). */
138
+ gcs_uri?: string | null;
139
+ filename: string;
140
+ original_filename?: string | null;
141
+ content_type: string;
142
+ size_bytes?: number | null;
143
+ /** Dedupe; null quando a fonte não fornece. */
144
+ sha256?: string | null;
145
+ blocked?: boolean;
146
+ blocked_reason?: string | null;
147
+ quarantine_uri?: string | null;
148
+ media_kind: AttachmentMediaKind;
149
+ caption?: string | null;
150
+ }
151
+
152
+ export interface IAttachmentAiSuggestion {
153
+ /** Vocabulário do classificador (`ATTACHMENT_KINDS` do @evo/hubia). */
154
+ kind: string;
155
+ label?: string | null;
156
+ summary: string;
157
+ confidence: number;
158
+ prompt_version: string;
159
+ suggested_base_category: PatientAttachmentBaseCategory | null;
160
+ classified_at: Date;
161
+ }
162
+
163
+ export interface IAttachmentClassification {
164
+ /** Snapshot do `display_name` do dicionário `attachment_categories` (feat-021). */
165
+ category?: string | null;
166
+ base_category?: PatientAttachmentBaseCategory | null;
167
+ category_color?: string | null;
168
+ source: AttachmentClassificationSource;
169
+ reviewed_by?: IAttachmentActor | null;
170
+ reviewed_at?: Date | null;
171
+ ai?: IAttachmentAiSuggestion | null;
172
+ }
173
+
174
+ export interface IAttachmentLegacy {
175
+ patient_id: string;
176
+ migrated_at: Date;
177
+ }
178
+
179
+ /** Anexo unificado: tenants/{t}/apps/evo-docs/attachments/{id}. Escrita só pelo backend. */
180
+ export interface IAttachment extends IFireDoc {
181
+ externalLinks: IExternalLink[];
182
+ /** "type:id", derivado pelo model (nunca vem do cliente). */
183
+ externalLinkKeys: string[];
184
+ primary_subject: { type: AttachmentSubjectType; id: string };
185
+ source: IAttachmentSource;
186
+ file: IAttachmentFile;
187
+ classification: IAttachmentClassification;
188
+ /** Mesmo shape das tags do lead (`ITag`), não `string[]`. */
189
+ tags?: ITag[] | null;
190
+ description?: string | null;
191
+ /** Fonte A migrada do array (Q7): auditoria da migração lazy. */
192
+ legacy?: IAttachmentLegacy | null;
193
+ created_by?: IAttachmentActor | null;
194
+ }
195
+
196
+ // ───────── Evento de indexação (§2.3) ─────────
197
+
198
+ /** Motivo da publicação: mensagem persistida ou republicação manual (`POST /attachments/reindex`). */
199
+ export const AttachmentIndexReasonEnum = {
200
+ Message: "message",
201
+ Reindex: "reindex",
202
+ } as const;
203
+
204
+ export type AttachmentIndexReason =
205
+ (typeof AttachmentIndexReasonEnum)[keyof typeof AttachmentIndexReasonEnum];
206
+
207
+ /**
208
+ * Payload do tópico `app_evo-docs_attachments_index`. Só ids e o contexto que o ponto de
209
+ * publish já tem em memória; nenhum campo do arquivo (o consumidor relê a mensagem).
210
+ */
211
+ export interface IAttachmentIndexEvent {
212
+ tenant: string;
213
+ thread_id: string;
214
+ message_id: string;
215
+ direction: MessageDirection;
216
+ provider: string;
217
+ channel_id: string;
218
+ channel_type: string;
219
+ ticket_id?: string | null;
220
+ department_id?: string | null;
221
+ lead_id?: string | null;
222
+ /** Links da notificação (ponto 6); o consumidor filtra para `ATTACHMENT_SUBJECT_TYPES`. */
223
+ external_links?: IExternalLink[] | null;
224
+ created_by?: IAttachmentActor | null;
225
+ occurred_at: Date;
226
+ trace_id?: string | null;
227
+ /** Default `message`. */
228
+ reason?: AttachmentIndexReason;
229
+ }
230
+
231
+ /** Atributos Pub/Sub da mensagem do evento (sempre string). */
232
+ export interface IAttachmentIndexEventAttributes {
233
+ tenant: string;
234
+ direction: MessageDirection;
235
+ trace_id?: string;
236
+ }
237
+
238
+ // ───────── Classificação (§2.4) ─────────
239
+
240
+ /** Confiança mínima para a sugestão da HubIA virar categoria (D4; mesma do classificador). */
241
+ export const ATTACHMENT_APPLY_MIN_CONFIDENCE = 0.7;
242
+
243
+ /**
244
+ * `kind` do classificador da HubIA → categoria base da feat-021. `unreadable` não sugere.
245
+ * `skipped` é do use case (não é kind do modelo) e não grava `classification.ai`.
246
+ */
247
+ export const HUBIA_ATTACHMENT_KIND_TO_BASE_CATEGORY = {
248
+ insurance_card: PatientAttachmentBaseCategoryEnum.InsuranceCard,
249
+ id_document: PatientAttachmentBaseCategoryEnum.IdentificationDocument,
250
+ medical_exam: PatientAttachmentBaseCategoryEnum.MedicalExam,
251
+ prescription: PatientAttachmentBaseCategoryEnum.Prescription,
252
+ referral: PatientAttachmentBaseCategoryEnum.ReferralLetter,
253
+ payment_proof: PatientAttachmentBaseCategoryEnum.PaymentReceipt,
254
+ screenshot: PatientAttachmentBaseCategoryEnum.Other,
255
+ photo_other: PatientAttachmentBaseCategoryEnum.Other,
256
+ document_other: PatientAttachmentBaseCategoryEnum.Other,
257
+ unreadable: null,
258
+ } as const satisfies Record<string, PatientAttachmentBaseCategory | null>;
259
+
260
+ export type HubiaAttachmentKind = keyof typeof HUBIA_ATTACHMENT_KIND_TO_BASE_CATEGORY;
261
+
262
+ /** Kind conhecido → categoria (ou null); kind desconhecido → `other`; kind vazio → null. */
263
+ export function baseCategoryForHubiaKind(
264
+ kind: string | null | undefined,
265
+ ): PatientAttachmentBaseCategory | null {
266
+ if (typeof kind !== "string" || kind.trim() === "") return null;
267
+ if (Object.prototype.hasOwnProperty.call(HUBIA_ATTACHMENT_KIND_TO_BASE_CATEGORY, kind)) {
268
+ return HUBIA_ATTACHMENT_KIND_TO_BASE_CATEGORY[kind as HubiaAttachmentKind];
269
+ }
270
+ return PatientAttachmentBaseCategoryEnum.Other;
271
+ }
272
+
273
+ // ───────── API do hub-omni (`hubomni_admin`, §2.7) ─────────
274
+
275
+ export const ATTACHMENT_LIST_DEFAULT_LIMIT = 50;
276
+ export const ATTACHMENT_LIST_MAX_LIMIT = 100;
277
+ /** D7: filtro `message_ids` (sidebar da feat-316), `in` sobre `source.message_id`. */
278
+ export const ATTACHMENT_LIST_MAX_MESSAGE_IDS = 30;
279
+ export const ATTACHMENT_DESCRIPTION_MAX = 1000;
280
+ export const ATTACHMENT_TAGS_MAX = 30;
281
+
282
+ /**
283
+ * Query de `GET /attachments` já interpretada (o FE serializa em query string).
284
+ * Exatamente um de `subject` ou `message_ids`; `message_ids` não aceita `family`/`cursor`.
285
+ */
286
+ export interface IAttachmentListQuery {
287
+ /** "type:id" com type ∈ `ATTACHMENT_LIST_ROOT_TYPES`. */
288
+ subject?: string;
289
+ /** Até 30 ids de mensagem; sem família nem cursor. */
290
+ message_ids?: string[];
291
+ family?: boolean;
292
+ /** Interno (Q5: camada 2 desligada) — não expor na tela nem no service do FE. */
293
+ family_depth?: 1 | 2;
294
+ /** Paciente da consulta, junto de `subject=med_appointment:{id}` (migração lazy). */
295
+ patient?: string;
296
+ direction?: AttachmentDirection;
297
+ base_category?: PatientAttachmentBaseCategory;
298
+ blocked?: boolean;
299
+ media_kind?: AttachmentMediaKind;
300
+ source_kind?: AttachmentSourceKind;
301
+ tag?: string;
302
+ /** Default `ATTACHMENT_LIST_DEFAULT_LIMIT`, máx. `ATTACHMENT_LIST_MAX_LIMIT`. */
303
+ limit?: number;
304
+ /** base64url de `{ o: occurred_at ISO, id }`. */
305
+ cursor?: string;
306
+ }
307
+
308
+ /** Nó da família que trouxe o item quando ele não tem a key da raiz (rótulo "via …"). */
309
+ export interface IAttachmentVia {
310
+ type: ExternalObjectType;
311
+ id: string;
312
+ display_name?: string | null;
313
+ relation?: IExternalLinkRelation | null;
314
+ channel_type?: string | null;
315
+ }
316
+
317
+ export type AttachmentListItemOrigin = "collection" | "legacy_array";
318
+
319
+ export interface IAttachmentListItem extends IAttachment {
320
+ via?: IAttachmentVia | null;
321
+ /** Quantas outras cópias com o mesmo `file.sha256` foram recolhidas neste item, na página. */
322
+ duplicates?: number;
323
+ can_edit: boolean;
324
+ origin: AttachmentListItemOrigin;
325
+ }
326
+
327
+ export interface IAttachmentFamilyContext {
328
+ /** Nós da família cujos anexos entraram (camada 1: vínculos confirmed/legacy). */
329
+ nodes?: IAttachmentVia[];
330
+ /** Teto de keys atingido (120); parte da família ficou de fora. */
331
+ truncated?: boolean;
332
+ /** Família pedida mas omitida (sem permissão de leitura do tipo oposto/chat). */
333
+ omitted?: "permission" | null;
334
+ }
335
+
336
+ export interface IAttachmentListResponse {
337
+ ok: true;
338
+ items: IAttachmentListItem[];
339
+ next_cursor: string | null;
340
+ family?: IAttachmentFamilyContext;
341
+ /** Itens migrados do array do paciente nesta chamada (migração lazy, Q7). */
342
+ migrated?: number;
343
+ }
344
+
345
+ /** Vínculo adicionado/removido pelo PATCH: só tipos de `ATTACHMENT_SUBJECT_TYPES`. */
346
+ export interface IAttachmentSubjectRef {
347
+ type: AttachmentSubjectType;
348
+ id: string;
349
+ label?: string;
350
+ }
351
+
352
+ /** Corpo de `PATCH /attachments/:id` (zod `zAttachmentPatchBodySchema`, strict). */
353
+ export interface IAttachmentPatchBody {
354
+ category?: string | null;
355
+ base_category?: PatientAttachmentBaseCategory | null;
356
+ category_color?: string | null;
357
+ description?: string | null;
358
+ tags?: ITag[];
359
+ add_links?: IAttachmentSubjectRef[];
360
+ remove_links?: IAttachmentSubjectRef[];
361
+ }
362
+
363
+ export interface IAttachmentPatchResponse {
364
+ ok: true;
365
+ item: IAttachmentListItem;
366
+ }
367
+
368
+ /** Resposta de `GET /attachments/:id/signed-url` (TTL 1 h; quarentena 5 min). */
369
+ export interface IAttachmentSignedUrlResponse {
370
+ ok: true;
371
+ url: string;
372
+ filename: string;
373
+ expires_at: string;
374
+ }
375
+
376
+ /** Corpo de `POST /attachments/reindex`: só republica o evento de indexação. */
377
+ export interface IAttachmentReindexBody {
378
+ thread_id: string;
379
+ message_id?: string;
380
+ }
381
+
382
+ export interface IAttachmentReindexResponse {
383
+ ok: true;
384
+ published: number;
385
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "evo360-types",
3
- "version": "1.3.764",
3
+ "version": "1.3.768",
4
4
  "description": "HREVO360 Shared Types",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",