@adatechnology/expense-contracts 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/dist/index.cjs +1655 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +797 -0
- package/dist/index.d.ts +797 -0
- package/dist/index.js +1536 -0
- package/dist/index.js.map +1 -0
- package/package.json +38 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3
|
+
*
|
|
4
|
+
* O vocabulário do módulo de contas: conta (fixa ou variável), ocorrência (o que vence), categoria e mudança de valor.
|
|
5
|
+
* Dinheiro é texto com duas casas; datas civis são `yyyy-mm-dd` e competências `yyyy-mm`.
|
|
6
|
+
*/
|
|
7
|
+
declare const EXPENSE_KINDS: readonly ["fixed", "variable"];
|
|
8
|
+
type ExpenseKind = (typeof EXPENSE_KINDS)[number];
|
|
9
|
+
/** `fortnightly` (quinzenal) vence nos dias 15 e no último dia do mês. */
|
|
10
|
+
declare const EXPENSE_RECURRENCES: readonly ["monthly", "bimonthly", "quarterly", "yearly", "fortnightly"];
|
|
11
|
+
type ExpenseRecurrence = (typeof EXPENSE_RECURRENCES)[number];
|
|
12
|
+
declare const EXPENSE_OCCURRENCE_STATUSES: readonly ["open", "paid", "canceled"];
|
|
13
|
+
type ExpenseOccurrenceStatus = (typeof EXPENSE_OCCURRENCE_STATUSES)[number];
|
|
14
|
+
/** `adjustment` = reajuste com vigência; `correction` = valor digitado errado, corrigido (o antigo fica no histórico). */
|
|
15
|
+
declare const EXPENSE_AMOUNT_CHANGE_KINDS: readonly ["adjustment", "correction"];
|
|
16
|
+
type ExpenseAmountChangeKind = (typeof EXPENSE_AMOUNT_CHANGE_KINDS)[number];
|
|
17
|
+
/** Canal por onde a conta entrou ou foi baixada. */
|
|
18
|
+
declare const EXPENSE_CHANNELS: readonly ["panel", "whatsapp", "email", "api"];
|
|
19
|
+
type ExpenseChannel = (typeof EXPENSE_CHANNELS)[number];
|
|
20
|
+
/**
|
|
21
|
+
* Grupo de custo da categoria, para o rateio entre unidades de trabalho (viagem, pedido, atendimento).
|
|
22
|
+
* - `asset_fixed`: custo fixo de um bem (seguro, IPVA, parcela do veículo);
|
|
23
|
+
* - `per_distance`: custo que anda com a distância (combustível, pneu);
|
|
24
|
+
* - `administrative`: custo da empresa (aluguel, contador);
|
|
25
|
+
* - `in_unit`: já está no custo da unidade (diária do motorista); nunca é rateado de novo.
|
|
26
|
+
*/
|
|
27
|
+
declare const EXPENSE_COST_GROUPS: readonly ["asset_fixed", "per_distance", "administrative", "in_unit"];
|
|
28
|
+
type ExpenseCostGroup = (typeof EXPENSE_COST_GROUPS)[number];
|
|
29
|
+
type ExpenseCategory = {
|
|
30
|
+
readonly active: boolean;
|
|
31
|
+
readonly costGroup: ExpenseCostGroup;
|
|
32
|
+
readonly displayOrder: number;
|
|
33
|
+
readonly id: string;
|
|
34
|
+
readonly name: string;
|
|
35
|
+
};
|
|
36
|
+
type Expense = {
|
|
37
|
+
readonly active: boolean;
|
|
38
|
+
/** `yyyy-mm` em que a conta começou: bimestral/trimestral/anual contam a partir dele. */
|
|
39
|
+
readonly anchorCompetence: string;
|
|
40
|
+
readonly categoryId: string;
|
|
41
|
+
readonly companyId: string;
|
|
42
|
+
readonly createdAt: string;
|
|
43
|
+
/** 1–31 na fixa (menos a quinzenal); nulo na variável. */
|
|
44
|
+
readonly dueDay: number | null;
|
|
45
|
+
/** Valor de abertura; o valor de uma competência sai de `amountInEffect` com o histórico. */
|
|
46
|
+
readonly expectedAmount: string;
|
|
47
|
+
readonly id: string;
|
|
48
|
+
/** Total de parcelas da fixa; nulo = sem fim. */
|
|
49
|
+
readonly installmentsTotal: number | null;
|
|
50
|
+
readonly kind: ExpenseKind;
|
|
51
|
+
readonly name: string;
|
|
52
|
+
readonly notes: string | null;
|
|
53
|
+
/** Referências opacas do produto: quem recebe, qual bem, quem é responsável. O módulo nunca as interpreta. */
|
|
54
|
+
readonly assetRef: string | null;
|
|
55
|
+
readonly payeeRef: string | null;
|
|
56
|
+
readonly payeeName: string | null;
|
|
57
|
+
readonly recurrence: ExpenseRecurrence | null;
|
|
58
|
+
readonly responsibleUserId: string | null;
|
|
59
|
+
readonly supplier: string | null;
|
|
60
|
+
readonly billUrl: string | null;
|
|
61
|
+
/** Quem originou a conta (ex.: `purchase-receipt:<id>`); nulo quando lançada à mão. */
|
|
62
|
+
readonly sourceRef: string | null;
|
|
63
|
+
};
|
|
64
|
+
type ExpenseOccurrence = {
|
|
65
|
+
readonly cancelReason: string | null;
|
|
66
|
+
readonly canceledAt: string | null;
|
|
67
|
+
readonly companyId: string;
|
|
68
|
+
/** `yyyy-mm`. */
|
|
69
|
+
readonly competence: string;
|
|
70
|
+
/** `yyyy-mm-dd`. */
|
|
71
|
+
readonly dueDate: string;
|
|
72
|
+
readonly expectedAmount: string;
|
|
73
|
+
readonly expenseId: string;
|
|
74
|
+
readonly id: string;
|
|
75
|
+
readonly installmentNumber: number | null;
|
|
76
|
+
readonly paidAmount: string | null;
|
|
77
|
+
/** `yyyy-mm-dd` do pagamento. */
|
|
78
|
+
readonly paidAt: string | null;
|
|
79
|
+
readonly paidBy: string | null;
|
|
80
|
+
readonly settledVia: ExpenseChannel | null;
|
|
81
|
+
readonly settlementNote: string | null;
|
|
82
|
+
readonly slot: 1 | 2;
|
|
83
|
+
readonly status: ExpenseOccurrenceStatus;
|
|
84
|
+
};
|
|
85
|
+
/** Linha da lista de vencimentos: a ocorrência com o que a tela precisa da conta. */
|
|
86
|
+
type ExpenseOccurrenceListItem = ExpenseOccurrence & {
|
|
87
|
+
readonly categoryId: string;
|
|
88
|
+
readonly categoryName: string;
|
|
89
|
+
readonly expenseKind: ExpenseKind;
|
|
90
|
+
readonly expenseName: string;
|
|
91
|
+
readonly installmentsTotal: number | null;
|
|
92
|
+
readonly payeeName: string | null;
|
|
93
|
+
readonly supplier: string | null;
|
|
94
|
+
};
|
|
95
|
+
type ExpenseAmountChange = {
|
|
96
|
+
readonly changedBy: string;
|
|
97
|
+
readonly createdAt: string;
|
|
98
|
+
/** `yyyy-mm`: a primeira competência com o valor novo. */
|
|
99
|
+
readonly effectiveCompetence: string;
|
|
100
|
+
readonly expenseId: string;
|
|
101
|
+
readonly id: string;
|
|
102
|
+
readonly kind: ExpenseAmountChangeKind;
|
|
103
|
+
readonly newAmount: string;
|
|
104
|
+
readonly previousAmount: string;
|
|
105
|
+
};
|
|
106
|
+
/** Situação de uma ocorrência aberta num dia: a vencer, vence hoje ou vencida. */
|
|
107
|
+
type ExpenseDueState = 'upcoming' | 'due_today' | 'overdue';
|
|
108
|
+
/** Categorias semeadas para empresa nova. Genéricas: servem a restaurante, transportadora ou escritório. */
|
|
109
|
+
declare const DEFAULT_EXPENSE_CATEGORIES: readonly {
|
|
110
|
+
readonly costGroup: ExpenseCostGroup;
|
|
111
|
+
readonly name: string;
|
|
112
|
+
}[];
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
116
|
+
*
|
|
117
|
+
* Códigos estáveis de recusa do módulo de contas. O host traduz para HTTP (`status`) e a tela, para texto.
|
|
118
|
+
*/
|
|
119
|
+
declare const EXPENSE_ERROR: {
|
|
120
|
+
readonly AMOUNT_INVALID: {
|
|
121
|
+
readonly code: "EXPENSE_AMOUNT_INVALID";
|
|
122
|
+
readonly status: 400;
|
|
123
|
+
};
|
|
124
|
+
readonly CATEGORY_INACTIVE: {
|
|
125
|
+
readonly code: "EXPENSE_CATEGORY_INACTIVE";
|
|
126
|
+
readonly status: 409;
|
|
127
|
+
};
|
|
128
|
+
readonly CATEGORY_NAME_TAKEN: {
|
|
129
|
+
readonly code: "EXPENSE_CATEGORY_NAME_TAKEN";
|
|
130
|
+
readonly status: 409;
|
|
131
|
+
};
|
|
132
|
+
readonly CATEGORY_NOT_FOUND: {
|
|
133
|
+
readonly code: "EXPENSE_CATEGORY_NOT_FOUND";
|
|
134
|
+
readonly status: 404;
|
|
135
|
+
};
|
|
136
|
+
readonly EXPENSE_NOT_FOUND: {
|
|
137
|
+
readonly code: "EXPENSE_NOT_FOUND";
|
|
138
|
+
readonly status: 404;
|
|
139
|
+
};
|
|
140
|
+
readonly INVALID_SCHEDULE: {
|
|
141
|
+
readonly code: "EXPENSE_INVALID_SCHEDULE";
|
|
142
|
+
readonly status: 400;
|
|
143
|
+
};
|
|
144
|
+
readonly OCCURRENCE_NOT_FOUND: {
|
|
145
|
+
readonly code: "EXPENSE_OCCURRENCE_NOT_FOUND";
|
|
146
|
+
readonly status: 404;
|
|
147
|
+
};
|
|
148
|
+
readonly OCCURRENCE_TRANSITION_NOT_ALLOWED: {
|
|
149
|
+
readonly code: "EXPENSE_OCCURRENCE_TRANSITION_NOT_ALLOWED";
|
|
150
|
+
readonly status: 409;
|
|
151
|
+
};
|
|
152
|
+
readonly UNAUTHENTICATED: {
|
|
153
|
+
readonly code: "EXPENSE_UNAUTHENTICATED";
|
|
154
|
+
readonly status: 401;
|
|
155
|
+
};
|
|
156
|
+
};
|
|
157
|
+
/** Texto padrão (pt-BR) de cada recusa; a tela pode trocar pelo dela usando o `code`. */
|
|
158
|
+
declare const EXPENSE_ERROR_MESSAGES: Record<keyof typeof EXPENSE_ERROR, string>;
|
|
159
|
+
type ExpenseErrorKey = keyof typeof EXPENSE_ERROR;
|
|
160
|
+
type ExpenseErrorCode = (typeof EXPENSE_ERROR)[ExpenseErrorKey]['code'];
|
|
161
|
+
declare class ExpenseError extends Error {
|
|
162
|
+
readonly code: ExpenseErrorCode;
|
|
163
|
+
readonly status: number;
|
|
164
|
+
/** Mesmo valor de `status`, no nome que o `@adatechnology/module-http` reconhece como erro de domínio. */
|
|
165
|
+
readonly statusCode: number;
|
|
166
|
+
constructor(key: ExpenseErrorKey, message?: string);
|
|
167
|
+
}
|
|
168
|
+
declare function isExpenseError(error: unknown): error is ExpenseError;
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
172
|
+
*
|
|
173
|
+
* Dinheiro é texto com até duas casas (`numeric` do banco), nunca float. Toda conta é feita em centavos (`bigint`).
|
|
174
|
+
*/
|
|
175
|
+
/** `'1500.5'` → `150050n`; `null` quando não é valor não negativo com até 2 casas. */
|
|
176
|
+
declare function parseMoneyToCents(value: string): bigint | null;
|
|
177
|
+
/** `150050n` → `'1500.50'`. Aceita negativo (lucro, diferença). */
|
|
178
|
+
declare function formatCents(cents: bigint): string;
|
|
179
|
+
/** Normaliza para duas casas (`'10'` → `'10.00'`); `null` quando ilegível. */
|
|
180
|
+
declare function normalizeMoney(value: string): string | null;
|
|
181
|
+
/**
|
|
182
|
+
* Valor vindo do banco com quatro casas (`numeric(19,4)`): aceito só quando as duas últimas são zero (`'10.5000'`).
|
|
183
|
+
* Arredondar aqui faria a soma deixar de bater com o que foi digitado.
|
|
184
|
+
*/
|
|
185
|
+
declare function parseStoredMoneyToCents(value: string): bigint | null;
|
|
186
|
+
/** Divisão de não negativos arredondada meio para cima (o arredondamento de dinheiro do módulo). */
|
|
187
|
+
declare function divideHalfUp(numerator: bigint, denominator: bigint): bigint;
|
|
188
|
+
/**
|
|
189
|
+
* Divide `total` pelos pesos sem perder unidade: piso em cada parte e o resto inteiro para o de maior peso.
|
|
190
|
+
* Determinístico no empate (o primeiro índice vence), para a mesma entrada dar sempre os mesmos números.
|
|
191
|
+
*/
|
|
192
|
+
declare function distributeByWeight(total: bigint, weights: readonly bigint[]): bigint[];
|
|
193
|
+
/** `'1234.5'` → `'R$ 1.234,50'`. Negativo sai com sinal antes do símbolo. */
|
|
194
|
+
declare function formatBrl(amount: string | bigint): string;
|
|
195
|
+
/** `yyyy-mm-dd` que existe no calendário. */
|
|
196
|
+
declare function isCivilDate(value: string): boolean;
|
|
197
|
+
/** `yyyy-mm` válido. */
|
|
198
|
+
declare function isCompetence(value: string): boolean;
|
|
199
|
+
/** Soma `days` dias a uma data civil `yyyy-mm-dd`. */
|
|
200
|
+
declare function addCivilDays(isoDate: string, days: number): string;
|
|
201
|
+
/** O dia civil (`yyyy-mm-dd`) de um instante num fuso IANA (padrão `America/Sao_Paulo`). */
|
|
202
|
+
declare function civilDateInTimeZone(instant: Date, timeZone?: string): string;
|
|
203
|
+
/** A hora cheia (0–23) de um instante num fuso IANA. */
|
|
204
|
+
declare function hourInTimeZone(instant: Date, timeZone?: string): number;
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
208
|
+
*
|
|
209
|
+
* Vencimento é data civil, sem hora. A conta fixa gera uma janela de competências (mês corrente + 3); cada recorrência
|
|
210
|
+
* cai em alguns meses e a quinzenal tem duas datas por mês (`slot` 1 = dia 15, `slot` 2 = último dia).
|
|
211
|
+
*/
|
|
212
|
+
|
|
213
|
+
declare const EXPENSE_GENERATION_WINDOW_MONTHS = 4;
|
|
214
|
+
type ResolveExpenseDueDateParams = {
|
|
215
|
+
/** `yyyy-mm`. */
|
|
216
|
+
readonly competence: string;
|
|
217
|
+
/** 1–31; mês curto cai no último dia. */
|
|
218
|
+
readonly dueDay: number;
|
|
219
|
+
};
|
|
220
|
+
type ExpenseScheduleSlot = {
|
|
221
|
+
readonly dueDate: string;
|
|
222
|
+
/** Número da parcela (1..total) só quando a conta é parcelada; nulo nas demais. */
|
|
223
|
+
readonly installmentNumber: number | null;
|
|
224
|
+
readonly slot: 1 | 2;
|
|
225
|
+
};
|
|
226
|
+
/** Índice contínuo do mês (`ano × 12 + mês − 1`), para contar distância entre competências. */
|
|
227
|
+
declare function competenceIndex(competence: string): number;
|
|
228
|
+
/** Soma `months` meses a uma competência `yyyy-mm`. */
|
|
229
|
+
declare function addCompetenceMonths(competence: string, months: number): string;
|
|
230
|
+
/** Devolve `yyyy-mm-dd`. */
|
|
231
|
+
declare function resolveExpenseDueDate(params: ResolveExpenseDueDateParams): string;
|
|
232
|
+
/** `yyyy-mm` de uma data civil `yyyy-mm-dd`. */
|
|
233
|
+
declare function competenceOfDate(date: string): string;
|
|
234
|
+
/** Primeiro e último dia (`yyyy-mm-dd`) de uma competência. */
|
|
235
|
+
declare function competenceBounds(competence: string): {
|
|
236
|
+
readonly from: string;
|
|
237
|
+
readonly to: string;
|
|
238
|
+
};
|
|
239
|
+
/** As competências a gerar: a do `today` e as `months - 1` seguintes. */
|
|
240
|
+
declare function listExpenseCompetenceWindow(today: string, months?: number): readonly string[];
|
|
241
|
+
/**
|
|
242
|
+
* As datas que a recorrência pede numa competência (vazio quando o mês não é dela). `anchorCompetence` é o mês em
|
|
243
|
+
* que a conta começou: bimestral/trimestral/anual contam a partir dele.
|
|
244
|
+
*/
|
|
245
|
+
declare function resolveExpenseSlots(params: {
|
|
246
|
+
readonly anchorCompetence: string;
|
|
247
|
+
readonly competence: string;
|
|
248
|
+
readonly dueDay: number | null;
|
|
249
|
+
/** Total de parcelas da conta; nulo = sem fim. A parcela além do total não é gerada. */
|
|
250
|
+
readonly installmentsTotal?: number | null;
|
|
251
|
+
readonly recurrence: ExpenseRecurrence;
|
|
252
|
+
}): readonly ExpenseScheduleSlot[];
|
|
253
|
+
/** Um vencimento a gerar: competência, slot, data e parcela. Chave natural `(competence, slot)`. */
|
|
254
|
+
type PlannedExpenseOccurrence = ExpenseScheduleSlot & {
|
|
255
|
+
readonly competence: string;
|
|
256
|
+
};
|
|
257
|
+
/**
|
|
258
|
+
* Todas as ocorrências que uma conta fixa pede dentro da janela que começa em `today`. Idempotente por desenho:
|
|
259
|
+
* quem grava usa `(expense, competence, slot)` como chave única e ignora o que já existe.
|
|
260
|
+
*/
|
|
261
|
+
declare function planFixedExpenseOccurrences(params: {
|
|
262
|
+
readonly anchorCompetence: string;
|
|
263
|
+
readonly dueDay: number | null;
|
|
264
|
+
readonly installmentsTotal?: number | null;
|
|
265
|
+
readonly recurrence: ExpenseRecurrence;
|
|
266
|
+
readonly today: string;
|
|
267
|
+
readonly windowMonths?: number;
|
|
268
|
+
}): readonly PlannedExpenseOccurrence[];
|
|
269
|
+
|
|
270
|
+
type AmountChangeLike = {
|
|
271
|
+
readonly createdAt?: string;
|
|
272
|
+
readonly effectiveCompetence: string;
|
|
273
|
+
readonly newAmount: string;
|
|
274
|
+
};
|
|
275
|
+
/** Valor em vigor numa competência: o da última mudança com início até ela; sem nenhuma, `baseAmount`. */
|
|
276
|
+
declare function amountInEffect(baseAmount: string, changes: readonly AmountChangeLike[], competence: string): string;
|
|
277
|
+
type PlannedAmountChange = {
|
|
278
|
+
/** `yyyy-mm`: início da vigência do valor novo. */
|
|
279
|
+
readonly effectiveCompetence: string;
|
|
280
|
+
readonly kind: ExpenseAmountChangeKind;
|
|
281
|
+
readonly newAmount: string;
|
|
282
|
+
/** `adjustment` só regrava ocorrência aberta que ainda não venceu; `correction` regrava as abertas do trecho. */
|
|
283
|
+
readonly onlyNotDue: boolean;
|
|
284
|
+
readonly previousAmount: string;
|
|
285
|
+
/** Até onde a correção vale (exclusivo); nulo = sem fim. */
|
|
286
|
+
readonly untilCompetence: string | null;
|
|
287
|
+
};
|
|
288
|
+
/**
|
|
289
|
+
* Decide a mudança de valor pedida. Devolve `null` quando o valor não muda (nada a gravar).
|
|
290
|
+
* - reajuste (`adjustment`): vale de `effectiveFrom` (padrão: o mês de `today`) em diante;
|
|
291
|
+
* - correção (`correction`): troca o trecho de valor em que `correctionCompetence` está, do começo dele até a próxima
|
|
292
|
+
* mudança.
|
|
293
|
+
*/
|
|
294
|
+
declare function planAmountChange(input: {
|
|
295
|
+
readonly baseAmount: string;
|
|
296
|
+
readonly changes: readonly AmountChangeLike[];
|
|
297
|
+
readonly correctionCompetence?: string;
|
|
298
|
+
readonly effectiveFrom?: string;
|
|
299
|
+
readonly kind?: ExpenseAmountChangeKind;
|
|
300
|
+
readonly newAmount: string;
|
|
301
|
+
readonly today: string;
|
|
302
|
+
}): PlannedAmountChange | null;
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
306
|
+
*
|
|
307
|
+
* O ciclo de uma ocorrência: `open → paid` (baixa), `paid → open` (desfazer baixa), `open → canceled`. Paga não se
|
|
308
|
+
* cancela (desfaça a baixa antes) e cancelada não volta.
|
|
309
|
+
*/
|
|
310
|
+
|
|
311
|
+
type ExpenseOccurrenceAction = 'settle' | 'reopen' | 'cancel';
|
|
312
|
+
declare function canTransitionOccurrence(status: ExpenseOccurrenceStatus, action: ExpenseOccurrenceAction): boolean;
|
|
313
|
+
|
|
314
|
+
/** O grupo `in_unit` não é rateado: o custo já está na unidade. */
|
|
315
|
+
type AllocatableCostGroup = Exclude<ExpenseCostGroup, 'in_unit'>;
|
|
316
|
+
declare const ALLOCATABLE_COST_GROUPS: readonly AllocatableCostGroup[];
|
|
317
|
+
declare const ALLOCATION_CRITERIA: readonly ["per_distance", "per_unit_day", "per_revenue", "equal"];
|
|
318
|
+
type AllocationCriterion = (typeof ALLOCATION_CRITERIA)[number];
|
|
319
|
+
type AllocationSettings = Readonly<Record<AllocatableCostGroup, AllocationCriterion>>;
|
|
320
|
+
/** Padrão sem configuração: fixo do bem e variável por distância, administrativo pelo faturamento. */
|
|
321
|
+
declare const DEFAULT_ALLOCATION_SETTINGS: AllocationSettings;
|
|
322
|
+
/** Unidade de trabalho concluída no período, com o resultado vivo. */
|
|
323
|
+
type AllocationUnit = {
|
|
324
|
+
/** `yyyy-mm-dd` da conclusão. */
|
|
325
|
+
readonly completedOn: string;
|
|
326
|
+
/** Bem que executou a unidade (veículo, máquina, sala); nulo quando não há. */
|
|
327
|
+
readonly assetId: string | null;
|
|
328
|
+
readonly daysCount: number;
|
|
329
|
+
readonly distanceMeters: number;
|
|
330
|
+
/** Receita da unidade; aceita até quatro casas (`numeric(19,4)`). */
|
|
331
|
+
readonly revenue: string;
|
|
332
|
+
readonly unitId: string;
|
|
333
|
+
};
|
|
334
|
+
/** Conta do período com o valor já considerado (pago, senão previsto); cancelada nunca chega aqui. */
|
|
335
|
+
type AllocationExpense = {
|
|
336
|
+
readonly amount: string;
|
|
337
|
+
/** Bem ligado à conta: ela só se divide entre as unidades dele. */
|
|
338
|
+
readonly assetId: string | null;
|
|
339
|
+
readonly costGroup: ExpenseCostGroup;
|
|
340
|
+
readonly expenseId: string;
|
|
341
|
+
/** Só no grupo `in_unit`: soma das unidades incluídas no pagamento. */
|
|
342
|
+
readonly includedUnitsAmount?: string;
|
|
343
|
+
readonly occurrenceId: string;
|
|
344
|
+
};
|
|
345
|
+
type AllocationShare = {
|
|
346
|
+
readonly amount: string;
|
|
347
|
+
readonly occurrenceId: string;
|
|
348
|
+
/** `asset`: conta ligada a um bem; `general`: conta sem bem e o excedente do pagamento. */
|
|
349
|
+
readonly scope: 'asset' | 'general';
|
|
350
|
+
readonly unitId: string;
|
|
351
|
+
};
|
|
352
|
+
type UnallocatedReason = 'asset_without_units' | 'no_unit_weight';
|
|
353
|
+
type AllocationUnallocated = {
|
|
354
|
+
readonly amount: string;
|
|
355
|
+
readonly assetId: string | null;
|
|
356
|
+
readonly occurrenceId: string;
|
|
357
|
+
readonly reason: UnallocatedReason;
|
|
358
|
+
};
|
|
359
|
+
type AllocationResult = {
|
|
360
|
+
/** Pagamento que passou das unidades incluídas (bônus, adiantamento), rateado como administrativo. */
|
|
361
|
+
readonly excesses: readonly {
|
|
362
|
+
readonly amount: string;
|
|
363
|
+
readonly occurrenceId: string;
|
|
364
|
+
}[];
|
|
365
|
+
readonly shares: readonly AllocationShare[];
|
|
366
|
+
readonly unallocated: readonly AllocationUnallocated[];
|
|
367
|
+
};
|
|
368
|
+
declare function allocateExpenses(input: {
|
|
369
|
+
readonly expenses: readonly AllocationExpense[];
|
|
370
|
+
readonly settings: AllocationSettings;
|
|
371
|
+
readonly units: readonly AllocationUnit[];
|
|
372
|
+
}): AllocationResult;
|
|
373
|
+
|
|
374
|
+
/** Mês fechado já calculado pelo mesmo caminho do resultado (ADR-0116 §7). */
|
|
375
|
+
type ClosedMonthResult = {
|
|
376
|
+
/** Dias úteis do mês, pelo calendário da empresa. */
|
|
377
|
+
readonly businessDays: number;
|
|
378
|
+
/** Custo direto das unidades do mês (viagens, pedidos), já com o que mora nelas. */
|
|
379
|
+
readonly directCost: string;
|
|
380
|
+
/** `yyyy-mm`. */
|
|
381
|
+
readonly month: string;
|
|
382
|
+
readonly revenue: string;
|
|
383
|
+
};
|
|
384
|
+
type ForecastRange = {
|
|
385
|
+
readonly expected: string;
|
|
386
|
+
readonly max: string;
|
|
387
|
+
readonly min: string;
|
|
388
|
+
};
|
|
389
|
+
type ForecastInput = {
|
|
390
|
+
/** Meses fechados, qualquer ordem; só os 6 mais recentes entram. */
|
|
391
|
+
readonly history: readonly ClosedMonthResult[];
|
|
392
|
+
/** Dias úteis do mês previsto. */
|
|
393
|
+
readonly nextMonthBusinessDays: number;
|
|
394
|
+
/** Contas recorrentes já cadastradas para o mês previsto. */
|
|
395
|
+
readonly recurringExpenses: string;
|
|
396
|
+
};
|
|
397
|
+
type ForecastResult = {
|
|
398
|
+
readonly forecast: null;
|
|
399
|
+
readonly monthsOfData: number;
|
|
400
|
+
readonly status: 'unavailable';
|
|
401
|
+
readonly warning: 'few_data';
|
|
402
|
+
} | {
|
|
403
|
+
readonly forecast: {
|
|
404
|
+
readonly cost: ForecastRange;
|
|
405
|
+
readonly profit: ForecastRange;
|
|
406
|
+
readonly revenue: ForecastRange;
|
|
407
|
+
};
|
|
408
|
+
readonly monthsOfData: number;
|
|
409
|
+
readonly status: 'limited' | 'ok';
|
|
410
|
+
/** `few_data` só entre 3 e 5 meses (CA12). */
|
|
411
|
+
readonly warning: 'few_data' | null;
|
|
412
|
+
};
|
|
413
|
+
/** Meses fechados com dado que bastam para mostrar a previsão (RF22, CA12). */
|
|
414
|
+
declare const FORECAST_MIN_MONTHS = 3;
|
|
415
|
+
/** A partir de quantos meses com dado a previsão sai sem o aviso de poucos dados (RF22). */
|
|
416
|
+
declare const FORECAST_FULL_MONTHS = 6;
|
|
417
|
+
/**
|
|
418
|
+
* Meia largura mínima da faixa, em % da parte estimada (faturamento e custo direto), por situação do histórico.
|
|
419
|
+
* A faixa é a maior entre essa margem e a variação que os próprios meses mostraram (ver `estimate`). Com 3 a 5 meses
|
|
420
|
+
* a margem dobra: pouca amostra não dá para fingir precisão (RF22, "usa a faixa mais larga"). Decisão da T6.2,
|
|
421
|
+
* registrada em `specs/325-contas-fixas-e-variaveis/evidence.md` § T6.2.
|
|
422
|
+
*/
|
|
423
|
+
declare const FORECAST_BAND_FLOOR_PERCENT: {
|
|
424
|
+
readonly limited: 30n;
|
|
425
|
+
readonly ok: 15n;
|
|
426
|
+
};
|
|
427
|
+
declare function forecastNextMonth(input: ForecastInput): ForecastResult;
|
|
428
|
+
/** O que se compara: categoria, conta ou um custo unitário do produto (ex.: custo por km do veículo). */
|
|
429
|
+
type OutOfPatternKind = string;
|
|
430
|
+
type OutOfPatternItem = {
|
|
431
|
+
/** Valor do mês corrente. */
|
|
432
|
+
readonly current: string;
|
|
433
|
+
readonly key: string;
|
|
434
|
+
readonly kind: OutOfPatternKind;
|
|
435
|
+
readonly label: string;
|
|
436
|
+
/** Valores dos meses fechados anteriores, mais recente primeiro; só os 3 mais recentes entram na média. */
|
|
437
|
+
readonly previousMonths: readonly string[];
|
|
438
|
+
};
|
|
439
|
+
type OutOfPatternAlert = {
|
|
440
|
+
readonly average: string;
|
|
441
|
+
readonly current: string;
|
|
442
|
+
readonly difference: string;
|
|
443
|
+
readonly direction: 'above' | 'below';
|
|
444
|
+
readonly key: string;
|
|
445
|
+
readonly kind: OutOfPatternKind;
|
|
446
|
+
readonly label: string;
|
|
447
|
+
};
|
|
448
|
+
declare const DEFAULT_OUT_OF_PATTERN_THRESHOLD_PERCENT = 10;
|
|
449
|
+
/** Meses fechados anteriores que formam o padrão do item (RF23). */
|
|
450
|
+
declare const OUT_OF_PATTERN_MONTHS = 3;
|
|
451
|
+
/**
|
|
452
|
+
* Compara o mês corrente com a média dos 3 meses fechados mais recentes, arredondada ao centavo (a mesma que a tela
|
|
453
|
+
* mostra, para os números exibidos nunca contradizerem a regra). Alerta só quando |corrente − média| passa
|
|
454
|
+
* **estritamente** do limite sobre a média: exatamente no limite não alerta (CA13).
|
|
455
|
+
*
|
|
456
|
+
* A conta é feita por multiplicação cruzada, sem divisão. Por isso média zero tem resposta natural: corrente também
|
|
457
|
+
* zero não alerta; qualquer valor diferente de zero alerta, porque passa de qualquer porcentagem de zero (um gasto
|
|
458
|
+
* que não existia e apareceu é exatamente o que a lista deve mostrar).
|
|
459
|
+
*
|
|
460
|
+
* Item com menos de 3 meses de histórico (bem novo, conta nova) não alerta: não há padrão. Quem monta
|
|
461
|
+
* `previousMonths` deixa de fora o mês em que o item não existiu (custo unitário de um bem parado não é zero, é
|
|
462
|
+
* ausência), para esse mês não virar um zero que dispara o alerta. A saída segue a ordem da entrada.
|
|
463
|
+
*/
|
|
464
|
+
declare function detectOutOfPattern(input: {
|
|
465
|
+
readonly items: readonly OutOfPatternItem[];
|
|
466
|
+
readonly thresholdPercent: number;
|
|
467
|
+
}): readonly OutOfPatternAlert[];
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
471
|
+
*
|
|
472
|
+
* Os filtros do resultado **não** mudam o rateio: ele é feito sobre todas as unidades e contas do período; o filtro só
|
|
473
|
+
* escolhe quais linhas aparecem e somam.
|
|
474
|
+
*/
|
|
475
|
+
/** Unidade sem bem (ou sem cliente) não some do resultado: vira uma linha com este identificador. */
|
|
476
|
+
declare const NO_ASSET_ID = "sem-bem";
|
|
477
|
+
declare const NO_CUSTOMER_ID = "sem-cliente";
|
|
478
|
+
type ExpenseResultFilters = {
|
|
479
|
+
readonly assetId?: string;
|
|
480
|
+
readonly categoryId?: string;
|
|
481
|
+
readonly customerId?: string;
|
|
482
|
+
readonly payeeRef?: string;
|
|
483
|
+
};
|
|
484
|
+
declare const EXPENSE_RESULT_FILTER_KEYS: readonly ["assetId", "categoryId", "customerId", "payeeRef"];
|
|
485
|
+
declare function hasResultFilters(filters: ExpenseResultFilters | undefined): boolean;
|
|
486
|
+
declare function unitMatchesFilters(unit: {
|
|
487
|
+
readonly assetId: string;
|
|
488
|
+
readonly customerId: string;
|
|
489
|
+
}, filters: ExpenseResultFilters): boolean;
|
|
490
|
+
declare function expenseMatchesFilters(expense: {
|
|
491
|
+
readonly categoryId: string;
|
|
492
|
+
readonly payeeRef: string | null | undefined;
|
|
493
|
+
}, filters: ExpenseResultFilters): boolean;
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
497
|
+
*
|
|
498
|
+
* A regra de **quando** avisar, **quem** avisar e **por qual canal**, pura (sem banco, sem relógio, sem fuso: datas
|
|
499
|
+
* civis em texto e a hora já convertida). A rotina do host só a aplica.
|
|
500
|
+
*
|
|
501
|
+
* - **Quando**: `before` exatamente `daysBefore` dias antes (0 desliga), `due_today` no dia e `overdue` do 1º ao
|
|
502
|
+
* `maxOverdueNotices`-ésimo dia de atraso, contado pelo calendário (rotina que não rodou num dia não empurra o aviso).
|
|
503
|
+
* Nada antes de `dailySummaryHour`.
|
|
504
|
+
* - **Quem**: o responsável, se ainda é da empresa **e** tem algum canal ligado; senão os administradores. Responsável
|
|
505
|
+
* que não pode receber nada conta como sem responsável: o aviso cai no administrador em vez de não sair.
|
|
506
|
+
* - **Canal**: e-mail sempre que a pessoa tem e-mail; WhatsApp só com opt-in **e** número verificado; push só com
|
|
507
|
+
* opt-in. Cada um ainda precisa estar ligado na empresa. A ordem é fixa (e-mail, WhatsApp, push).
|
|
508
|
+
*/
|
|
509
|
+
declare const REMINDER_KINDS: readonly ["before", "due_today", "overdue"];
|
|
510
|
+
type ReminderKind = (typeof REMINDER_KINDS)[number];
|
|
511
|
+
declare const REMINDER_CHANNELS: readonly ["email", "whatsapp", "push"];
|
|
512
|
+
type ReminderChannel = (typeof REMINDER_CHANNELS)[number];
|
|
513
|
+
type ReminderSettings = {
|
|
514
|
+
/** Avisa N dias antes (padrão 3; 0 desliga o aviso antecipado). */
|
|
515
|
+
readonly daysBefore: number;
|
|
516
|
+
/** Avisos de atraso, um por dia, até este limite (padrão 3). */
|
|
517
|
+
readonly maxOverdueNotices: number;
|
|
518
|
+
/** Canais ligados na empresa; só neles o aviso sai. */
|
|
519
|
+
readonly enabledChannels: readonly ReminderChannel[];
|
|
520
|
+
/** Resumo diário ligado (padrão desligado). */
|
|
521
|
+
readonly dailySummaryEnabled: boolean;
|
|
522
|
+
/** Hora cheia (0–23) a partir da qual saem o resumo e os avisos do dia (padrão 8). */
|
|
523
|
+
readonly dailySummaryHour: number;
|
|
524
|
+
};
|
|
525
|
+
declare const DEFAULT_REMINDER_SETTINGS: ReminderSettings;
|
|
526
|
+
type ReminderRecipient = {
|
|
527
|
+
readonly channels: readonly ReminderChannel[];
|
|
528
|
+
readonly userId: string;
|
|
529
|
+
};
|
|
530
|
+
/** Dias de `from` até `to` (positivo quando `to` é depois). Datas `yyyy-mm-dd`. */
|
|
531
|
+
declare function civilDaysBetween(from: string, to: string): number;
|
|
532
|
+
/** O tipo de aviso que a ocorrência aberta pede hoje, ou `null`. Não olha status: isso é do caso de uso. */
|
|
533
|
+
declare function reminderKindOn(input: {
|
|
534
|
+
readonly dueDate: string;
|
|
535
|
+
readonly settings: Pick<ReminderSettings, 'daysBefore' | 'maxOverdueNotices'>;
|
|
536
|
+
readonly today: string;
|
|
537
|
+
}): ReminderKind | null;
|
|
538
|
+
/** Quantos dias faltam (positivo) ou de atraso (negativo). */
|
|
539
|
+
declare function daysUntilDue(input: {
|
|
540
|
+
readonly dueDate: string;
|
|
541
|
+
readonly today: string;
|
|
542
|
+
}): number;
|
|
543
|
+
/** O resumo do dia lista o que vence hoje e tudo o que está vencido e aberto, sem limite de dias. */
|
|
544
|
+
declare function belongsToDailySummary(input: {
|
|
545
|
+
readonly dueDate: string;
|
|
546
|
+
readonly status: string;
|
|
547
|
+
readonly today: string;
|
|
548
|
+
}): boolean;
|
|
549
|
+
/** Avisos e resumo só saem a partir da hora configurada (hora cheia 0–23 no fuso da empresa). */
|
|
550
|
+
declare function isReminderHour(input: {
|
|
551
|
+
readonly hourOfDay: number;
|
|
552
|
+
readonly settings: Pick<ReminderSettings, 'dailySummaryHour'>;
|
|
553
|
+
}): boolean;
|
|
554
|
+
/** O que a pessoa tem para receber, antes de olhar a empresa. */
|
|
555
|
+
type ReminderPersonFacts = {
|
|
556
|
+
readonly hasEmail: boolean;
|
|
557
|
+
readonly hasVerifiedWhatsapp: boolean;
|
|
558
|
+
readonly pushOptIn: boolean;
|
|
559
|
+
readonly whatsappOptIn: boolean;
|
|
560
|
+
};
|
|
561
|
+
/**
|
|
562
|
+
* Quem é só equipe de campo (motorista, entregador, cozinha) não recebe aviso de conta, a menos que também tenha papel
|
|
563
|
+
* de escritório. `fieldRoles` são os papéis de campo do produto; `neutralRoles` os que todo mundo tem (não contam como
|
|
564
|
+
* escritório). `isFieldStaff` cobre o cadastro de campo fora do papel (ficha de motorista, por exemplo).
|
|
565
|
+
*/
|
|
566
|
+
declare function isBarredFromReminders(facts: {
|
|
567
|
+
readonly fieldRoles: readonly string[];
|
|
568
|
+
readonly isFieldStaff?: boolean;
|
|
569
|
+
readonly neutralRoles?: readonly string[];
|
|
570
|
+
readonly roles: readonly string[];
|
|
571
|
+
}): boolean;
|
|
572
|
+
/** Os canais da pessoa (sem a empresa). E-mail não tem opt-out: é o canal que garante o aviso. */
|
|
573
|
+
declare function personalReminderChannels(facts: ReminderPersonFacts): readonly ReminderChannel[];
|
|
574
|
+
/** Os canais em que o aviso de fato sai para a pessoa: os dela, ligados na empresa. */
|
|
575
|
+
declare function effectiveReminderChannels(input: {
|
|
576
|
+
readonly companyChannels: readonly ReminderChannel[];
|
|
577
|
+
readonly recipient: Pick<ReminderRecipient, 'channels'>;
|
|
578
|
+
}): readonly ReminderChannel[];
|
|
579
|
+
type ReminderRecipientReason = 'responsible' | 'no_responsible' | 'responsible_unreachable';
|
|
580
|
+
type ReminderRecipientChoice = {
|
|
581
|
+
readonly reason: ReminderRecipientReason;
|
|
582
|
+
/** Já com os canais efetivos; vazio só quando nem administrador pode receber. */
|
|
583
|
+
readonly recipients: readonly ReminderRecipient[];
|
|
584
|
+
};
|
|
585
|
+
/** Quem recebe o aviso de uma ocorrência. `responsible` é `null` quando a conta não tem ou ele saiu da empresa. */
|
|
586
|
+
declare function chooseReminderRecipients(input: {
|
|
587
|
+
readonly admins: readonly ReminderRecipient[];
|
|
588
|
+
readonly companyChannels: readonly ReminderChannel[];
|
|
589
|
+
readonly responsible: ReminderRecipient | null;
|
|
590
|
+
}): ReminderRecipientChoice;
|
|
591
|
+
|
|
592
|
+
/** Mesmo escape de `@adatechnology/notification-contracts` (`escapeEmailHtml`). */
|
|
593
|
+
declare function escapeHtml(value: string): string;
|
|
594
|
+
/** `'2026-11-17'` → `'17/11/2026'`. */
|
|
595
|
+
declare function formatCivilDateBr(value: string): string;
|
|
596
|
+
/** `'2026-11'` → `'11/2026'`. */
|
|
597
|
+
declare function formatCompetenceBr(value: string): string;
|
|
598
|
+
/** A frase do prazo, do jeito que o aviso diz. */
|
|
599
|
+
declare function describeDueSituation(daysUntilDue: number): string;
|
|
600
|
+
type ExpenseReminderFacts = {
|
|
601
|
+
readonly amount: string;
|
|
602
|
+
readonly categoryName: string;
|
|
603
|
+
readonly companyDisplayName: string;
|
|
604
|
+
readonly competence: string;
|
|
605
|
+
readonly dueDate: string;
|
|
606
|
+
readonly expenseName: string;
|
|
607
|
+
readonly payeeName: string | null;
|
|
608
|
+
readonly recipientName: string;
|
|
609
|
+
readonly today: string;
|
|
610
|
+
};
|
|
611
|
+
type ExpenseTextOptions = {
|
|
612
|
+
/** Nome da variável que leva o nome da empresa no modelo (padrão `empresa`; a transportadora usa `transportadora`). */
|
|
613
|
+
readonly companyVariable?: string;
|
|
614
|
+
};
|
|
615
|
+
/** Os valores de texto do aviso de uma conta (e-mail e WhatsApp usam os mesmos). */
|
|
616
|
+
declare function buildExpenseReminderValues(facts: ExpenseReminderFacts, options?: ExpenseTextOptions): Readonly<Record<string, string>>;
|
|
617
|
+
type ExpenseSummaryLine = {
|
|
618
|
+
readonly amount: string;
|
|
619
|
+
readonly dueDate: string;
|
|
620
|
+
readonly expenseName: string;
|
|
621
|
+
};
|
|
622
|
+
/** Os valores de texto do resumo diário. */
|
|
623
|
+
declare function buildExpenseDailySummaryValues(input: {
|
|
624
|
+
readonly companyDisplayName: string;
|
|
625
|
+
readonly lines: readonly ExpenseSummaryLine[];
|
|
626
|
+
readonly recipientName: string;
|
|
627
|
+
readonly today: string;
|
|
628
|
+
}, options?: ExpenseTextOptions): Readonly<Record<string, string>>;
|
|
629
|
+
type ExpenseMailPalette = {
|
|
630
|
+
readonly border: string;
|
|
631
|
+
readonly muted: string;
|
|
632
|
+
readonly primary: string;
|
|
633
|
+
readonly text: string;
|
|
634
|
+
};
|
|
635
|
+
declare const DEFAULT_EXPENSE_MAIL_PALETTE: ExpenseMailPalette;
|
|
636
|
+
/** Um botão "à prova de Outlook" (tabela, sem CSS moderno). Sem URL https, nada: a variável sai vazia. */
|
|
637
|
+
declare function buildExpenseMailButtonHtml(input: {
|
|
638
|
+
readonly label: string;
|
|
639
|
+
readonly palette?: ExpenseMailPalette;
|
|
640
|
+
readonly primary: boolean;
|
|
641
|
+
readonly url: string | null;
|
|
642
|
+
}): string;
|
|
643
|
+
/** A tabela do resumo, uma linha por conta, na ordem recebida. */
|
|
644
|
+
declare function buildExpenseSummaryTableHtml(input: {
|
|
645
|
+
readonly lines: readonly ExpenseSummaryLine[];
|
|
646
|
+
readonly palette?: ExpenseMailPalette;
|
|
647
|
+
readonly today: string;
|
|
648
|
+
}): string;
|
|
649
|
+
/** Interpola `{{nome}}` num texto sem HTML (WhatsApp, push): valor cru, desconhecido sai vazio. Uma passada só. */
|
|
650
|
+
declare function renderPlainTemplate(body: string, values: Readonly<Record<string, string>>): string;
|
|
651
|
+
/** Texto padrão do aviso por WhatsApp, para o produto que ainda não tem modelo próprio. */
|
|
652
|
+
declare const DEFAULT_EXPENSE_REMINDER_WHATSAPP_TEXT: string;
|
|
653
|
+
/** Texto padrão do resumo diário por WhatsApp. */
|
|
654
|
+
declare const DEFAULT_EXPENSE_SUMMARY_WHATSAPP_TEXT: string;
|
|
655
|
+
|
|
656
|
+
/** Texto sem acento, minúsculo, só letras/números/espaço. */
|
|
657
|
+
declare function normalizeChatText(text: string): string;
|
|
658
|
+
/** `R$ 1.500,50` / `1500` / `89,9` → `'1500.50'`; `undefined` quando não é valor positivo. */
|
|
659
|
+
declare function parseExpenseAmount(text: string): string | undefined;
|
|
660
|
+
/** `hoje`, `amanhã`, `dd/mm` (próxima ocorrência a partir de hoje) e `dd/mm/aaaa`. `today` é injetado. */
|
|
661
|
+
declare function parseExpenseDueDate(text: string, today: string): string | undefined;
|
|
662
|
+
/** `5` ou `dia 10` → 1..31. */
|
|
663
|
+
declare function parseExpenseDueDay(text: string): number | undefined;
|
|
664
|
+
/**
|
|
665
|
+
* A mensagem fala de conta ou só abre a conversa ("oi", "menu"): vai ao assistente financeiro. "baixa" sozinha fica de
|
|
666
|
+
* fora (equipe de campo também dá baixa em entrega).
|
|
667
|
+
*/
|
|
668
|
+
declare function isDirectExpenseIntent(text: string): boolean;
|
|
669
|
+
declare function isFieldStaffFinanceIntent(text: string): boolean;
|
|
670
|
+
/** "paguei", "já paguei 150,00", "pago": a resposta que dá baixa num aviso. Valor opcional. */
|
|
671
|
+
declare function parseSettlementReply(text: string): {
|
|
672
|
+
readonly amount?: string;
|
|
673
|
+
} | null;
|
|
674
|
+
|
|
675
|
+
declare const EXPENSE_NAME_MIN_LENGTH = 2;
|
|
676
|
+
declare const EXPENSE_NAME_MAX_LENGTH = 80;
|
|
677
|
+
declare const EXPENSE_CONVERSATION_STEPS: readonly ["kind", "name", "category", "amount", "recurrence", "due_day", "due_date", "confirm", "done", "cancelled"];
|
|
678
|
+
type ExpenseConversationStep = (typeof EXPENSE_CONVERSATION_STEPS)[number];
|
|
679
|
+
declare const EXPENSE_CONVERSATION_ANSWER: {
|
|
680
|
+
readonly cancel: "cancel";
|
|
681
|
+
readonly confirm: "confirm";
|
|
682
|
+
readonly fix: "fix";
|
|
683
|
+
};
|
|
684
|
+
declare const EXPENSE_RECURRENCE_OPTIONS: readonly (readonly [ExpenseRecurrence, string])[];
|
|
685
|
+
declare const EXPENSE_CONVERSATION_TEXT: {
|
|
686
|
+
readonly amount: "Qual o valor? Por exemplo: 1500 ou 1.500,50";
|
|
687
|
+
readonly amountInvalid: "Não entendi o valor. Digite só números, por exemplo: 1500 ou 1.500,50";
|
|
688
|
+
readonly cancelled: "Certo, não lancei nada.";
|
|
689
|
+
readonly categoryChoice: "Em qual categoria?";
|
|
690
|
+
readonly categoryInvalid: "Escolha uma categoria da lista acima.";
|
|
691
|
+
readonly confirm: "Confere a conta?";
|
|
692
|
+
readonly dueDate: "Qual o vencimento? Por exemplo: 20/11, 20/11/2026, hoje ou amanhã.";
|
|
693
|
+
readonly dueDateInvalid: "Não entendi a data. Use 20/11, 20/11/2026, hoje ou amanhã.";
|
|
694
|
+
readonly dueDay: "Em que dia do mês ela vence? De 1 a 31.";
|
|
695
|
+
readonly dueDayInvalid: "Digite o dia do mês, de 1 a 31.";
|
|
696
|
+
readonly kindChoice: "Que tipo de conta você quer lançar?";
|
|
697
|
+
readonly kindInvalid: "Escolha Fixa (todo mês) ou Variável (uma vez só).";
|
|
698
|
+
readonly name: "Qual o nome da conta? Por exemplo: Aluguel do galpão.";
|
|
699
|
+
readonly nameInvalid: "O nome precisa ter de 2 a 80 letras. Digite de novo.";
|
|
700
|
+
readonly noCategories: "Não há categoria ativa para lançar. Cadastre uma em Contas, no painel.";
|
|
701
|
+
readonly recurrenceChoice: "Com que frequência ela vence?";
|
|
702
|
+
readonly recurrenceInvalid: "Escolha a frequência da lista acima.";
|
|
703
|
+
readonly saved: (name: string) => string;
|
|
704
|
+
};
|
|
705
|
+
type ExpenseConversationDraft = {
|
|
706
|
+
readonly amount?: string;
|
|
707
|
+
readonly categoryId?: string;
|
|
708
|
+
readonly categoryName?: string;
|
|
709
|
+
readonly dueDate?: string;
|
|
710
|
+
readonly dueDay?: number;
|
|
711
|
+
readonly kind?: ExpenseKind;
|
|
712
|
+
readonly name?: string;
|
|
713
|
+
readonly recurrence?: ExpenseRecurrence;
|
|
714
|
+
};
|
|
715
|
+
type ExpenseConversationState = {
|
|
716
|
+
readonly draft: ExpenseConversationDraft;
|
|
717
|
+
readonly step: ExpenseConversationStep;
|
|
718
|
+
};
|
|
719
|
+
type ExpenseConversationOption = {
|
|
720
|
+
readonly id: string;
|
|
721
|
+
readonly title: string;
|
|
722
|
+
};
|
|
723
|
+
/** O que o canal manda: texto e, quando há, botões/lista (o canal decide como desenhar). */
|
|
724
|
+
type ExpenseConversationPrompt = {
|
|
725
|
+
readonly options?: readonly ExpenseConversationOption[];
|
|
726
|
+
readonly text: string;
|
|
727
|
+
};
|
|
728
|
+
/** Pronto para o caso de uso de criar conta (o host acrescenta empresa, autor, canal e hoje). */
|
|
729
|
+
type ExpenseConversationSubmit = {
|
|
730
|
+
readonly categoryId: string;
|
|
731
|
+
readonly dueDate?: string;
|
|
732
|
+
readonly dueDay?: number;
|
|
733
|
+
readonly expectedAmount: string;
|
|
734
|
+
readonly kind: ExpenseKind;
|
|
735
|
+
readonly name: string;
|
|
736
|
+
readonly recurrence?: ExpenseRecurrence;
|
|
737
|
+
};
|
|
738
|
+
type ExpenseConversationResult = {
|
|
739
|
+
readonly prompt: ExpenseConversationPrompt;
|
|
740
|
+
readonly state: ExpenseConversationState;
|
|
741
|
+
readonly submit?: ExpenseConversationSubmit;
|
|
742
|
+
};
|
|
743
|
+
type ExpenseConversationCategory = {
|
|
744
|
+
readonly id: string;
|
|
745
|
+
readonly name: string;
|
|
746
|
+
};
|
|
747
|
+
/** Começa a conversa: pergunta fixa ou variável. */
|
|
748
|
+
declare function startExpenseConversation(): ExpenseConversationResult;
|
|
749
|
+
/** A resposta escolhe uma opção pelo id, pelo número da posição (1, 2…) ou pelo título sem emoji. */
|
|
750
|
+
declare function matchConversationOption(input: string, options: readonly ExpenseConversationOption[]): ExpenseConversationOption | undefined;
|
|
751
|
+
/** O resumo antes do Confirmar. */
|
|
752
|
+
declare function describeExpenseDraft(draft: ExpenseConversationDraft): string;
|
|
753
|
+
/**
|
|
754
|
+
* Avança um passo. `input` é o texto digitado ou o id do botão. `categories` são as ativas que podem ser oferecidas
|
|
755
|
+
* (o host já tirou as que exigem dado que o chat não colhe). `today` é o dia civil da empresa.
|
|
756
|
+
*/
|
|
757
|
+
declare function advanceExpenseConversation(params: {
|
|
758
|
+
readonly categories: readonly ExpenseConversationCategory[];
|
|
759
|
+
readonly input: string;
|
|
760
|
+
readonly state: ExpenseConversationState;
|
|
761
|
+
readonly today: string;
|
|
762
|
+
}): ExpenseConversationResult;
|
|
763
|
+
|
|
764
|
+
type SummarizableOccurrence = {
|
|
765
|
+
readonly categoryId?: string;
|
|
766
|
+
readonly categoryName?: string;
|
|
767
|
+
readonly dueDate: string;
|
|
768
|
+
readonly expectedAmount: string;
|
|
769
|
+
readonly paidAmount: string | null;
|
|
770
|
+
readonly status: ExpenseOccurrenceStatus;
|
|
771
|
+
};
|
|
772
|
+
type ExpenseCategoryTotal = {
|
|
773
|
+
readonly categoryId: string;
|
|
774
|
+
readonly categoryName: string;
|
|
775
|
+
readonly expected: string;
|
|
776
|
+
readonly open: string;
|
|
777
|
+
readonly paid: string;
|
|
778
|
+
};
|
|
779
|
+
type ExpensePeriodSummary = {
|
|
780
|
+
readonly count: {
|
|
781
|
+
readonly open: number;
|
|
782
|
+
readonly overdue: number;
|
|
783
|
+
readonly paid: number;
|
|
784
|
+
readonly canceled: number;
|
|
785
|
+
};
|
|
786
|
+
/** Previsto das abertas + pago das pagas (o "custo do período"). Cancelada não entra. */
|
|
787
|
+
readonly total: string;
|
|
788
|
+
readonly open: string;
|
|
789
|
+
readonly overdue: string;
|
|
790
|
+
readonly paid: string;
|
|
791
|
+
readonly byCategory: readonly ExpenseCategoryTotal[];
|
|
792
|
+
};
|
|
793
|
+
/** A situação de uma ocorrência aberta em relação a `today`. */
|
|
794
|
+
declare function dueStateOf(dueDate: string, today: string): ExpenseDueState;
|
|
795
|
+
declare function summarizeExpenseOccurrences(occurrences: readonly SummarizableOccurrence[], today: string): ExpensePeriodSummary;
|
|
796
|
+
|
|
797
|
+
export { ALLOCATABLE_COST_GROUPS, ALLOCATION_CRITERIA, type AllocatableCostGroup, type AllocationCriterion, type AllocationExpense, type AllocationResult, type AllocationSettings, type AllocationShare, type AllocationUnallocated, type AllocationUnit, type AmountChangeLike, type ClosedMonthResult, DEFAULT_ALLOCATION_SETTINGS, DEFAULT_EXPENSE_CATEGORIES, DEFAULT_EXPENSE_MAIL_PALETTE, DEFAULT_EXPENSE_REMINDER_WHATSAPP_TEXT, DEFAULT_EXPENSE_SUMMARY_WHATSAPP_TEXT, DEFAULT_OUT_OF_PATTERN_THRESHOLD_PERCENT, DEFAULT_REMINDER_SETTINGS, EXPENSE_AMOUNT_CHANGE_KINDS, EXPENSE_CHANNELS, EXPENSE_CONVERSATION_ANSWER, EXPENSE_CONVERSATION_STEPS, EXPENSE_CONVERSATION_TEXT, EXPENSE_COST_GROUPS, EXPENSE_ERROR, EXPENSE_ERROR_MESSAGES, EXPENSE_GENERATION_WINDOW_MONTHS, EXPENSE_KINDS, EXPENSE_NAME_MAX_LENGTH, EXPENSE_NAME_MIN_LENGTH, EXPENSE_OCCURRENCE_STATUSES, EXPENSE_RECURRENCES, EXPENSE_RECURRENCE_OPTIONS, EXPENSE_RESULT_FILTER_KEYS, type Expense, type ExpenseAmountChange, type ExpenseAmountChangeKind, type ExpenseCategory, type ExpenseCategoryTotal, type ExpenseChannel, type ExpenseConversationCategory, type ExpenseConversationDraft, type ExpenseConversationOption, type ExpenseConversationPrompt, type ExpenseConversationResult, type ExpenseConversationState, type ExpenseConversationStep, type ExpenseConversationSubmit, type ExpenseCostGroup, type ExpenseDueState, ExpenseError, type ExpenseErrorCode, type ExpenseErrorKey, type ExpenseKind, type ExpenseMailPalette, type ExpenseOccurrence, type ExpenseOccurrenceAction, type ExpenseOccurrenceListItem, type ExpenseOccurrenceStatus, type ExpensePeriodSummary, type ExpenseRecurrence, type ExpenseReminderFacts, type ExpenseResultFilters, type ExpenseScheduleSlot, type ExpenseSummaryLine, type ExpenseTextOptions, FORECAST_BAND_FLOOR_PERCENT, FORECAST_FULL_MONTHS, FORECAST_MIN_MONTHS, type ForecastInput, type ForecastRange, type ForecastResult, NO_ASSET_ID, NO_CUSTOMER_ID, OUT_OF_PATTERN_MONTHS, type OutOfPatternAlert, type OutOfPatternItem, type OutOfPatternKind, type PlannedAmountChange, type PlannedExpenseOccurrence, REMINDER_CHANNELS, REMINDER_KINDS, type ReminderChannel, type ReminderKind, type ReminderPersonFacts, type ReminderRecipient, type ReminderRecipientChoice, type ReminderRecipientReason, type ReminderSettings, type ResolveExpenseDueDateParams, type SummarizableOccurrence, type UnallocatedReason, addCivilDays, addCompetenceMonths, advanceExpenseConversation, allocateExpenses, amountInEffect, belongsToDailySummary, buildExpenseDailySummaryValues, buildExpenseMailButtonHtml, buildExpenseReminderValues, buildExpenseSummaryTableHtml, canTransitionOccurrence, chooseReminderRecipients, civilDateInTimeZone, civilDaysBetween, competenceBounds, competenceIndex, competenceOfDate, daysUntilDue, describeDueSituation, describeExpenseDraft, detectOutOfPattern, distributeByWeight, divideHalfUp, dueStateOf, effectiveReminderChannels, escapeHtml, expenseMatchesFilters, forecastNextMonth, formatBrl, formatCents, formatCivilDateBr, formatCompetenceBr, hasResultFilters, hourInTimeZone, isBarredFromReminders, isCivilDate, isCompetence, isDirectExpenseIntent, isExpenseError, isFieldStaffFinanceIntent, isReminderHour, listExpenseCompetenceWindow, matchConversationOption, normalizeChatText, normalizeMoney, parseExpenseAmount, parseExpenseDueDate, parseExpenseDueDay, parseMoneyToCents, parseSettlementReply, parseStoredMoneyToCents, personalReminderChannels, planAmountChange, planFixedExpenseOccurrences, reminderKindOn, renderPlainTemplate, resolveExpenseDueDate, resolveExpenseSlots, startExpenseConversation, summarizeExpenseOccurrences, unitMatchesFilters };
|