evo360-types 1.3.656 → 1.3.662

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/apps/evo-csq/zod-schemas.d.ts +40 -40
  2. package/dist/apps/evo-modules/zod-schemas.d.ts +446 -0
  3. package/dist/apps/evo-modules/zod-schemas.js +143 -0
  4. package/dist/apps/evo-modules/zod-schemas.ts +153 -0
  5. package/dist/apps/evo-task/zod-schemas.d.ts +201 -4
  6. package/dist/apps/evo-task/zod-schemas.js +22 -2
  7. package/dist/apps/evo-task/zod-schemas.ts +23 -1
  8. package/dist/index.d.ts +2 -0
  9. package/dist/index.js +2 -0
  10. package/dist/index.ts +2 -0
  11. package/dist/types/evo-modules/activation.d.ts +46 -0
  12. package/dist/types/evo-modules/activation.js +131 -0
  13. package/dist/types/evo-modules/activation.ts +150 -0
  14. package/dist/types/evo-modules/catalog.d.ts +28 -0
  15. package/dist/types/evo-modules/catalog.js +130 -0
  16. package/dist/types/evo-modules/catalog.ts +131 -0
  17. package/dist/types/evo-modules/index.d.ts +227 -0
  18. package/dist/types/evo-modules/index.js +75 -0
  19. package/dist/types/evo-modules/index.ts +329 -0
  20. package/dist/types/evo-task/index.d.ts +14 -0
  21. package/dist/types/evo-task/index.js +3 -0
  22. package/dist/types/evo-task/index.ts +25 -0
  23. package/dist/types/evo-task-runner/index.d.ts +2 -1
  24. package/dist/types/evo-task-runner/index.ts +5 -1
  25. package/dist/types/evo-telemedicine/fb_collections.js +1 -1
  26. package/dist/types/evo-telemedicine/fb_collections.ts +1 -1
  27. package/dist/types/evo-telemedicine/index.d.ts +8 -12
  28. package/dist/types/evo-telemedicine/index.ts +8 -12
  29. package/dist/types/evo-tenant/index.ts +3 -1
  30. package/fixtures/tenant-modules/is-module-active.parity.json +364 -0
  31. package/package.json +7 -4
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.moduleDateToMillis = moduleDateToMillis;
4
+ exports.isModuleActive = isModuleActive;
5
+ exports.hasModuleCapability = hasModuleCapability;
6
+ exports.moduleContractMismatches = moduleContractMismatches;
7
+ const catalog_1 = require("./catalog");
8
+ /**
9
+ * Normaliza qualquer forma de data que chega às superfícies: `Date`, Firestore
10
+ * `Timestamp` (`toDate()`), Timestamp serializado (`{_seconds}` / `{seconds}`),
11
+ * ISO string e epoch em ms. Inválido ⇒ `null` (equivale a "sem data").
12
+ */
13
+ function moduleDateToMillis(value) {
14
+ if (value === null || value === undefined || value === "")
15
+ return null;
16
+ if (value instanceof Date) {
17
+ const t = value.getTime();
18
+ return isNaN(t) ? null : t;
19
+ }
20
+ if (typeof value === "number")
21
+ return isFinite(value) ? value : null;
22
+ if (typeof value === "string") {
23
+ const t = new Date(value).getTime();
24
+ return isNaN(t) ? null : t;
25
+ }
26
+ if (typeof value === "object") {
27
+ const v = value;
28
+ if (typeof v.toDate === "function") {
29
+ try {
30
+ const d = v.toDate();
31
+ if (d instanceof Date) {
32
+ const t = d.getTime();
33
+ return isNaN(t) ? null : t;
34
+ }
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ return null;
40
+ }
41
+ const seconds = typeof v._seconds === "number" ? v._seconds : typeof v.seconds === "number" ? v.seconds : null;
42
+ if (seconds !== null && isFinite(seconds)) {
43
+ const nanos = typeof v._nanoseconds === "number" ? v._nanoseconds : typeof v.nanoseconds === "number" ? v.nanoseconds : 0;
44
+ return seconds * 1000 + Math.floor(nanos / 1e6);
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+ /**
50
+ * Decide se o entitlement autoriza um uso NOVO do módulo. Função pura e ÚNICA:
51
+ * backend (`Core.Tenant.isModuleActive`), web-app e Nexus usam esta; o Flutter
52
+ * espelha e prova pela fixture `fixtures/tenant-modules/is-module-active.parity.json`.
53
+ *
54
+ * Ordem das cláusulas (importa):
55
+ * 1. `override_until` futuro COM `override_by` libera (D6: exceção operacional
56
+ * temporária e auditada) — mesmo suspenso/cancelado/vencido;
57
+ * 2. `enabled !== true` bloqueia;
58
+ * 3. `suspended`/`cancelled` bloqueiam;
59
+ * 4. `effective_at` no futuro bloqueia;
60
+ * 5. `expires_at` no passado (ou agora) bloqueia, para QUALQUER status;
61
+ * 6. só `active` e `trial` liberam.
62
+ *
63
+ * Não tem parâmetro de papel: super admin não ignora entitlement (D6).
64
+ */
65
+ function isModuleActive(entitlement, now = new Date()) {
66
+ if (!entitlement || typeof entitlement !== "object")
67
+ return false;
68
+ const t = now.getTime();
69
+ const overrideUntil = moduleDateToMillis(entitlement.override_until);
70
+ if (overrideUntil !== null && overrideUntil > t && !!entitlement.override_by)
71
+ return true;
72
+ if (entitlement.enabled !== true)
73
+ return false;
74
+ if (entitlement.status === "suspended" || entitlement.status === "cancelled")
75
+ return false;
76
+ const effectiveAt = moduleDateToMillis(entitlement.effective_at);
77
+ if (effectiveAt !== null && effectiveAt > t)
78
+ return false;
79
+ const expiresAt = moduleDateToMillis(entitlement.expires_at);
80
+ if (expiresAt !== null && expiresAt <= t)
81
+ return false;
82
+ return entitlement.status === "active" || entitlement.status === "trial";
83
+ }
84
+ /**
85
+ * Capability ausente, não-booleana (`"true"`, `1`) ou `false` equivale a `false`.
86
+ * Não implica módulo ativo: o gate de UI equivalente ao backend é
87
+ * `isModuleActive(e) && hasModuleCapability(e, cap)`.
88
+ */
89
+ function hasModuleCapability(entitlement, capability) {
90
+ if (!entitlement || !entitlement.capabilities)
91
+ return false;
92
+ return entitlement.capabilities[capability] === true;
93
+ }
94
+ /**
95
+ * Divergências entre franquias do contrato (`allowances`) e módulos do tenant,
96
+ * pelas `allowance_metrics` do catálogo. Só informa (a tela de contrato mostra);
97
+ * nada sincroniza sozinho (Q1).
98
+ *
99
+ * - `active_without_allowance`: módulo ativo e nenhuma métrica dele no contrato
100
+ * (consumo invisível ao alerta e ao portal);
101
+ * - `allowance_without_module`: contrato tem franquia de uma métrica do módulo e
102
+ * o módulo não está ativo.
103
+ */
104
+ function moduleContractMismatches(allowances, modules, now = new Date()) {
105
+ const out = [];
106
+ const allow = allowances && typeof allowances === "object" ? allowances : {};
107
+ const mods = modules && typeof modules === "object" ? modules : {};
108
+ for (const key in catalog_1.PLATFORM_MODULE_CATALOG) {
109
+ if (!Object.prototype.hasOwnProperty.call(catalog_1.PLATFORM_MODULE_CATALOG, key))
110
+ continue;
111
+ const def = catalog_1.PLATFORM_MODULE_CATALOG[key];
112
+ if (def.allowance_metrics.length === 0)
113
+ continue;
114
+ const active = isModuleActive(Object.prototype.hasOwnProperty.call(mods, key) ? mods[key] : null, now);
115
+ const present = [];
116
+ for (const m of def.allowance_metrics) {
117
+ if (Object.prototype.hasOwnProperty.call(allow, m.metric) && allow[m.metric] !== null && allow[m.metric] !== undefined) {
118
+ present.push(m.metric);
119
+ }
120
+ }
121
+ if (active && present.length === 0) {
122
+ out.push({ module: key, metric: def.allowance_metrics[0].metric, kind: "active_without_allowance" });
123
+ }
124
+ if (!active) {
125
+ for (const metric of present) {
126
+ out.push({ module: key, metric, kind: "allowance_without_module" });
127
+ }
128
+ }
129
+ }
130
+ return out;
131
+ }
@@ -0,0 +1,150 @@
1
+ import type { ITenantModuleEntitlement } from "../evo-tenant";
2
+ import { PLATFORM_MODULE_CATALOG } from "./catalog";
3
+
4
+ /**
5
+ * Normaliza qualquer forma de data que chega às superfícies: `Date`, Firestore
6
+ * `Timestamp` (`toDate()`), Timestamp serializado (`{_seconds}` / `{seconds}`),
7
+ * ISO string e epoch em ms. Inválido ⇒ `null` (equivale a "sem data").
8
+ */
9
+ export function moduleDateToMillis(value: unknown): number | null {
10
+ if (value === null || value === undefined || value === "") return null;
11
+ if (value instanceof Date) {
12
+ const t = value.getTime();
13
+ return isNaN(t) ? null : t;
14
+ }
15
+ if (typeof value === "number") return isFinite(value) ? value : null;
16
+ if (typeof value === "string") {
17
+ const t = new Date(value).getTime();
18
+ return isNaN(t) ? null : t;
19
+ }
20
+ if (typeof value === "object") {
21
+ const v = value as {
22
+ toDate?: unknown;
23
+ _seconds?: unknown;
24
+ seconds?: unknown;
25
+ _nanoseconds?: unknown;
26
+ nanoseconds?: unknown;
27
+ };
28
+ if (typeof v.toDate === "function") {
29
+ try {
30
+ const d = (v.toDate as () => unknown)();
31
+ if (d instanceof Date) {
32
+ const t = d.getTime();
33
+ return isNaN(t) ? null : t;
34
+ }
35
+ } catch {
36
+ return null;
37
+ }
38
+ return null;
39
+ }
40
+ const seconds = typeof v._seconds === "number" ? v._seconds : typeof v.seconds === "number" ? v.seconds : null;
41
+ if (seconds !== null && isFinite(seconds)) {
42
+ const nanos =
43
+ typeof v._nanoseconds === "number" ? v._nanoseconds : typeof v.nanoseconds === "number" ? v.nanoseconds : 0;
44
+ return seconds * 1000 + Math.floor(nanos / 1e6);
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+
50
+ /**
51
+ * Decide se o entitlement autoriza um uso NOVO do módulo. Função pura e ÚNICA:
52
+ * backend (`Core.Tenant.isModuleActive`), web-app e Nexus usam esta; o Flutter
53
+ * espelha e prova pela fixture `fixtures/tenant-modules/is-module-active.parity.json`.
54
+ *
55
+ * Ordem das cláusulas (importa):
56
+ * 1. `override_until` futuro COM `override_by` libera (D6: exceção operacional
57
+ * temporária e auditada) — mesmo suspenso/cancelado/vencido;
58
+ * 2. `enabled !== true` bloqueia;
59
+ * 3. `suspended`/`cancelled` bloqueiam;
60
+ * 4. `effective_at` no futuro bloqueia;
61
+ * 5. `expires_at` no passado (ou agora) bloqueia, para QUALQUER status;
62
+ * 6. só `active` e `trial` liberam.
63
+ *
64
+ * Não tem parâmetro de papel: super admin não ignora entitlement (D6).
65
+ */
66
+ export function isModuleActive(
67
+ entitlement: ITenantModuleEntitlement | null | undefined,
68
+ now: Date = new Date(),
69
+ ): boolean {
70
+ if (!entitlement || typeof entitlement !== "object") return false;
71
+
72
+ const t = now.getTime();
73
+
74
+ const overrideUntil = moduleDateToMillis(entitlement.override_until);
75
+ if (overrideUntil !== null && overrideUntil > t && !!entitlement.override_by) return true;
76
+
77
+ if (entitlement.enabled !== true) return false;
78
+ if (entitlement.status === "suspended" || entitlement.status === "cancelled") return false;
79
+
80
+ const effectiveAt = moduleDateToMillis(entitlement.effective_at);
81
+ if (effectiveAt !== null && effectiveAt > t) return false;
82
+
83
+ const expiresAt = moduleDateToMillis(entitlement.expires_at);
84
+ if (expiresAt !== null && expiresAt <= t) return false;
85
+
86
+ return entitlement.status === "active" || entitlement.status === "trial";
87
+ }
88
+
89
+ /**
90
+ * Capability ausente, não-booleana (`"true"`, `1`) ou `false` equivale a `false`.
91
+ * Não implica módulo ativo: o gate de UI equivalente ao backend é
92
+ * `isModuleActive(e) && hasModuleCapability(e, cap)`.
93
+ */
94
+ export function hasModuleCapability(
95
+ entitlement: ITenantModuleEntitlement | null | undefined,
96
+ capability: string,
97
+ ): boolean {
98
+ if (!entitlement || !entitlement.capabilities) return false;
99
+ return entitlement.capabilities[capability] === true;
100
+ }
101
+
102
+ export interface IModuleContractMismatch {
103
+ module: string;
104
+ metric: string;
105
+ kind: "active_without_allowance" | "allowance_without_module";
106
+ }
107
+
108
+ /**
109
+ * Divergências entre franquias do contrato (`allowances`) e módulos do tenant,
110
+ * pelas `allowance_metrics` do catálogo. Só informa (a tela de contrato mostra);
111
+ * nada sincroniza sozinho (Q1).
112
+ *
113
+ * - `active_without_allowance`: módulo ativo e nenhuma métrica dele no contrato
114
+ * (consumo invisível ao alerta e ao portal);
115
+ * - `allowance_without_module`: contrato tem franquia de uma métrica do módulo e
116
+ * o módulo não está ativo.
117
+ */
118
+ export function moduleContractMismatches(
119
+ allowances: Record<string, unknown> | null | undefined,
120
+ modules: Record<string, ITenantModuleEntitlement> | null | undefined,
121
+ now: Date = new Date(),
122
+ ): IModuleContractMismatch[] {
123
+ const out: IModuleContractMismatch[] = [];
124
+ const allow = allowances && typeof allowances === "object" ? allowances : {};
125
+ const mods = modules && typeof modules === "object" ? modules : {};
126
+
127
+ for (const key in PLATFORM_MODULE_CATALOG) {
128
+ if (!Object.prototype.hasOwnProperty.call(PLATFORM_MODULE_CATALOG, key)) continue;
129
+ const def = PLATFORM_MODULE_CATALOG[key];
130
+ if (def.allowance_metrics.length === 0) continue;
131
+
132
+ const active = isModuleActive(Object.prototype.hasOwnProperty.call(mods, key) ? mods[key] : null, now);
133
+ const present: string[] = [];
134
+ for (const m of def.allowance_metrics) {
135
+ if (Object.prototype.hasOwnProperty.call(allow, m.metric) && allow[m.metric] !== null && allow[m.metric] !== undefined) {
136
+ present.push(m.metric);
137
+ }
138
+ }
139
+
140
+ if (active && present.length === 0) {
141
+ out.push({ module: key, metric: def.allowance_metrics[0].metric, kind: "active_without_allowance" });
142
+ }
143
+ if (!active) {
144
+ for (const metric of present) {
145
+ out.push({ module: key, metric, kind: "allowance_without_module" });
146
+ }
147
+ }
148
+ }
149
+ return out;
150
+ }
@@ -0,0 +1,28 @@
1
+ import type { IPlatformModuleDefinition } from "./index";
2
+ /**
3
+ * Versão do catálogo, gravada em `IModuleProvisioningRun.types_version`.
4
+ * Mudou capability, passo, grupo ou métrica de algum módulo ⇒ incrementar: o
5
+ * run antigo precisa dizer com que catálogo foi planejado.
6
+ */
7
+ export declare const PLATFORM_MODULE_CATALOG_VERSION = "2026-10-06.1";
8
+ export declare const PLATFORM_MODULE_TELEMEDICINE = "telemedicine";
9
+ export declare const PLATFORM_MODULE_CSQ = "csq";
10
+ /**
11
+ * Catálogo de módulos da plataforma (feat-263). É código, não Firestore: carrega
12
+ * comportamento (passos, grupos, métricas) e precisa de versionamento e tipos.
13
+ *
14
+ * Módulo novo = uma entrada aqui + publish. O estado por tenant continua em
15
+ * `tenants/{t}.modules[key]`.
16
+ */
17
+ export declare const PLATFORM_MODULE_CATALOG: Readonly<Record<string, IPlatformModuleDefinition>>;
18
+ export declare function getModuleDefinition(key: string | null | undefined): IPlatformModuleDefinition | null;
19
+ /** Definições em ordem estável (ordem de declaração). */
20
+ export declare function listModuleDefinitions(): IPlatformModuleDefinition[];
21
+ /** Chaves do catálogo em ordem de declaração. */
22
+ export declare function listModuleKeys(): string[];
23
+ /** Capabilities default do módulo (mapa novo a cada chamada). */
24
+ export declare function buildModuleDefaultCapabilities(definition: IPlatformModuleDefinition): Record<string, boolean | number | string>;
25
+ /** Módulos que tenant novo recebe habilitados. */
26
+ export declare function listDefaultModulesForNewTenants(): IPlatformModuleDefinition[];
27
+ /** União, sem repetição e em ordem, dos grupos RBAC dos módulos default de tenant novo. */
28
+ export declare function listDefaultTenantRbacGroups(): string[];
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PLATFORM_MODULE_CATALOG = exports.PLATFORM_MODULE_CSQ = exports.PLATFORM_MODULE_TELEMEDICINE = exports.PLATFORM_MODULE_CATALOG_VERSION = void 0;
4
+ exports.getModuleDefinition = getModuleDefinition;
5
+ exports.listModuleDefinitions = listModuleDefinitions;
6
+ exports.listModuleKeys = listModuleKeys;
7
+ exports.buildModuleDefaultCapabilities = buildModuleDefaultCapabilities;
8
+ exports.listDefaultModulesForNewTenants = listDefaultModulesForNewTenants;
9
+ exports.listDefaultTenantRbacGroups = listDefaultTenantRbacGroups;
10
+ /**
11
+ * Versão do catálogo, gravada em `IModuleProvisioningRun.types_version`.
12
+ * Mudou capability, passo, grupo ou métrica de algum módulo ⇒ incrementar: o
13
+ * run antigo precisa dizer com que catálogo foi planejado.
14
+ */
15
+ exports.PLATFORM_MODULE_CATALOG_VERSION = "2026-10-06.1";
16
+ exports.PLATFORM_MODULE_TELEMEDICINE = "telemedicine";
17
+ exports.PLATFORM_MODULE_CSQ = "csq";
18
+ /**
19
+ * Catálogo de módulos da plataforma (feat-263). É código, não Firestore: carrega
20
+ * comportamento (passos, grupos, métricas) e precisa de versionamento e tipos.
21
+ *
22
+ * Módulo novo = uma entrada aqui + publish. O estado por tenant continua em
23
+ * `tenants/{t}.modules[key]`.
24
+ */
25
+ exports.PLATFORM_MODULE_CATALOG = {
26
+ telemedicine: {
27
+ key: exports.PLATFORM_MODULE_TELEMEDICINE,
28
+ label: "Virtual Care (Telemedicina)",
29
+ description: "Teleconsultas por vídeo integradas à agenda, com gravação e admissão automática.",
30
+ app_id: "evo-telemedicine",
31
+ // Defaults idênticos ao `TELEMEDICINE_DEFAULT_CAPABILITIES` da R5 (feat-160):
32
+ // transcrição NUNCA nasce ligada (gate documental D12).
33
+ capabilities: {
34
+ recording: { label: "Gravação", default: true },
35
+ transcription: { label: "Transcrição", default: false },
36
+ auto_admit: { label: "Admissão automática", default: true },
37
+ },
38
+ // `active/contract` sem `expires_at`: a franquia faz parte do contrato; um
39
+ // `expires_at` desligaria a base inteira numa data, em silêncio.
40
+ default_entitlement: { status: "active", source: "contract" },
41
+ default_for_new_tenants: true,
42
+ rbac_groups: ["evo-telemedicine"],
43
+ allowance_metrics: [{ metric: "teleconsultations_unrecorded", default_included: 5 }],
44
+ rollout: {
45
+ path: "platform/evo-telemedicine/config/rollout",
46
+ layout: "legacy_fields",
47
+ flags: {
48
+ create: "create_enabled",
49
+ join: "join_enabled",
50
+ recording: "recording_enabled",
51
+ transcription: "transcription_enabled",
52
+ },
53
+ },
54
+ depends_on: [],
55
+ provisioning: {
56
+ enable: ["entitlement", "rbac_group", "rbac_recompute", "contract_allowance", "rollout_check"],
57
+ // O grupo RBAC fica no disable (Q7): o upsell depende de `evo_telemedicine_read`.
58
+ disable: ["entitlement", "contract_check"],
59
+ },
60
+ legacy: { audit_collections: ["apps/evo-telemedicine/entitlement-audit"] },
61
+ },
62
+ csq: {
63
+ key: exports.PLATFORM_MODULE_CSQ,
64
+ label: "CSQ — Qualidade do atendimento",
65
+ description: "Avaliação automática da qualidade das conversas encerradas (laudo por ticket).",
66
+ app_id: "evo-csq",
67
+ capabilities: {},
68
+ default_entitlement: { status: "active", source: "manual" },
69
+ default_for_new_tenants: false,
70
+ rbac_groups: [],
71
+ allowance_metrics: [],
72
+ rollout: null,
73
+ depends_on: [],
74
+ provisioning: {
75
+ enable: ["entitlement"],
76
+ disable: ["entitlement"],
77
+ },
78
+ },
79
+ };
80
+ function getModuleDefinition(key) {
81
+ if (!key || typeof key !== "string")
82
+ return null;
83
+ if (!Object.prototype.hasOwnProperty.call(exports.PLATFORM_MODULE_CATALOG, key))
84
+ return null;
85
+ return exports.PLATFORM_MODULE_CATALOG[key];
86
+ }
87
+ /** Definições em ordem estável (ordem de declaração). */
88
+ function listModuleDefinitions() {
89
+ const out = [];
90
+ for (const key in exports.PLATFORM_MODULE_CATALOG) {
91
+ if (Object.prototype.hasOwnProperty.call(exports.PLATFORM_MODULE_CATALOG, key)) {
92
+ out.push(exports.PLATFORM_MODULE_CATALOG[key]);
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+ /** Chaves do catálogo em ordem de declaração. */
98
+ function listModuleKeys() {
99
+ const out = [];
100
+ for (const key in exports.PLATFORM_MODULE_CATALOG) {
101
+ if (Object.prototype.hasOwnProperty.call(exports.PLATFORM_MODULE_CATALOG, key))
102
+ out.push(key);
103
+ }
104
+ return out;
105
+ }
106
+ /** Capabilities default do módulo (mapa novo a cada chamada). */
107
+ function buildModuleDefaultCapabilities(definition) {
108
+ const out = {};
109
+ for (const cap in definition.capabilities) {
110
+ if (Object.prototype.hasOwnProperty.call(definition.capabilities, cap)) {
111
+ out[cap] = definition.capabilities[cap].default;
112
+ }
113
+ }
114
+ return out;
115
+ }
116
+ /** Módulos que tenant novo recebe habilitados. */
117
+ function listDefaultModulesForNewTenants() {
118
+ return listModuleDefinitions().filter((d) => d.default_for_new_tenants);
119
+ }
120
+ /** União, sem repetição e em ordem, dos grupos RBAC dos módulos default de tenant novo. */
121
+ function listDefaultTenantRbacGroups() {
122
+ const out = [];
123
+ for (const def of listDefaultModulesForNewTenants()) {
124
+ for (const g of def.rbac_groups) {
125
+ if (out.indexOf(g) === -1)
126
+ out.push(g);
127
+ }
128
+ }
129
+ return out;
130
+ }
@@ -0,0 +1,131 @@
1
+ import type { IPlatformModuleDefinition } from "./index";
2
+
3
+ /**
4
+ * Versão do catálogo, gravada em `IModuleProvisioningRun.types_version`.
5
+ * Mudou capability, passo, grupo ou métrica de algum módulo ⇒ incrementar: o
6
+ * run antigo precisa dizer com que catálogo foi planejado.
7
+ */
8
+ export const PLATFORM_MODULE_CATALOG_VERSION = "2026-10-06.1";
9
+
10
+ export const PLATFORM_MODULE_TELEMEDICINE = "telemedicine";
11
+ export const PLATFORM_MODULE_CSQ = "csq";
12
+
13
+ /**
14
+ * Catálogo de módulos da plataforma (feat-263). É código, não Firestore: carrega
15
+ * comportamento (passos, grupos, métricas) e precisa de versionamento e tipos.
16
+ *
17
+ * Módulo novo = uma entrada aqui + publish. O estado por tenant continua em
18
+ * `tenants/{t}.modules[key]`.
19
+ */
20
+ export const PLATFORM_MODULE_CATALOG: Readonly<Record<string, IPlatformModuleDefinition>> = {
21
+ telemedicine: {
22
+ key: PLATFORM_MODULE_TELEMEDICINE,
23
+ label: "Virtual Care (Telemedicina)",
24
+ description:
25
+ "Teleconsultas por vídeo integradas à agenda, com gravação e admissão automática.",
26
+ app_id: "evo-telemedicine",
27
+ // Defaults idênticos ao `TELEMEDICINE_DEFAULT_CAPABILITIES` da R5 (feat-160):
28
+ // transcrição NUNCA nasce ligada (gate documental D12).
29
+ capabilities: {
30
+ recording: { label: "Gravação", default: true },
31
+ transcription: { label: "Transcrição", default: false },
32
+ auto_admit: { label: "Admissão automática", default: true },
33
+ },
34
+ // `active/contract` sem `expires_at`: a franquia faz parte do contrato; um
35
+ // `expires_at` desligaria a base inteira numa data, em silêncio.
36
+ default_entitlement: { status: "active", source: "contract" },
37
+ default_for_new_tenants: true,
38
+ rbac_groups: ["evo-telemedicine"],
39
+ allowance_metrics: [{ metric: "teleconsultations_unrecorded", default_included: 5 }],
40
+ rollout: {
41
+ path: "platform/evo-telemedicine/config/rollout",
42
+ layout: "legacy_fields",
43
+ flags: {
44
+ create: "create_enabled",
45
+ join: "join_enabled",
46
+ recording: "recording_enabled",
47
+ transcription: "transcription_enabled",
48
+ },
49
+ },
50
+ depends_on: [],
51
+ provisioning: {
52
+ enable: ["entitlement", "rbac_group", "rbac_recompute", "contract_allowance", "rollout_check"],
53
+ // O grupo RBAC fica no disable (Q7): o upsell depende de `evo_telemedicine_read`.
54
+ disable: ["entitlement", "contract_check"],
55
+ },
56
+ legacy: { audit_collections: ["apps/evo-telemedicine/entitlement-audit"] },
57
+ },
58
+ csq: {
59
+ key: PLATFORM_MODULE_CSQ,
60
+ label: "CSQ — Qualidade do atendimento",
61
+ description:
62
+ "Avaliação automática da qualidade das conversas encerradas (laudo por ticket).",
63
+ app_id: "evo-csq",
64
+ capabilities: {},
65
+ default_entitlement: { status: "active", source: "manual" },
66
+ default_for_new_tenants: false,
67
+ rbac_groups: [],
68
+ allowance_metrics: [],
69
+ rollout: null,
70
+ depends_on: [],
71
+ provisioning: {
72
+ enable: ["entitlement"],
73
+ disable: ["entitlement"],
74
+ },
75
+ },
76
+ };
77
+
78
+ export function getModuleDefinition(key: string | null | undefined): IPlatformModuleDefinition | null {
79
+ if (!key || typeof key !== "string") return null;
80
+ if (!Object.prototype.hasOwnProperty.call(PLATFORM_MODULE_CATALOG, key)) return null;
81
+ return PLATFORM_MODULE_CATALOG[key];
82
+ }
83
+
84
+ /** Definições em ordem estável (ordem de declaração). */
85
+ export function listModuleDefinitions(): IPlatformModuleDefinition[] {
86
+ const out: IPlatformModuleDefinition[] = [];
87
+ for (const key in PLATFORM_MODULE_CATALOG) {
88
+ if (Object.prototype.hasOwnProperty.call(PLATFORM_MODULE_CATALOG, key)) {
89
+ out.push(PLATFORM_MODULE_CATALOG[key]);
90
+ }
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /** Chaves do catálogo em ordem de declaração. */
96
+ export function listModuleKeys(): string[] {
97
+ const out: string[] = [];
98
+ for (const key in PLATFORM_MODULE_CATALOG) {
99
+ if (Object.prototype.hasOwnProperty.call(PLATFORM_MODULE_CATALOG, key)) out.push(key);
100
+ }
101
+ return out;
102
+ }
103
+
104
+ /** Capabilities default do módulo (mapa novo a cada chamada). */
105
+ export function buildModuleDefaultCapabilities(
106
+ definition: IPlatformModuleDefinition,
107
+ ): Record<string, boolean | number | string> {
108
+ const out: Record<string, boolean | number | string> = {};
109
+ for (const cap in definition.capabilities) {
110
+ if (Object.prototype.hasOwnProperty.call(definition.capabilities, cap)) {
111
+ out[cap] = definition.capabilities[cap].default;
112
+ }
113
+ }
114
+ return out;
115
+ }
116
+
117
+ /** Módulos que tenant novo recebe habilitados. */
118
+ export function listDefaultModulesForNewTenants(): IPlatformModuleDefinition[] {
119
+ return listModuleDefinitions().filter((d) => d.default_for_new_tenants);
120
+ }
121
+
122
+ /** União, sem repetição e em ordem, dos grupos RBAC dos módulos default de tenant novo. */
123
+ export function listDefaultTenantRbacGroups(): string[] {
124
+ const out: string[] = [];
125
+ for (const def of listDefaultModulesForNewTenants()) {
126
+ for (const g of def.rbac_groups) {
127
+ if (out.indexOf(g) === -1) out.push(g);
128
+ }
129
+ }
130
+ return out;
131
+ }