@trismegisto/primitives 3.3.3 → 3.3.5

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 (186) hide show
  1. package/dist/account.d.ts +62 -0
  2. package/dist/account.js +102 -0
  3. package/dist/account.js.map +1 -0
  4. package/dist/address.d.ts +61 -0
  5. package/dist/address.js +119 -0
  6. package/dist/address.js.map +1 -0
  7. package/dist/announcer.d.ts +48 -0
  8. package/dist/announcer.js +130 -0
  9. package/dist/announcer.js.map +1 -0
  10. package/dist/billing.d.ts +171 -0
  11. package/dist/billing.js +184 -0
  12. package/dist/billing.js.map +1 -0
  13. package/dist/bottom-sheet.d.ts +64 -0
  14. package/dist/bottom-sheet.js +91 -0
  15. package/dist/bottom-sheet.js.map +1 -0
  16. package/dist/color-field.d.ts +18 -0
  17. package/dist/color-field.js +32 -0
  18. package/dist/color-field.js.map +1 -0
  19. package/dist/commerce.d.ts +268 -0
  20. package/dist/commerce.js +259 -0
  21. package/dist/commerce.js.map +1 -0
  22. package/dist/consent.d.ts +25 -0
  23. package/dist/consent.js +29 -0
  24. package/dist/consent.js.map +1 -0
  25. package/dist/data-grid-column-groups.d.ts +23 -0
  26. package/dist/data-grid-column-groups.js +32 -0
  27. package/dist/data-grid-column-groups.js.map +1 -0
  28. package/dist/data-grid-edit.d.ts +105 -0
  29. package/dist/data-grid-edit.js +236 -0
  30. package/dist/data-grid-edit.js.map +1 -0
  31. package/dist/data-grid-tree.d.ts +43 -0
  32. package/dist/data-grid-tree.js +75 -0
  33. package/dist/data-grid-tree.js.map +1 -0
  34. package/dist/data-grid.d.ts +6 -0
  35. package/dist/data-grid.js +3 -0
  36. package/dist/data-grid.js.map +1 -1
  37. package/dist/date-time.d.ts +90 -0
  38. package/dist/date-time.js +216 -0
  39. package/dist/date-time.js.map +1 -0
  40. package/dist/dev-tools.d.ts +78 -0
  41. package/dist/dev-tools.js +176 -0
  42. package/dist/dev-tools.js.map +1 -0
  43. package/dist/event-calendar-edit.d.ts +46 -0
  44. package/dist/event-calendar-edit.js +96 -0
  45. package/dist/event-calendar-edit.js.map +1 -0
  46. package/dist/event-calendar.d.ts +17 -0
  47. package/dist/event-calendar.js.map +1 -1
  48. package/dist/file-browser.d.ts +57 -0
  49. package/dist/file-browser.js +142 -0
  50. package/dist/file-browser.js.map +1 -0
  51. package/dist/file-manager.d.ts +124 -0
  52. package/dist/file-manager.js +124 -0
  53. package/dist/file-manager.js.map +1 -0
  54. package/dist/finance.d.ts +120 -0
  55. package/dist/finance.js +139 -0
  56. package/dist/finance.js.map +1 -0
  57. package/dist/focus.d.ts +11 -0
  58. package/dist/focus.js +82 -0
  59. package/dist/focus.js.map +1 -1
  60. package/dist/form-errors.d.ts +35 -0
  61. package/dist/form-errors.js +28 -0
  62. package/dist/form-errors.js.map +1 -0
  63. package/dist/gallery.d.ts +37 -0
  64. package/dist/gallery.js +45 -0
  65. package/dist/gallery.js.map +1 -0
  66. package/dist/icalendar.d.ts +50 -0
  67. package/dist/icalendar.js +213 -0
  68. package/dist/icalendar.js.map +1 -0
  69. package/dist/identity-document.d.ts +44 -0
  70. package/dist/identity-document.js +191 -0
  71. package/dist/identity-document.js.map +1 -0
  72. package/dist/in-page-focus.d.ts +27 -0
  73. package/dist/in-page-focus.js +93 -0
  74. package/dist/in-page-focus.js.map +1 -0
  75. package/dist/index.d.ts +49 -0
  76. package/dist/index.js +57 -0
  77. package/dist/index.js.map +1 -1
  78. package/dist/integrations.d.ts +218 -0
  79. package/dist/integrations.js +281 -0
  80. package/dist/integrations.js.map +1 -0
  81. package/dist/json-tree.d.ts +74 -0
  82. package/dist/json-tree.js +213 -0
  83. package/dist/json-tree.js.map +1 -0
  84. package/dist/kanban.d.ts +20 -0
  85. package/dist/kanban.js +26 -0
  86. package/dist/kanban.js.map +1 -1
  87. package/dist/log-view.d.ts +53 -0
  88. package/dist/log-view.js +116 -0
  89. package/dist/log-view.js.map +1 -0
  90. package/dist/mentions.d.ts +58 -0
  91. package/dist/mentions.js +88 -0
  92. package/dist/mentions.js.map +1 -0
  93. package/dist/messages-calendar-files.d.ts +363 -0
  94. package/dist/messages-calendar-files.js +2 -0
  95. package/dist/messages-calendar-files.js.map +1 -0
  96. package/dist/messages-en.js +8 -0
  97. package/dist/messages-en.js.map +1 -1
  98. package/dist/messages-es.js +8 -0
  99. package/dist/messages-es.js.map +1 -1
  100. package/dist/messages.d.ts +11 -0
  101. package/dist/messages.js +8 -0
  102. package/dist/messages.js.map +1 -1
  103. package/dist/monitoring-format.d.ts +32 -0
  104. package/dist/monitoring-format.js +44 -0
  105. package/dist/monitoring-format.js.map +1 -0
  106. package/dist/monitoring.d.ts +182 -0
  107. package/dist/monitoring.js +324 -0
  108. package/dist/monitoring.js.map +1 -0
  109. package/dist/number-format.d.ts +164 -0
  110. package/dist/number-format.js +345 -0
  111. package/dist/number-format.js.map +1 -0
  112. package/dist/observability-format.d.ts +20 -0
  113. package/dist/observability-format.js +43 -0
  114. package/dist/observability-format.js.map +1 -0
  115. package/dist/payments.d.ts +188 -0
  116. package/dist/payments.js +372 -0
  117. package/dist/payments.js.map +1 -0
  118. package/dist/pdf-view.d.ts +34 -0
  119. package/dist/pdf-view.js +63 -0
  120. package/dist/pdf-view.js.map +1 -0
  121. package/dist/people.d.ts +236 -0
  122. package/dist/people.js +348 -0
  123. package/dist/people.js.map +1 -0
  124. package/dist/popover.d.ts +2 -0
  125. package/dist/popover.js.map +1 -1
  126. package/dist/progress-circle.d.ts +16 -0
  127. package/dist/progress-circle.js +20 -0
  128. package/dist/progress-circle.js.map +1 -0
  129. package/dist/project-planning.d.ts +71 -0
  130. package/dist/project-planning.js +134 -0
  131. package/dist/project-planning.js.map +1 -0
  132. package/dist/rating.d.ts +30 -0
  133. package/dist/rating.js +76 -0
  134. package/dist/rating.js.map +1 -0
  135. package/dist/recurrence.d.ts +99 -0
  136. package/dist/recurrence.js +270 -0
  137. package/dist/recurrence.js.map +1 -0
  138. package/dist/reports.d.ts +83 -0
  139. package/dist/reports.js +100 -0
  140. package/dist/reports.js.map +1 -0
  141. package/dist/save-status.d.ts +32 -0
  142. package/dist/save-status.js +24 -0
  143. package/dist/save-status.js.map +1 -0
  144. package/dist/scheduling.d.ts +178 -0
  145. package/dist/scheduling.js +240 -0
  146. package/dist/scheduling.js.map +1 -0
  147. package/dist/scrollspy.d.ts +43 -0
  148. package/dist/scrollspy.js +106 -0
  149. package/dist/scrollspy.js.map +1 -0
  150. package/dist/service-graph.d.ts +74 -0
  151. package/dist/service-graph.js +157 -0
  152. package/dist/service-graph.js.map +1 -0
  153. package/dist/sidebar.d.ts +12 -3
  154. package/dist/sidebar.js +26 -5
  155. package/dist/sidebar.js.map +1 -1
  156. package/dist/storefront.d.ts +45 -0
  157. package/dist/storefront.js +72 -0
  158. package/dist/storefront.js.map +1 -0
  159. package/dist/tag-input.d.ts +53 -0
  160. package/dist/tag-input.js +105 -0
  161. package/dist/tag-input.js.map +1 -0
  162. package/dist/tasks.d.ts +266 -0
  163. package/dist/tasks.js +340 -0
  164. package/dist/tasks.js.map +1 -0
  165. package/dist/tour.d.ts +63 -0
  166. package/dist/tour.js +66 -0
  167. package/dist/tour.js.map +1 -0
  168. package/dist/trace.d.ts +64 -0
  169. package/dist/trace.js +108 -0
  170. package/dist/trace.js.map +1 -0
  171. package/dist/tree-select.d.ts +65 -0
  172. package/dist/tree-select.js +150 -0
  173. package/dist/tree-select.js.map +1 -0
  174. package/dist/unsaved-changes.d.ts +43 -0
  175. package/dist/unsaved-changes.js +64 -0
  176. package/dist/unsaved-changes.js.map +1 -0
  177. package/dist/vehicle-plate.d.ts +44 -0
  178. package/dist/vehicle-plate.js +106 -0
  179. package/dist/vehicle-plate.js.map +1 -0
  180. package/dist/workflow.d.ts +268 -0
  181. package/dist/workflow.js +392 -0
  182. package/dist/workflow.js.map +1 -0
  183. package/dist/workspace.d.ts +29 -0
  184. package/dist/workspace.js +61 -0
  185. package/dist/workspace.js.map +1 -1
  186. package/package.json +3 -3
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Padrões de status e workflow sem framework: situações e transições de um fluxo, escalas de nível
3
+ * (prioridade, severidade, criticidade, urgência, impacto, probabilidade e risco), prazos e SLA,
4
+ * aprovação em várias etapas, execução e o desenho (camadas) de um fluxo. Tudo puro: nada aqui toca em
5
+ * DOM, guarda estado nem muta o que recebe — os componentes do `@trismegisto/angular` (e um porte futuro
6
+ * para outro framework) só ligam estas regras à tela.
7
+ */
8
+ /** Tom semântico de um status ou nível (o mesmo conjunto de cores do `hm-tag`). */
9
+ export type WorkflowTone = 'primary' | 'info' | 'success' | 'warning' | 'danger' | 'neutral';
10
+ /** Em que fase do fluxo o status está: decide o tom padrão e o que conta como "terminado". */
11
+ export type WorkflowStatusCategory = 'todo' | 'active' | 'done' | 'canceled';
12
+ /** Uma situação do fluxo ("Aberto", "Em análise", "Concluído"). */
13
+ export interface WorkflowStatus {
14
+ readonly id: string;
15
+ readonly label: string;
16
+ /** Sem tom, ele sai da categoria (`todo` neutro, `active` informação, `done` sucesso, `canceled` neutro). */
17
+ readonly tone?: WorkflowTone;
18
+ readonly category?: WorkflowStatusCategory;
19
+ /** Explicação curta (aparece no editor e no seletor). */
20
+ readonly description?: string;
21
+ }
22
+ /** Quando a transição pede motivo: nunca, opcional ou obrigatório. */
23
+ export type WorkflowReasonMode = 'none' | 'optional' | 'required';
24
+ /** Uma passagem permitida entre dois status. `from: '*'` vale a partir de qualquer status. */
25
+ export interface WorkflowTransition {
26
+ readonly from: string;
27
+ readonly to: string;
28
+ /** Nome da ação ("Aprovar", "Reabrir"); sem ele, o nome do status de destino. */
29
+ readonly label?: string;
30
+ /** Pede confirmação antes de mudar. */
31
+ readonly confirm?: boolean;
32
+ readonly reason?: WorkflowReasonMode;
33
+ /** Ação destrutiva (cancelar, rejeitar): o botão de confirmar fica em perigo. */
34
+ readonly danger?: boolean;
35
+ }
36
+ /** Um fluxo: os status, as transições e o status inicial. Sem `transitions`, toda passagem é livre. */
37
+ export interface WorkflowDefinition {
38
+ readonly statuses: readonly WorkflowStatus[];
39
+ readonly transitions?: readonly WorkflowTransition[];
40
+ /** Id do status inicial; sem ele, o primeiro da lista. */
41
+ readonly initial?: string;
42
+ }
43
+ export declare function findWorkflowStatus(statuses: readonly WorkflowStatus[], id: string | null | undefined): WorkflowStatus | undefined;
44
+ /** O tom do status: o declarado ou o da categoria. */
45
+ export declare function workflowStatusTone(status: WorkflowStatus | null | undefined): WorkflowTone;
46
+ /** O status encerra o fluxo (`done` ou `canceled`)? */
47
+ export declare function isWorkflowStatusFinal(status: WorkflowStatus | null | undefined): boolean;
48
+ /**
49
+ * Para onde dá para ir a partir de `current`, na ordem dos status do fluxo. Sem `transitions`, todo outro
50
+ * status é destino (com uma transição implícita, sem confirmação). Destino repetido (uma regra exata e uma
51
+ * `'*'`) fica com a regra exata.
52
+ */
53
+ export declare function availableWorkflowTransitions(definition: WorkflowDefinition, current: string | null | undefined): WorkflowTransition[];
54
+ export declare function findWorkflowTransition(definition: WorkflowDefinition, from: string | null | undefined, to: string): WorkflowTransition | undefined;
55
+ export declare function canWorkflowTransition(definition: WorkflowDefinition, from: string | null | undefined, to: string): boolean;
56
+ /** A transição abre um diálogo (confirmação ou motivo)? */
57
+ export declare function workflowTransitionNeedsDialog(transition: WorkflowTransition): boolean;
58
+ /** O motivo informado basta para a transição? (Obrigatório = algum texto além de espaços.) */
59
+ export declare function isWorkflowReasonValid(transition: WorkflowTransition, reason: string): boolean;
60
+ /** Existe a transição exata `from → to`? */
61
+ export declare function hasWorkflowTransition(definition: WorkflowDefinition, from: string, to: string): boolean;
62
+ /**
63
+ * Liga ou desliga a transição exata `from → to`. Num fluxo livre (sem `transitions`), a primeira edição
64
+ * materializa todas as passagens implícitas antes de mudar a pedida — o fluxo continua igual, menos ela.
65
+ */
66
+ export declare function toggleWorkflowTransition(definition: WorkflowDefinition, from: string, to: string): WorkflowDefinition;
67
+ /** Acrescenta (ou troca, se o id já existe) um status. */
68
+ export declare function upsertWorkflowStatus(definition: WorkflowDefinition, status: WorkflowStatus): WorkflowDefinition;
69
+ /** Tira um status e todas as transições que passam por ele. Se era o inicial, o inicial passa ao primeiro. */
70
+ export declare function removeWorkflowStatus(definition: WorkflowDefinition, id: string): WorkflowDefinition;
71
+ /** Move o status `id` para a posição `index` (a ordem é a das colunas e do seletor). */
72
+ export declare function moveWorkflowStatus(definition: WorkflowDefinition, id: string, index: number): WorkflowDefinition;
73
+ /** Um id livre a partir de um nome ("Em análise" → "em-analise", "em-analise-2"...). */
74
+ export declare function workflowStatusId(label: string, taken: readonly string[]): string;
75
+ /** Problema de um fluxo que o editor aponta. */
76
+ export interface WorkflowIssue {
77
+ /** `unreachable`: não se chega a ele a partir do inicial; `deadEnd`: não é final e não tem saída; `emptyLabel`: sem nome. */
78
+ readonly kind: 'unreachable' | 'deadEnd' | 'emptyLabel';
79
+ readonly statusId: string;
80
+ }
81
+ export declare function workflowIssues(definition: WorkflowDefinition): WorkflowIssue[];
82
+ /** Nó do diagrama: coluna = passos desde o inicial; linha = ordem dentro da coluna. */
83
+ export interface WorkflowLayoutNode {
84
+ readonly id: string;
85
+ readonly column: number;
86
+ readonly row: number;
87
+ }
88
+ /** Aresta do diagrama. `back` = volta para uma coluna anterior (ou a mesma): desenhada por baixo, curva. */
89
+ export interface WorkflowLayoutEdge {
90
+ readonly from: string;
91
+ readonly to: string;
92
+ readonly back: boolean;
93
+ readonly transition: WorkflowTransition;
94
+ }
95
+ export interface WorkflowLayout {
96
+ readonly nodes: readonly WorkflowLayoutNode[];
97
+ readonly edges: readonly WorkflowLayoutEdge[];
98
+ readonly columns: number;
99
+ readonly rows: number;
100
+ }
101
+ /**
102
+ * Camadas do diagrama de um fluxo: cada status vai para a coluna da sua distância ao inicial (os
103
+ * inalcançáveis numa coluna extra, no fim), na ordem em que aparecem em `statuses`. As transições `'*'`
104
+ * viram uma aresta por origem (exceto o próprio destino).
105
+ */
106
+ export declare function layoutWorkflow(definition: WorkflowDefinition): WorkflowLayout;
107
+ /** Escalas prontas. Os nomes vêm do catálogo de mensagens (`workflow.levels.<tipo>`). */
108
+ export type LevelScaleKind = 'priority' | 'severity' | 'criticality' | 'urgency' | 'impact' | 'likelihood' | 'risk';
109
+ /** Um degrau da escala. `rank` começa em 1 (o mais baixo) e decide quantas barras a marca acende. */
110
+ export interface LevelOption {
111
+ readonly value: string;
112
+ readonly label: string;
113
+ readonly tone: WorkflowTone;
114
+ readonly rank: number;
115
+ }
116
+ export interface LevelScale {
117
+ /** Nome da escala ("Prioridade"): rótulo do seletor e prefixo do nome acessível do selo. */
118
+ readonly label: string;
119
+ /** Do mais baixo ao mais alto. */
120
+ readonly levels: readonly LevelOption[];
121
+ }
122
+ /** Nomes de uma escala pronta no catálogo: o nome da escala e o de cada valor. */
123
+ export interface LevelScaleMessages {
124
+ readonly label: string;
125
+ readonly values: Readonly<Record<string, string>>;
126
+ }
127
+ /** Valores e tons de cada escala pronta, do mais baixo ao mais alto. */
128
+ export declare const LEVEL_SCALE_PRESETS: Readonly<Record<LevelScaleKind, readonly (readonly [string, WorkflowTone])[]>>;
129
+ /** Monta uma escala pronta com os nomes do catálogo ativo. */
130
+ export declare function levelScalePreset(kind: LevelScaleKind, messages: LevelScaleMessages): LevelScale;
131
+ export declare function findScaleLevel(scale: LevelScale, value: string | null | undefined): LevelOption | undefined;
132
+ /** Pontuação de risco: probabilidade × impacto (degraus a partir de 1). */
133
+ export declare function riskScore(likelihood: number, impact: number): number;
134
+ /**
135
+ * Faixa de risco (`low`/`medium`/`high`/`critical`, os valores da escala `risk`) de uma pontuação. Os
136
+ * limites padrão são os da matriz 5×5 mais comum: até 4 baixo, até 9 médio, até 16 alto, acima crítico.
137
+ */
138
+ export declare function riskLevel(score: number, thresholds?: readonly [number, number, number]): string;
139
+ export type WorkflowDateValue = Date | string | number | null | undefined;
140
+ /** Converte para milissegundos; `null` se vazio ou inválido. */
141
+ export declare function workflowTime(value: WorkflowDateValue): number | null;
142
+ /** Situação de um prazo. `met`/`late` só quando há data de conclusão. */
143
+ export type DeadlineState = 'onTrack' | 'dueSoon' | 'overdue' | 'met' | 'late';
144
+ export interface DeadlineStatus {
145
+ readonly state: DeadlineState;
146
+ /** Prazo − agora (ou − conclusão); negativo = vencido. */
147
+ readonly remainingMs: number;
148
+ }
149
+ /**
150
+ * Situação do prazo `due` agora. `soonMs` (padrão 24 h) é a janela de "vence logo". Com `completedAt`,
151
+ * a pergunta vira "cumpriu?" (`met`/`late`).
152
+ */
153
+ export declare function deadlineStatus(due: WorkflowDateValue, now: WorkflowDateValue, options?: {
154
+ readonly soonMs?: number;
155
+ readonly completedAt?: WorkflowDateValue;
156
+ }): DeadlineStatus | null;
157
+ export type SlaState = 'onTrack' | 'atRisk' | 'breached' | 'paused' | 'met' | 'missed';
158
+ export interface SlaStatus {
159
+ readonly state: SlaState;
160
+ /** Fração do tempo do SLA já consumida (pode passar de 1). */
161
+ readonly ratio: number;
162
+ readonly elapsedMs: number;
163
+ /** Tempo restante; negativo = estourado. */
164
+ readonly remainingMs: number;
165
+ readonly targetMs: number;
166
+ }
167
+ export interface SlaInput {
168
+ readonly start: WorkflowDateValue;
169
+ readonly due: WorkflowDateValue;
170
+ readonly now?: WorkflowDateValue;
171
+ readonly completedAt?: WorkflowDateValue;
172
+ /** Tempo já parado (aguardando cliente, fora do expediente) — não conta. */
173
+ readonly pausedMs?: number;
174
+ /** O relógio está parado agora. */
175
+ readonly paused?: boolean;
176
+ /** A partir de que fração consumida vira "em risco". Padrão 0,75. */
177
+ readonly atRiskRatio?: number;
178
+ }
179
+ /** Consumo de um SLA entre `start` e `due` (o alvo), descontando as pausas. */
180
+ export declare function slaStatus(input: SlaInput): SlaStatus | null;
181
+ export interface CountdownParts {
182
+ readonly days: number;
183
+ readonly hours: number;
184
+ readonly minutes: number;
185
+ readonly seconds: number;
186
+ }
187
+ /** Quebra uma duração (valor absoluto) em dias, horas, minutos e segundos. */
188
+ export declare function countdownParts(ms: number): CountdownParts;
189
+ /**
190
+ * Texto de uma duração para contagem regressiva e prazos ("2 d 4 h", "2 days 4 hours"), com as maiores
191
+ * `maxUnits` unidades não nulas e as unidades do `Intl` no idioma. Menos de um segundo = "0 s". Sempre
192
+ * o valor absoluto: o sentido ("faltam", "atrasado há") é do texto em volta.
193
+ */
194
+ export declare function formatCountdown(ms: number, locale: string, options?: {
195
+ readonly maxUnits?: number;
196
+ readonly unitDisplay?: 'narrow' | 'short' | 'long';
197
+ readonly seconds?: boolean;
198
+ }): string;
199
+ export type ApprovalDecision = 'pending' | 'approved' | 'rejected' | 'skipped';
200
+ /** Situação geral de um pedido de aprovação. */
201
+ export type ApprovalState = 'pending' | 'approved' | 'rejected';
202
+ /** Quem aprova: todos (em sequência), qualquer um ou um mínimo de aprovações. */
203
+ export type ApprovalRule = 'all' | 'any' | {
204
+ readonly min: number;
205
+ };
206
+ export interface ApprovalStepDescriptor {
207
+ readonly id: string;
208
+ readonly decision: ApprovalDecision;
209
+ }
210
+ export interface ApprovalSummary {
211
+ readonly state: ApprovalState;
212
+ readonly approved: number;
213
+ readonly rejected: number;
214
+ readonly pending: number;
215
+ /** Etapas que contam (as `skipped` ficam de fora). */
216
+ readonly total: number;
217
+ /** Aprovações necessárias pela regra. */
218
+ readonly required: number;
219
+ /** A etapa que decide agora (a primeira pendente), enquanto o pedido está pendente. */
220
+ readonly currentId: string | null;
221
+ }
222
+ /** Resume as decisões das etapas segundo a regra. */
223
+ export declare function approvalSummary(steps: readonly ApprovalStepDescriptor[], rule?: ApprovalRule): ApprovalSummary;
224
+ export type ExecutionState = 'queued' | 'running' | 'paused' | 'succeeded' | 'failed' | 'canceled';
225
+ export declare function executionTone(state: ExecutionState): WorkflowTone;
226
+ /** A execução terminou (com sucesso, falha ou cancelada)? */
227
+ export declare function isExecutionFinal(state: ExecutionState): boolean;
228
+ /** Duração de uma execução: do início ao fim (ou até agora, enquanto corre). `null` sem início. */
229
+ export declare function executionDuration(startedAt: WorkflowDateValue, finishedAt: WorkflowDateValue, now?: WorkflowDateValue): number | null;
230
+ /** Quem pode receber um item: uma pessoa, uma equipe ou uma fila. */
231
+ export interface WorkflowAssignee {
232
+ readonly id: string;
233
+ readonly name: string;
234
+ readonly imageUrl?: string | null;
235
+ /** Padrão `person`. Fila e equipe aparecem com ícone em vez de rosto. */
236
+ readonly kind?: 'person' | 'team' | 'queue';
237
+ /** Segunda linha (e-mail, cargo, tamanho da fila). */
238
+ readonly detail?: string;
239
+ }
240
+ /** Valor de "sem responsável" nos seletores (string vazia). */
241
+ export declare const WORKFLOW_UNASSIGNED = "";
242
+ /** Próximo nível de escalonamento (`levels` em ordem); `null` se já está no último. */
243
+ export declare function nextEscalationLevel<T>(levels: readonly T[], current: number): {
244
+ readonly index: number;
245
+ readonly level: T;
246
+ } | null;
247
+ /** Tipo de um registro do histórico: decide a frase ("mudou o status", "alterou {campo}"...). */
248
+ export type ChangeHistoryKind = 'created' | 'status' | 'field' | 'assignment' | 'comment';
249
+ /** Um registro do histórico de um item (status, campo, responsável, comentário). */
250
+ export interface ChangeHistoryEntry {
251
+ readonly id?: string;
252
+ readonly at: WorkflowDateValue;
253
+ readonly kind: ChangeHistoryKind;
254
+ /** Quem fez; sem autor, "Sistema". */
255
+ readonly actor?: {
256
+ readonly name: string;
257
+ readonly imageUrl?: string | null;
258
+ } | null;
259
+ /** Nome do campo (`field`). */
260
+ readonly field?: string;
261
+ /** Valores antes e depois. Em `status`, ids procurados nos status do fluxo. */
262
+ readonly from?: string | null;
263
+ readonly to?: string | null;
264
+ /** Texto livre: o comentário ou o motivo da mudança. */
265
+ readonly note?: string;
266
+ }
267
+ /** Registros do mais recente para o mais antigo (os sem data por último, na ordem recebida). */
268
+ export declare function sortChangeHistory<T extends ChangeHistoryEntry>(entries: readonly T[], order?: 'newest' | 'oldest'): T[];
@@ -0,0 +1,392 @@
1
+ /**
2
+ * Padrões de status e workflow sem framework: situações e transições de um fluxo, escalas de nível
3
+ * (prioridade, severidade, criticidade, urgência, impacto, probabilidade e risco), prazos e SLA,
4
+ * aprovação em várias etapas, execução e o desenho (camadas) de um fluxo. Tudo puro: nada aqui toca em
5
+ * DOM, guarda estado nem muta o que recebe — os componentes do `@trismegisto/angular` (e um porte futuro
6
+ * para outro framework) só ligam estas regras à tela.
7
+ */
8
+ const CATEGORY_TONE = {
9
+ todo: 'neutral',
10
+ active: 'info',
11
+ done: 'success',
12
+ canceled: 'neutral',
13
+ };
14
+ export function findWorkflowStatus(statuses, id) {
15
+ return id === null || id === undefined ? undefined : statuses.find((status) => status.id === id);
16
+ }
17
+ /** O tom do status: o declarado ou o da categoria. */
18
+ export function workflowStatusTone(status) {
19
+ if (!status)
20
+ return 'neutral';
21
+ return status.tone ?? CATEGORY_TONE[status.category ?? 'todo'];
22
+ }
23
+ /** O status encerra o fluxo (`done` ou `canceled`)? */
24
+ export function isWorkflowStatusFinal(status) {
25
+ return status?.category === 'done' || status?.category === 'canceled';
26
+ }
27
+ /**
28
+ * Para onde dá para ir a partir de `current`, na ordem dos status do fluxo. Sem `transitions`, todo outro
29
+ * status é destino (com uma transição implícita, sem confirmação). Destino repetido (uma regra exata e uma
30
+ * `'*'`) fica com a regra exata.
31
+ */
32
+ export function availableWorkflowTransitions(definition, current) {
33
+ const from = current ?? '';
34
+ const known = new Set(definition.statuses.map((status) => status.id));
35
+ if (!definition.transitions) {
36
+ return definition.statuses.filter((status) => status.id !== from).map((status) => ({ from, to: status.id }));
37
+ }
38
+ const byTarget = new Map();
39
+ for (const transition of definition.transitions) {
40
+ if (transition.to === from || !known.has(transition.to))
41
+ continue;
42
+ if (transition.from !== from && transition.from !== '*')
43
+ continue;
44
+ const previous = byTarget.get(transition.to);
45
+ if (!previous || (previous.from === '*' && transition.from === from))
46
+ byTarget.set(transition.to, transition);
47
+ }
48
+ return definition.statuses.filter((status) => byTarget.has(status.id)).map((status) => byTarget.get(status.id));
49
+ }
50
+ export function findWorkflowTransition(definition, from, to) {
51
+ return availableWorkflowTransitions(definition, from).find((transition) => transition.to === to);
52
+ }
53
+ export function canWorkflowTransition(definition, from, to) {
54
+ return findWorkflowTransition(definition, from, to) !== undefined;
55
+ }
56
+ /** A transição abre um diálogo (confirmação ou motivo)? */
57
+ export function workflowTransitionNeedsDialog(transition) {
58
+ return !!transition.confirm || (transition.reason ?? 'none') !== 'none';
59
+ }
60
+ /** O motivo informado basta para a transição? (Obrigatório = algum texto além de espaços.) */
61
+ export function isWorkflowReasonValid(transition, reason) {
62
+ return (transition.reason ?? 'none') !== 'required' || reason.trim().length > 0;
63
+ }
64
+ // ---------------------------------------------------------------------------------------------------------
65
+ // Edição de um fluxo (hm-workflow-editor). Cada função devolve um fluxo novo.
66
+ /** Existe a transição exata `from → to`? */
67
+ export function hasWorkflowTransition(definition, from, to) {
68
+ return (definition.transitions ?? []).some((transition) => transition.from === from && transition.to === to);
69
+ }
70
+ /**
71
+ * Liga ou desliga a transição exata `from → to`. Num fluxo livre (sem `transitions`), a primeira edição
72
+ * materializa todas as passagens implícitas antes de mudar a pedida — o fluxo continua igual, menos ela.
73
+ */
74
+ export function toggleWorkflowTransition(definition, from, to) {
75
+ if (from === to)
76
+ return definition;
77
+ const transitions = definition.transitions ??
78
+ definition.statuses.flatMap((a) => definition.statuses.filter((b) => b.id !== a.id).map((b) => ({ from: a.id, to: b.id })));
79
+ const exists = transitions.some((t) => t.from === from && t.to === to);
80
+ return {
81
+ ...definition,
82
+ transitions: exists ? transitions.filter((t) => !(t.from === from && t.to === to)) : [...transitions, { from, to }],
83
+ };
84
+ }
85
+ /** Acrescenta (ou troca, se o id já existe) um status. */
86
+ export function upsertWorkflowStatus(definition, status) {
87
+ const exists = definition.statuses.some((s) => s.id === status.id);
88
+ return {
89
+ ...definition,
90
+ statuses: exists ? definition.statuses.map((s) => (s.id === status.id ? status : s)) : [...definition.statuses, status],
91
+ };
92
+ }
93
+ /** Tira um status e todas as transições que passam por ele. Se era o inicial, o inicial passa ao primeiro. */
94
+ export function removeWorkflowStatus(definition, id) {
95
+ const statuses = definition.statuses.filter((s) => s.id !== id);
96
+ return {
97
+ ...definition,
98
+ statuses,
99
+ transitions: definition.transitions?.filter((t) => t.from !== id && t.to !== id),
100
+ initial: definition.initial === id ? statuses[0]?.id : definition.initial,
101
+ };
102
+ }
103
+ /** Move o status `id` para a posição `index` (a ordem é a das colunas e do seletor). */
104
+ export function moveWorkflowStatus(definition, id, index) {
105
+ const from = definition.statuses.findIndex((s) => s.id === id);
106
+ if (from < 0)
107
+ return definition;
108
+ const statuses = [...definition.statuses];
109
+ const [moved] = statuses.splice(from, 1);
110
+ statuses.splice(Math.max(0, Math.min(index, statuses.length)), 0, moved);
111
+ return { ...definition, statuses };
112
+ }
113
+ /** Um id livre a partir de um nome ("Em análise" → "em-analise", "em-analise-2"...). */
114
+ export function workflowStatusId(label, taken) {
115
+ const base = label
116
+ .normalize('NFD')
117
+ .replace(/\p{Diacritic}/gu, '')
118
+ .toLowerCase()
119
+ .replace(/[^a-z0-9]+/g, '-')
120
+ .replace(/^-+|-+$/g, '') || 'status';
121
+ let id = base;
122
+ for (let n = 2; taken.includes(id); n++)
123
+ id = `${base}-${n}`;
124
+ return id;
125
+ }
126
+ function initialOf(definition) {
127
+ return findWorkflowStatus(definition.statuses, definition.initial)?.id ?? definition.statuses[0]?.id;
128
+ }
129
+ /** Profundidade (passos a partir do inicial) de cada status alcançável. */
130
+ function workflowDepths(definition) {
131
+ const depth = new Map();
132
+ const start = initialOf(definition);
133
+ if (start === undefined)
134
+ return depth;
135
+ depth.set(start, 0);
136
+ const queue = [start];
137
+ while (queue.length) {
138
+ const id = queue.shift();
139
+ for (const transition of availableWorkflowTransitions(definition, id)) {
140
+ if (depth.has(transition.to))
141
+ continue;
142
+ depth.set(transition.to, depth.get(id) + 1);
143
+ queue.push(transition.to);
144
+ }
145
+ }
146
+ return depth;
147
+ }
148
+ export function workflowIssues(definition) {
149
+ const depth = workflowDepths(definition);
150
+ const issues = [];
151
+ for (const status of definition.statuses) {
152
+ if (!status.label.trim())
153
+ issues.push({ kind: 'emptyLabel', statusId: status.id });
154
+ if (!depth.has(status.id))
155
+ issues.push({ kind: 'unreachable', statusId: status.id });
156
+ if (!isWorkflowStatusFinal(status) && availableWorkflowTransitions(definition, status.id).length === 0) {
157
+ issues.push({ kind: 'deadEnd', statusId: status.id });
158
+ }
159
+ }
160
+ return issues;
161
+ }
162
+ /**
163
+ * Camadas do diagrama de um fluxo: cada status vai para a coluna da sua distância ao inicial (os
164
+ * inalcançáveis numa coluna extra, no fim), na ordem em que aparecem em `statuses`. As transições `'*'`
165
+ * viram uma aresta por origem (exceto o próprio destino).
166
+ */
167
+ export function layoutWorkflow(definition) {
168
+ const depth = workflowDepths(definition);
169
+ const reachableColumns = depth.size ? Math.max(...depth.values()) + 1 : 0;
170
+ const rowsPerColumn = [];
171
+ const nodes = definition.statuses.map((status) => {
172
+ const column = depth.get(status.id) ?? reachableColumns;
173
+ const row = rowsPerColumn[column] ?? 0;
174
+ rowsPerColumn[column] = row + 1;
175
+ return { id: status.id, column, row };
176
+ });
177
+ const columnOf = new Map(nodes.map((node) => [node.id, node.column]));
178
+ const edges = [];
179
+ for (const status of definition.statuses) {
180
+ for (const transition of availableWorkflowTransitions(definition, status.id)) {
181
+ edges.push({
182
+ from: status.id,
183
+ to: transition.to,
184
+ back: columnOf.get(transition.to) <= columnOf.get(status.id),
185
+ transition,
186
+ });
187
+ }
188
+ }
189
+ return {
190
+ nodes,
191
+ edges,
192
+ columns: rowsPerColumn.length,
193
+ rows: rowsPerColumn.length ? Math.max(...rowsPerColumn.map((n) => n ?? 0)) : 0,
194
+ };
195
+ }
196
+ /** Valores e tons de cada escala pronta, do mais baixo ao mais alto. */
197
+ export const LEVEL_SCALE_PRESETS = {
198
+ priority: [['low', 'neutral'], ['medium', 'info'], ['high', 'warning'], ['urgent', 'danger']],
199
+ severity: [['minor', 'neutral'], ['moderate', 'info'], ['major', 'warning'], ['critical', 'danger']],
200
+ criticality: [['low', 'neutral'], ['medium', 'info'], ['high', 'warning'], ['critical', 'danger']],
201
+ urgency: [['low', 'neutral'], ['medium', 'info'], ['high', 'warning'], ['immediate', 'danger']],
202
+ impact: [['negligible', 'neutral'], ['minor', 'info'], ['moderate', 'warning'], ['major', 'warning'], ['severe', 'danger']],
203
+ likelihood: [['rare', 'neutral'], ['unlikely', 'info'], ['possible', 'warning'], ['likely', 'warning'], ['almost-certain', 'danger']],
204
+ risk: [['low', 'success'], ['medium', 'info'], ['high', 'warning'], ['critical', 'danger']],
205
+ };
206
+ /** Monta uma escala pronta com os nomes do catálogo ativo. */
207
+ export function levelScalePreset(kind, messages) {
208
+ return {
209
+ label: messages.label,
210
+ levels: LEVEL_SCALE_PRESETS[kind].map(([value, tone], index) => ({
211
+ value,
212
+ tone,
213
+ rank: index + 1,
214
+ label: messages.values[value] ?? value,
215
+ })),
216
+ };
217
+ }
218
+ export function findScaleLevel(scale, value) {
219
+ return value === null || value === undefined ? undefined : scale.levels.find((level) => level.value === value);
220
+ }
221
+ /** Pontuação de risco: probabilidade × impacto (degraus a partir de 1). */
222
+ export function riskScore(likelihood, impact) {
223
+ return Math.max(0, Math.round(likelihood)) * Math.max(0, Math.round(impact));
224
+ }
225
+ /**
226
+ * Faixa de risco (`low`/`medium`/`high`/`critical`, os valores da escala `risk`) de uma pontuação. Os
227
+ * limites padrão são os da matriz 5×5 mais comum: até 4 baixo, até 9 médio, até 16 alto, acima crítico.
228
+ */
229
+ export function riskLevel(score, thresholds = [4, 9, 16]) {
230
+ if (score <= thresholds[0])
231
+ return 'low';
232
+ if (score <= thresholds[1])
233
+ return 'medium';
234
+ if (score <= thresholds[2])
235
+ return 'high';
236
+ return 'critical';
237
+ }
238
+ const HOUR = 3_600_000;
239
+ /** Converte para milissegundos; `null` se vazio ou inválido. */
240
+ export function workflowTime(value) {
241
+ if (value === null || value === undefined || value === '')
242
+ return null;
243
+ const time = value instanceof Date ? value.getTime() : new Date(value).getTime();
244
+ return Number.isNaN(time) ? null : time;
245
+ }
246
+ /**
247
+ * Situação do prazo `due` agora. `soonMs` (padrão 24 h) é a janela de "vence logo". Com `completedAt`,
248
+ * a pergunta vira "cumpriu?" (`met`/`late`).
249
+ */
250
+ export function deadlineStatus(due, now, options = {}) {
251
+ const dueTime = workflowTime(due);
252
+ const nowTime = workflowTime(now) ?? Date.now();
253
+ if (dueTime === null)
254
+ return null;
255
+ const completed = workflowTime(options.completedAt);
256
+ if (completed !== null) {
257
+ const remainingMs = dueTime - completed;
258
+ return { state: remainingMs >= 0 ? 'met' : 'late', remainingMs };
259
+ }
260
+ const remainingMs = dueTime - nowTime;
261
+ if (remainingMs < 0)
262
+ return { state: 'overdue', remainingMs };
263
+ return { state: remainingMs <= (options.soonMs ?? 24 * HOUR) ? 'dueSoon' : 'onTrack', remainingMs };
264
+ }
265
+ /** Consumo de um SLA entre `start` e `due` (o alvo), descontando as pausas. */
266
+ export function slaStatus(input) {
267
+ const start = workflowTime(input.start);
268
+ const due = workflowTime(input.due);
269
+ if (start === null || due === null || due <= start)
270
+ return null;
271
+ const completed = workflowTime(input.completedAt);
272
+ const now = completed ?? workflowTime(input.now) ?? Date.now();
273
+ const targetMs = due - start;
274
+ const elapsedMs = Math.max(0, now - start - Math.max(0, input.pausedMs ?? 0));
275
+ const ratio = elapsedMs / targetMs;
276
+ const remainingMs = targetMs - elapsedMs;
277
+ let state;
278
+ if (completed !== null)
279
+ state = remainingMs >= 0 ? 'met' : 'missed';
280
+ else if (remainingMs < 0)
281
+ state = 'breached';
282
+ else if (input.paused)
283
+ state = 'paused';
284
+ else
285
+ state = ratio >= (input.atRiskRatio ?? 0.75) ? 'atRisk' : 'onTrack';
286
+ return { state, ratio, elapsedMs, remainingMs, targetMs };
287
+ }
288
+ /** Quebra uma duração (valor absoluto) em dias, horas, minutos e segundos. */
289
+ export function countdownParts(ms) {
290
+ let rest = Math.floor(Math.abs(ms) / 1000);
291
+ const days = Math.floor(rest / 86_400);
292
+ rest -= days * 86_400;
293
+ const hours = Math.floor(rest / 3_600);
294
+ rest -= hours * 3_600;
295
+ const minutes = Math.floor(rest / 60);
296
+ return { days, hours, minutes, seconds: rest - minutes * 60 };
297
+ }
298
+ const unitFormatters = new Map();
299
+ function unitFormatter(locale, unit, display) {
300
+ const key = `${locale}|${unit}|${display}`;
301
+ let formatter = unitFormatters.get(key);
302
+ if (!formatter) {
303
+ formatter = new Intl.NumberFormat(locale, { style: 'unit', unit, unitDisplay: display });
304
+ if (unitFormatters.size > 64)
305
+ unitFormatters.clear();
306
+ unitFormatters.set(key, formatter);
307
+ }
308
+ return formatter;
309
+ }
310
+ /**
311
+ * Texto de uma duração para contagem regressiva e prazos ("2 d 4 h", "2 days 4 hours"), com as maiores
312
+ * `maxUnits` unidades não nulas e as unidades do `Intl` no idioma. Menos de um segundo = "0 s". Sempre
313
+ * o valor absoluto: o sentido ("faltam", "atrasado há") é do texto em volta.
314
+ */
315
+ export function formatCountdown(ms, locale, options = {}) {
316
+ const parts = countdownParts(ms);
317
+ const display = options.unitDisplay ?? 'short';
318
+ const units = [
319
+ [parts.days, 'day'],
320
+ [parts.hours, 'hour'],
321
+ [parts.minutes, 'minute'],
322
+ ];
323
+ if (options.seconds ?? false)
324
+ units.push([parts.seconds, 'second']);
325
+ const used = units.filter(([value]) => value > 0).slice(0, Math.max(1, options.maxUnits ?? 2));
326
+ if (!used.length) {
327
+ const [value, unit] = options.seconds ? [parts.seconds, 'second'] : [0, 'minute'];
328
+ return unitFormatter(locale, unit, display).format(value);
329
+ }
330
+ return used.map(([value, unit]) => unitFormatter(locale, unit, display).format(value)).join(' ');
331
+ }
332
+ /** Resume as decisões das etapas segundo a regra. */
333
+ export function approvalSummary(steps, rule = 'all') {
334
+ const counted = steps.filter((step) => step.decision !== 'skipped');
335
+ const approved = counted.filter((step) => step.decision === 'approved').length;
336
+ const rejected = counted.filter((step) => step.decision === 'rejected').length;
337
+ const pending = counted.length - approved - rejected;
338
+ const total = counted.length;
339
+ const required = rule === 'all' ? total : rule === 'any' ? Math.min(1, total) : Math.min(Math.max(1, Math.floor(rule.min)), total);
340
+ let state;
341
+ if (rule === 'all')
342
+ state = rejected > 0 ? 'rejected' : pending === 0 ? 'approved' : 'pending';
343
+ else if (approved >= required && total > 0)
344
+ state = 'approved';
345
+ else
346
+ state = approved + pending < required ? 'rejected' : 'pending';
347
+ const current = state === 'pending' ? counted.find((step) => step.decision === 'pending') : undefined;
348
+ return { state, approved, rejected, pending, total, required, currentId: current?.id ?? null };
349
+ }
350
+ const EXECUTION_TONE = {
351
+ queued: 'neutral',
352
+ running: 'info',
353
+ paused: 'warning',
354
+ succeeded: 'success',
355
+ failed: 'danger',
356
+ canceled: 'neutral',
357
+ };
358
+ export function executionTone(state) {
359
+ return EXECUTION_TONE[state];
360
+ }
361
+ /** A execução terminou (com sucesso, falha ou cancelada)? */
362
+ export function isExecutionFinal(state) {
363
+ return state === 'succeeded' || state === 'failed' || state === 'canceled';
364
+ }
365
+ /** Duração de uma execução: do início ao fim (ou até agora, enquanto corre). `null` sem início. */
366
+ export function executionDuration(startedAt, finishedAt, now) {
367
+ const start = workflowTime(startedAt);
368
+ if (start === null)
369
+ return null;
370
+ const end = workflowTime(finishedAt) ?? workflowTime(now) ?? Date.now();
371
+ return Math.max(0, end - start);
372
+ }
373
+ /** Valor de "sem responsável" nos seletores (string vazia). */
374
+ export const WORKFLOW_UNASSIGNED = '';
375
+ /** Próximo nível de escalonamento (`levels` em ordem); `null` se já está no último. */
376
+ export function nextEscalationLevel(levels, current) {
377
+ const index = Math.max(-1, Math.floor(current)) + 1;
378
+ return index < levels.length ? { index, level: levels[index] } : null;
379
+ }
380
+ /** Registros do mais recente para o mais antigo (os sem data por último, na ordem recebida). */
381
+ export function sortChangeHistory(entries, order = 'newest') {
382
+ const sign = order === 'newest' ? -1 : 1;
383
+ return entries
384
+ .map((entry, index) => ({ entry, index, time: workflowTime(entry.at) }))
385
+ .sort((a, b) => {
386
+ if (a.time === null || b.time === null)
387
+ return a.time === null ? (b.time === null ? a.index - b.index : 1) : -1;
388
+ return sign * (a.time - b.time) || a.index - b.index;
389
+ })
390
+ .map((item) => item.entry);
391
+ }
392
+ //# sourceMappingURL=workflow.js.map