@adatechnology/expense-contracts 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,1536 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/types.ts
5
+ var EXPENSE_KINDS = [
6
+ "fixed",
7
+ "variable"
8
+ ];
9
+ var EXPENSE_RECURRENCES = [
10
+ "monthly",
11
+ "bimonthly",
12
+ "quarterly",
13
+ "yearly",
14
+ "fortnightly"
15
+ ];
16
+ var EXPENSE_OCCURRENCE_STATUSES = [
17
+ "open",
18
+ "paid",
19
+ "canceled"
20
+ ];
21
+ var EXPENSE_AMOUNT_CHANGE_KINDS = [
22
+ "adjustment",
23
+ "correction"
24
+ ];
25
+ var EXPENSE_CHANNELS = [
26
+ "panel",
27
+ "whatsapp",
28
+ "email",
29
+ "api"
30
+ ];
31
+ var EXPENSE_COST_GROUPS = [
32
+ "asset_fixed",
33
+ "per_distance",
34
+ "administrative",
35
+ "in_unit"
36
+ ];
37
+ var DEFAULT_EXPENSE_CATEGORIES = [
38
+ {
39
+ costGroup: "administrative",
40
+ name: "Aluguel"
41
+ },
42
+ {
43
+ costGroup: "administrative",
44
+ name: "Energia"
45
+ },
46
+ {
47
+ costGroup: "administrative",
48
+ name: "\xC1gua"
49
+ },
50
+ {
51
+ costGroup: "administrative",
52
+ name: "Internet e telefone"
53
+ },
54
+ {
55
+ costGroup: "administrative",
56
+ name: "Sal\xE1rios e encargos"
57
+ },
58
+ {
59
+ costGroup: "administrative",
60
+ name: "Impostos e taxas"
61
+ },
62
+ {
63
+ costGroup: "administrative",
64
+ name: "Fornecedores"
65
+ },
66
+ {
67
+ costGroup: "administrative",
68
+ name: "Manuten\xE7\xE3o"
69
+ },
70
+ {
71
+ costGroup: "administrative",
72
+ name: "Marketing"
73
+ },
74
+ {
75
+ costGroup: "administrative",
76
+ name: "Cart\xE3o de cr\xE9dito"
77
+ },
78
+ {
79
+ costGroup: "administrative",
80
+ name: "Empr\xE9stimos e financiamentos"
81
+ },
82
+ {
83
+ costGroup: "administrative",
84
+ name: "Outros"
85
+ }
86
+ ];
87
+
88
+ // src/errors.ts
89
+ var EXPENSE_ERROR = {
90
+ AMOUNT_INVALID: {
91
+ code: "EXPENSE_AMOUNT_INVALID",
92
+ status: 400
93
+ },
94
+ CATEGORY_INACTIVE: {
95
+ code: "EXPENSE_CATEGORY_INACTIVE",
96
+ status: 409
97
+ },
98
+ CATEGORY_NAME_TAKEN: {
99
+ code: "EXPENSE_CATEGORY_NAME_TAKEN",
100
+ status: 409
101
+ },
102
+ CATEGORY_NOT_FOUND: {
103
+ code: "EXPENSE_CATEGORY_NOT_FOUND",
104
+ status: 404
105
+ },
106
+ EXPENSE_NOT_FOUND: {
107
+ code: "EXPENSE_NOT_FOUND",
108
+ status: 404
109
+ },
110
+ INVALID_SCHEDULE: {
111
+ code: "EXPENSE_INVALID_SCHEDULE",
112
+ status: 400
113
+ },
114
+ OCCURRENCE_NOT_FOUND: {
115
+ code: "EXPENSE_OCCURRENCE_NOT_FOUND",
116
+ status: 404
117
+ },
118
+ OCCURRENCE_TRANSITION_NOT_ALLOWED: {
119
+ code: "EXPENSE_OCCURRENCE_TRANSITION_NOT_ALLOWED",
120
+ status: 409
121
+ },
122
+ UNAUTHENTICATED: {
123
+ code: "EXPENSE_UNAUTHENTICATED",
124
+ status: 401
125
+ }
126
+ };
127
+ var EXPENSE_ERROR_MESSAGES = {
128
+ AMOUNT_INVALID: "Valor inv\xE1lido.",
129
+ CATEGORY_INACTIVE: "A categoria est\xE1 desligada.",
130
+ CATEGORY_NAME_TAKEN: "J\xE1 existe uma categoria com esse nome.",
131
+ CATEGORY_NOT_FOUND: "Categoria n\xE3o encontrada.",
132
+ EXPENSE_NOT_FOUND: "Conta n\xE3o encontrada.",
133
+ INVALID_SCHEDULE: "Vencimento ou recorr\xEAncia inv\xE1lidos.",
134
+ OCCURRENCE_NOT_FOUND: "Vencimento n\xE3o encontrado.",
135
+ OCCURRENCE_TRANSITION_NOT_ALLOWED: "Esse vencimento n\xE3o permite essa a\xE7\xE3o no estado atual.",
136
+ UNAUTHENTICATED: "Identifica\xE7\xE3o da empresa ausente."
137
+ };
138
+ var ExpenseError = class extends Error {
139
+ static {
140
+ __name(this, "ExpenseError");
141
+ }
142
+ code;
143
+ status;
144
+ /** Mesmo valor de `status`, no nome que o `@adatechnology/module-http` reconhece como erro de domínio. */
145
+ statusCode;
146
+ constructor(key, message) {
147
+ super(message ?? EXPENSE_ERROR_MESSAGES[key]);
148
+ this.name = "ExpenseError";
149
+ this.code = EXPENSE_ERROR[key].code;
150
+ this.status = EXPENSE_ERROR[key].status;
151
+ this.statusCode = EXPENSE_ERROR[key].status;
152
+ }
153
+ };
154
+ function isExpenseError(error) {
155
+ return error instanceof ExpenseError;
156
+ }
157
+ __name(isExpenseError, "isExpenseError");
158
+
159
+ // src/money.ts
160
+ var MONEY_PATTERN = /^(\d+)(?:\.(\d{1,2}))?$/;
161
+ function parseMoneyToCents(value) {
162
+ const match = MONEY_PATTERN.exec(value.trim());
163
+ if (match?.[1] === void 0) return null;
164
+ return BigInt(match[1]) * 100n + BigInt((match[2] ?? "").padEnd(2, "0") || "0");
165
+ }
166
+ __name(parseMoneyToCents, "parseMoneyToCents");
167
+ function formatCents(cents2) {
168
+ const negative = cents2 < 0n;
169
+ const absolute = negative ? -cents2 : cents2;
170
+ const whole = absolute / 100n;
171
+ const fraction = (absolute % 100n).toString().padStart(2, "0");
172
+ return `${negative ? "-" : ""}${whole}.${fraction}`;
173
+ }
174
+ __name(formatCents, "formatCents");
175
+ function normalizeMoney(value) {
176
+ const cents2 = parseMoneyToCents(value);
177
+ return cents2 === null ? null : formatCents(cents2);
178
+ }
179
+ __name(normalizeMoney, "normalizeMoney");
180
+ function parseStoredMoneyToCents(value) {
181
+ return parseMoneyToCents(value.trim().replace(/^(\d+\.\d{2})0{1,2}$/, "$1"));
182
+ }
183
+ __name(parseStoredMoneyToCents, "parseStoredMoneyToCents");
184
+ function divideHalfUp(numerator, denominator) {
185
+ if (denominator === 0n) throw new RangeError("divis\xE3o por zero");
186
+ return (2n * numerator + denominator) / (2n * denominator);
187
+ }
188
+ __name(divideHalfUp, "divideHalfUp");
189
+ function distributeByWeight(total, weights) {
190
+ const totalWeight = weights.reduce((sum, weight) => sum + weight, 0n);
191
+ if (totalWeight === 0n || total === 0n) return weights.map(() => 0n);
192
+ const parts = weights.map((weight) => total * weight / totalWeight);
193
+ const remainder = total - parts.reduce((sum, part) => sum + part, 0n);
194
+ if (remainder === 0n) return parts;
195
+ let heaviest = 0;
196
+ weights.forEach((weight, index) => {
197
+ if (weight > (weights[heaviest] ?? 0n)) heaviest = index;
198
+ });
199
+ parts[heaviest] = (parts[heaviest] ?? 0n) + remainder;
200
+ return parts;
201
+ }
202
+ __name(distributeByWeight, "distributeByWeight");
203
+ function formatBrl(amount) {
204
+ const cents2 = typeof amount === "bigint" ? amount : parseSignedMoneyToCents(amount);
205
+ if (cents2 === null) throw new Error(`valor inv\xE1lido: ${String(amount)}`);
206
+ const negative = cents2 < 0n;
207
+ const absolute = negative ? -cents2 : cents2;
208
+ const whole = (absolute / 100n).toString().replace(/\B(?=(\d{3})+(?!\d))/gu, ".");
209
+ return `${negative ? "-" : ""}R$ ${whole},${(absolute % 100n).toString().padStart(2, "0")}`;
210
+ }
211
+ __name(formatBrl, "formatBrl");
212
+ function parseSignedMoneyToCents(value) {
213
+ const trimmed = value.trim();
214
+ if (trimmed.startsWith("-")) {
215
+ const cents2 = parseMoneyToCents(trimmed.slice(1));
216
+ return cents2 === null ? null : -cents2;
217
+ }
218
+ return parseMoneyToCents(trimmed);
219
+ }
220
+ __name(parseSignedMoneyToCents, "parseSignedMoneyToCents");
221
+ function isCivilDate(value) {
222
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
223
+ if (match === null) return false;
224
+ const date = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));
225
+ return date.toISOString().slice(0, 10) === value;
226
+ }
227
+ __name(isCivilDate, "isCivilDate");
228
+ function isCompetence(value) {
229
+ return /^\d{4}-(0[1-9]|1[0-2])$/u.test(value);
230
+ }
231
+ __name(isCompetence, "isCompetence");
232
+ function addCivilDays(isoDate, days) {
233
+ const date = /* @__PURE__ */ new Date(`${isoDate}T00:00:00Z`);
234
+ date.setUTCDate(date.getUTCDate() + days);
235
+ return date.toISOString().slice(0, 10);
236
+ }
237
+ __name(addCivilDays, "addCivilDays");
238
+ function civilDateInTimeZone(instant, timeZone = "America/Sao_Paulo") {
239
+ const parts = new Intl.DateTimeFormat("en-CA", {
240
+ day: "2-digit",
241
+ month: "2-digit",
242
+ timeZone,
243
+ year: "numeric"
244
+ }).formatToParts(instant);
245
+ const pick = /* @__PURE__ */ __name((type) => parts.find((part) => part.type === type)?.value ?? "", "pick");
246
+ return `${pick("year")}-${pick("month")}-${pick("day")}`;
247
+ }
248
+ __name(civilDateInTimeZone, "civilDateInTimeZone");
249
+ function hourInTimeZone(instant, timeZone = "America/Sao_Paulo") {
250
+ const hour = new Intl.DateTimeFormat("en-US", {
251
+ hour: "2-digit",
252
+ hourCycle: "h23",
253
+ timeZone
254
+ }).format(instant);
255
+ return Number(hour) % 24;
256
+ }
257
+ __name(hourInTimeZone, "hourInTimeZone");
258
+
259
+ // src/schedule.ts
260
+ var EXPENSE_GENERATION_WINDOW_MONTHS = 4;
261
+ var FORTNIGHT_FIRST_DAY = 15;
262
+ var MONTHS_BETWEEN = {
263
+ bimonthly: 2,
264
+ fortnightly: 1,
265
+ monthly: 1,
266
+ quarterly: 3,
267
+ yearly: 12
268
+ };
269
+ function parseCompetence(competence) {
270
+ const match = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(competence);
271
+ if (match === null) throw new Error(`competence must be yyyy-mm: ${competence}`);
272
+ return {
273
+ month: Number(match[2]),
274
+ year: Number(match[1])
275
+ };
276
+ }
277
+ __name(parseCompetence, "parseCompetence");
278
+ function formatCompetence(year, month) {
279
+ return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}`;
280
+ }
281
+ __name(formatCompetence, "formatCompetence");
282
+ function lastDayOfMonth(year, month) {
283
+ return new Date(Date.UTC(year, month, 0)).getUTCDate();
284
+ }
285
+ __name(lastDayOfMonth, "lastDayOfMonth");
286
+ function competenceIndex(competence) {
287
+ const { month, year } = parseCompetence(competence);
288
+ return year * 12 + (month - 1);
289
+ }
290
+ __name(competenceIndex, "competenceIndex");
291
+ function addCompetenceMonths(competence, months) {
292
+ const index = competenceIndex(competence) + months;
293
+ return formatCompetence(Math.floor(index / 12), index % 12 + 1);
294
+ }
295
+ __name(addCompetenceMonths, "addCompetenceMonths");
296
+ function resolveExpenseDueDate(params) {
297
+ if (!Number.isInteger(params.dueDay) || params.dueDay < 1 || params.dueDay > 31) {
298
+ throw new Error(`dueDay must be between 1 and 31: ${params.dueDay}`);
299
+ }
300
+ const { month, year } = parseCompetence(params.competence);
301
+ const day = Math.min(params.dueDay, lastDayOfMonth(year, month));
302
+ return `${params.competence}-${String(day).padStart(2, "0")}`;
303
+ }
304
+ __name(resolveExpenseDueDate, "resolveExpenseDueDate");
305
+ function competenceOfDate(date) {
306
+ const match = /^(\d{4}-\d{2})-\d{2}$/.exec(date);
307
+ if (match?.[1] === void 0) throw new Error(`date must be yyyy-mm-dd: ${date}`);
308
+ parseCompetence(match[1]);
309
+ return match[1];
310
+ }
311
+ __name(competenceOfDate, "competenceOfDate");
312
+ function competenceBounds(competence) {
313
+ const { month, year } = parseCompetence(competence);
314
+ return {
315
+ from: `${competence}-01`,
316
+ to: `${competence}-${String(lastDayOfMonth(year, month)).padStart(2, "0")}`
317
+ };
318
+ }
319
+ __name(competenceBounds, "competenceBounds");
320
+ function listExpenseCompetenceWindow(today, months = EXPENSE_GENERATION_WINDOW_MONTHS) {
321
+ const start = competenceIndex(competenceOfDate(today));
322
+ return Array.from({
323
+ length: months
324
+ }, (_, offset) => {
325
+ const index = start + offset;
326
+ return formatCompetence(Math.floor(index / 12), index % 12 + 1);
327
+ });
328
+ }
329
+ __name(listExpenseCompetenceWindow, "listExpenseCompetenceWindow");
330
+ function resolveExpenseSlots(params) {
331
+ const distance = competenceIndex(params.competence) - competenceIndex(params.anchorCompetence);
332
+ const step = MONTHS_BETWEEN[params.recurrence];
333
+ if (distance < 0 || distance % step !== 0) return [];
334
+ const total = params.installmentsTotal ?? null;
335
+ const perPeriod = params.recurrence === "fortnightly" ? 2 : 1;
336
+ const base = distance / step * perPeriod;
337
+ const numberOf = /* @__PURE__ */ __name((slot) => total === null ? null : base + slot, "numberOf");
338
+ const slots = [];
339
+ if (params.recurrence === "fortnightly") {
340
+ slots.push({
341
+ dueDate: resolveExpenseDueDate({
342
+ competence: params.competence,
343
+ dueDay: FORTNIGHT_FIRST_DAY
344
+ }),
345
+ installmentNumber: numberOf(1),
346
+ slot: 1
347
+ }, {
348
+ dueDate: resolveExpenseDueDate({
349
+ competence: params.competence,
350
+ dueDay: 31
351
+ }),
352
+ installmentNumber: numberOf(2),
353
+ slot: 2
354
+ });
355
+ } else {
356
+ if (params.dueDay === null) throw new Error("dueDay is required for a non-fortnightly recurrence");
357
+ slots.push({
358
+ dueDate: resolveExpenseDueDate({
359
+ competence: params.competence,
360
+ dueDay: params.dueDay
361
+ }),
362
+ installmentNumber: numberOf(1),
363
+ slot: 1
364
+ });
365
+ }
366
+ return total === null ? slots : slots.filter((item) => (item.installmentNumber ?? 0) <= total);
367
+ }
368
+ __name(resolveExpenseSlots, "resolveExpenseSlots");
369
+ function planFixedExpenseOccurrences(params) {
370
+ return listExpenseCompetenceWindow(params.today, params.windowMonths).flatMap((competence) => resolveExpenseSlots({
371
+ anchorCompetence: params.anchorCompetence,
372
+ competence,
373
+ dueDay: params.dueDay,
374
+ installmentsTotal: params.installmentsTotal ?? null,
375
+ recurrence: params.recurrence
376
+ }).map((slot) => ({
377
+ ...slot,
378
+ competence
379
+ })));
380
+ }
381
+ __name(planFixedExpenseOccurrences, "planFixedExpenseOccurrences");
382
+
383
+ // src/amount.ts
384
+ function byStartThenCreation(left, right) {
385
+ if (left.effectiveCompetence !== right.effectiveCompetence) {
386
+ return left.effectiveCompetence < right.effectiveCompetence ? -1 : 1;
387
+ }
388
+ const leftCreated = left.createdAt ?? "";
389
+ const rightCreated = right.createdAt ?? "";
390
+ if (leftCreated === rightCreated) return 0;
391
+ return leftCreated < rightCreated ? -1 : 1;
392
+ }
393
+ __name(byStartThenCreation, "byStartThenCreation");
394
+ function amountInEffect(baseAmount, changes, competence) {
395
+ let amount = baseAmount;
396
+ for (const change of [
397
+ ...changes
398
+ ].sort(byStartThenCreation)) {
399
+ if (change.effectiveCompetence <= competence) amount = change.newAmount;
400
+ }
401
+ return amount;
402
+ }
403
+ __name(amountInEffect, "amountInEffect");
404
+ function planAmountChange(input) {
405
+ const newAmount = normalizeMoney(input.newAmount);
406
+ if (newAmount === null) throw new RangeError(`valor inv\xE1lido: ${input.newAmount}`);
407
+ if (input.kind === "correction") {
408
+ const competence = input.correctionCompetence;
409
+ if (competence === void 0 || !/^\d{4}-(0[1-9]|1[0-2])$/u.test(competence)) {
410
+ throw new RangeError("correctionCompetence precisa ser yyyy-mm");
411
+ }
412
+ const starts = input.changes.map((change) => change.effectiveCompetence);
413
+ const segmentStart = starts.filter((start) => start <= competence).sort().at(-1) ?? "0000-01";
414
+ const segmentEnd = starts.filter((start) => start > competence).sort().at(0) ?? null;
415
+ const previousAmount2 = amountInEffect(input.baseAmount, input.changes, competence);
416
+ if (normalizeMoney(previousAmount2) === newAmount) return null;
417
+ return {
418
+ effectiveCompetence: segmentStart,
419
+ kind: "correction",
420
+ newAmount,
421
+ onlyNotDue: false,
422
+ previousAmount: previousAmount2,
423
+ untilCompetence: segmentEnd
424
+ };
425
+ }
426
+ const effectiveCompetence = input.effectiveFrom ?? competenceOfDate(input.today);
427
+ if (!/^\d{4}-(0[1-9]|1[0-2])$/u.test(effectiveCompetence)) {
428
+ throw new RangeError("effectiveFrom precisa ser yyyy-mm");
429
+ }
430
+ const previousAmount = amountInEffect(input.baseAmount, input.changes, effectiveCompetence);
431
+ if (normalizeMoney(previousAmount) === newAmount) return null;
432
+ return {
433
+ effectiveCompetence,
434
+ kind: "adjustment",
435
+ newAmount,
436
+ onlyNotDue: true,
437
+ previousAmount,
438
+ untilCompetence: null
439
+ };
440
+ }
441
+ __name(planAmountChange, "planAmountChange");
442
+
443
+ // src/occurrenceTransition.ts
444
+ var ALLOWED = {
445
+ cancel: "open",
446
+ reopen: "paid",
447
+ settle: "open"
448
+ };
449
+ function canTransitionOccurrence(status, action) {
450
+ return ALLOWED[action] === status;
451
+ }
452
+ __name(canTransitionOccurrence, "canTransitionOccurrence");
453
+
454
+ // src/allocation.ts
455
+ var ALLOCATABLE_COST_GROUPS = [
456
+ "asset_fixed",
457
+ "per_distance",
458
+ "administrative"
459
+ ];
460
+ var ALLOCATION_CRITERIA = [
461
+ "per_distance",
462
+ "per_unit_day",
463
+ "per_revenue",
464
+ "equal"
465
+ ];
466
+ var DEFAULT_ALLOCATION_SETTINGS = {
467
+ administrative: "per_revenue",
468
+ asset_fixed: "per_distance",
469
+ per_distance: "per_distance"
470
+ };
471
+ function allocateExpenses(input) {
472
+ const units = [
473
+ ...input.units
474
+ ].sort(compareUnits);
475
+ const excesses = [];
476
+ const shares = [];
477
+ const unallocated = [];
478
+ for (const expense of input.expenses) {
479
+ const considered = requireCents(expense.amount, `amount of ${expense.occurrenceId}`);
480
+ let amount = considered;
481
+ let group;
482
+ let assetId = expense.assetId;
483
+ if (expense.costGroup === "in_unit") {
484
+ const included = requireCents(expense.includedUnitsAmount ?? "0", `includedUnitsAmount of ${expense.occurrenceId}`);
485
+ amount = considered > included ? considered - included : 0n;
486
+ if (amount === 0n) continue;
487
+ excesses.push({
488
+ amount: formatCents(amount),
489
+ occurrenceId: expense.occurrenceId
490
+ });
491
+ group = "administrative";
492
+ assetId = null;
493
+ } else {
494
+ group = expense.costGroup;
495
+ }
496
+ if (amount === 0n) continue;
497
+ const eligible = assetId === null ? units : units.filter((unit) => unit.assetId === assetId);
498
+ if (assetId !== null && eligible.length === 0) {
499
+ unallocated.push({
500
+ amount: formatCents(amount),
501
+ assetId,
502
+ occurrenceId: expense.occurrenceId,
503
+ reason: "asset_without_units"
504
+ });
505
+ continue;
506
+ }
507
+ const criterion = input.settings[group];
508
+ const weights = eligible.map((unit) => weightOf(unit, criterion));
509
+ if (weights.every((weight) => weight === 0n)) {
510
+ unallocated.push({
511
+ amount: formatCents(amount),
512
+ assetId,
513
+ occurrenceId: expense.occurrenceId,
514
+ reason: "no_unit_weight"
515
+ });
516
+ continue;
517
+ }
518
+ const scope = assetId === null ? "general" : "asset";
519
+ distributeByWeight(amount, weights).forEach((part, index) => {
520
+ const unit = eligible[index];
521
+ if (part === 0n || unit === void 0) return;
522
+ shares.push({
523
+ amount: formatCents(part),
524
+ occurrenceId: expense.occurrenceId,
525
+ scope,
526
+ unitId: unit.unitId
527
+ });
528
+ });
529
+ }
530
+ return {
531
+ excesses,
532
+ shares,
533
+ unallocated
534
+ };
535
+ }
536
+ __name(allocateExpenses, "allocateExpenses");
537
+ function compareUnits(left, right) {
538
+ if (left.completedOn !== right.completedOn) return left.completedOn < right.completedOn ? -1 : 1;
539
+ if (left.unitId === right.unitId) return 0;
540
+ return left.unitId < right.unitId ? -1 : 1;
541
+ }
542
+ __name(compareUnits, "compareUnits");
543
+ function weightOf(unit, criterion) {
544
+ switch (criterion) {
545
+ case "equal":
546
+ return 1n;
547
+ case "per_distance":
548
+ return positiveWhole(unit.distanceMeters);
549
+ case "per_unit_day":
550
+ return positiveWhole(unit.daysCount);
551
+ case "per_revenue":
552
+ return revenueWeight(unit.revenue);
553
+ }
554
+ }
555
+ __name(weightOf, "weightOf");
556
+ function positiveWhole(value) {
557
+ return Number.isFinite(value) && value > 0 ? BigInt(Math.round(value)) : 0n;
558
+ }
559
+ __name(positiveWhole, "positiveWhole");
560
+ function revenueWeight(value) {
561
+ const match = /^(\d+)(?:\.(\d{1,4}))?$/.exec(value.trim());
562
+ if (match?.[1] === void 0) return 0n;
563
+ return BigInt(match[1]) * 10000n + BigInt((match[2] ?? "").padEnd(4, "0"));
564
+ }
565
+ __name(revenueWeight, "revenueWeight");
566
+ function requireCents(value, label) {
567
+ const cents2 = parseStoredMoneyToCents(value);
568
+ if (cents2 === null) throw new Error(`expense allocation: invalid money in ${label}`);
569
+ return cents2;
570
+ }
571
+ __name(requireCents, "requireCents");
572
+
573
+ // src/forecast.ts
574
+ var FORECAST_MIN_MONTHS = 3;
575
+ var FORECAST_FULL_MONTHS = 6;
576
+ var FORECAST_BAND_FLOOR_PERCENT = {
577
+ limited: 30n,
578
+ ok: 15n
579
+ };
580
+ function parseAmount(value, field) {
581
+ const cents2 = parseMoneyToCents(value);
582
+ if (cents2 === null) throw new RangeError(`${field} inv\xE1lido: '${value}'`);
583
+ return cents2;
584
+ }
585
+ __name(parseAmount, "parseAmount");
586
+ function minOf(values) {
587
+ return values.reduce((a, b) => b < a ? b : a);
588
+ }
589
+ __name(minOf, "minOf");
590
+ function maxOf(values) {
591
+ return values.reduce((a, b) => b > a ? b : a);
592
+ }
593
+ __name(maxOf, "maxOf");
594
+ function isDataMonth(month) {
595
+ return month.businessDays > 0n && (month.revenue > 0n || month.directCost > 0n);
596
+ }
597
+ __name(isDataMonth, "isDataMonth");
598
+ function estimate(months, pick, nextDays, floorPercent) {
599
+ const totalDays = months.reduce((sum, m) => sum + m.businessDays, 0n);
600
+ const total = months.reduce((sum, m) => sum + pick(m), 0n);
601
+ const expected = divideHalfUp(total * nextDays, totalDays);
602
+ const projected = months.map((m) => divideHalfUp(pick(m) * nextDays, m.businessDays));
603
+ const floor = divideHalfUp(expected * floorPercent, 100n);
604
+ const lowFloor = expected - floor;
605
+ const lowObserved = minOf(projected);
606
+ const highFloor = expected + floor;
607
+ const highObserved = maxOf(projected);
608
+ return {
609
+ expected,
610
+ max: highObserved > highFloor ? highObserved : highFloor,
611
+ min: lowObserved < lowFloor ? lowObserved : lowFloor
612
+ };
613
+ }
614
+ __name(estimate, "estimate");
615
+ function toRange(value) {
616
+ return {
617
+ expected: formatCents(value.expected),
618
+ max: formatCents(value.max),
619
+ min: formatCents(value.min)
620
+ };
621
+ }
622
+ __name(toRange, "toRange");
623
+ function forecastNextMonth(input) {
624
+ if (!Number.isInteger(input.nextMonthBusinessDays) || input.nextMonthBusinessDays < 0) throw new RangeError(`dias \xFAteis do m\xEAs previsto inv\xE1lidos: ${input.nextMonthBusinessDays}`);
625
+ const recurring = parseAmount(input.recurringExpenses, "recurringExpenses");
626
+ const window = [
627
+ ...input.history
628
+ ].sort((a, b) => a.month < b.month ? 1 : a.month > b.month ? -1 : 0).slice(0, FORECAST_FULL_MONTHS);
629
+ const months = window.map((m) => {
630
+ if (!Number.isInteger(m.businessDays) || m.businessDays < 0) throw new RangeError(`dias \xFAteis inv\xE1lidos em ${m.month}: ${m.businessDays}`);
631
+ return {
632
+ businessDays: BigInt(m.businessDays),
633
+ revenue: parseAmount(m.revenue, `revenue de ${m.month}`),
634
+ directCost: parseAmount(m.directCost, `directCost de ${m.month}`)
635
+ };
636
+ }).filter(isDataMonth);
637
+ const monthsOfData = months.length;
638
+ if (monthsOfData < FORECAST_MIN_MONTHS) return {
639
+ forecast: null,
640
+ monthsOfData,
641
+ status: "unavailable",
642
+ warning: "few_data"
643
+ };
644
+ const limited = monthsOfData < FORECAST_FULL_MONTHS;
645
+ const floorPercent = limited ? FORECAST_BAND_FLOOR_PERCENT.limited : FORECAST_BAND_FLOOR_PERCENT.ok;
646
+ const nextDays = BigInt(input.nextMonthBusinessDays);
647
+ const revenue = estimate(months, (m) => m.revenue, nextDays, floorPercent);
648
+ const directCost = estimate(months, (m) => m.directCost, nextDays, floorPercent);
649
+ const cost = {
650
+ expected: directCost.expected + recurring,
651
+ max: directCost.max + recurring,
652
+ min: directCost.min + recurring
653
+ };
654
+ const profit = {
655
+ expected: revenue.expected - cost.expected,
656
+ max: revenue.max - cost.min,
657
+ min: revenue.min - cost.max
658
+ };
659
+ return {
660
+ forecast: {
661
+ cost: toRange(cost),
662
+ profit: toRange(profit),
663
+ revenue: toRange(revenue)
664
+ },
665
+ monthsOfData,
666
+ status: limited ? "limited" : "ok",
667
+ warning: limited ? "few_data" : null
668
+ };
669
+ }
670
+ __name(forecastNextMonth, "forecastNextMonth");
671
+ var DEFAULT_OUT_OF_PATTERN_THRESHOLD_PERCENT = 10;
672
+ var OUT_OF_PATTERN_MONTHS = 3;
673
+ function thresholdInHundredths(thresholdPercent) {
674
+ const hundredths = Math.round(thresholdPercent * 100);
675
+ if (!Number.isFinite(thresholdPercent) || thresholdPercent < 0 || thresholdPercent > 1e3 || Math.abs(thresholdPercent * 100 - hundredths) > 1e-6) throw new RangeError(`limite de fora do padr\xE3o inv\xE1lido: ${thresholdPercent}`);
676
+ return BigInt(hundredths);
677
+ }
678
+ __name(thresholdInHundredths, "thresholdInHundredths");
679
+ function detectOutOfPattern(input) {
680
+ const threshold = thresholdInHundredths(input.thresholdPercent);
681
+ const alerts = [];
682
+ for (const item of input.items) {
683
+ const current = parseAmount(item.current, `current de ${item.key}`);
684
+ const previous = item.previousMonths.slice(0, OUT_OF_PATTERN_MONTHS).map((value) => parseAmount(value, `previousMonths de ${item.key}`));
685
+ if (previous.length < OUT_OF_PATTERN_MONTHS) continue;
686
+ const average = divideHalfUp(previous.reduce((sum, value) => sum + value, 0n), BigInt(previous.length));
687
+ const difference = current - average;
688
+ const distance = difference < 0n ? -difference : difference;
689
+ if (distance * 10000n <= average * threshold) continue;
690
+ alerts.push({
691
+ average: formatCents(average),
692
+ current: formatCents(current),
693
+ difference: formatCents(difference),
694
+ direction: difference > 0n ? "above" : "below",
695
+ key: item.key,
696
+ kind: item.kind,
697
+ label: item.label
698
+ });
699
+ }
700
+ return alerts;
701
+ }
702
+ __name(detectOutOfPattern, "detectOutOfPattern");
703
+
704
+ // src/resultFilters.ts
705
+ var NO_ASSET_ID = "sem-bem";
706
+ var NO_CUSTOMER_ID = "sem-cliente";
707
+ var EXPENSE_RESULT_FILTER_KEYS = [
708
+ "assetId",
709
+ "categoryId",
710
+ "customerId",
711
+ "payeeRef"
712
+ ];
713
+ function hasResultFilters(filters) {
714
+ return filters !== void 0 && EXPENSE_RESULT_FILTER_KEYS.some((key) => filters[key] !== void 0);
715
+ }
716
+ __name(hasResultFilters, "hasResultFilters");
717
+ function unitMatchesFilters(unit, filters) {
718
+ if (filters.assetId !== void 0 && unit.assetId !== filters.assetId) return false;
719
+ if (filters.customerId !== void 0 && unit.customerId !== filters.customerId) return false;
720
+ return true;
721
+ }
722
+ __name(unitMatchesFilters, "unitMatchesFilters");
723
+ function expenseMatchesFilters(expense, filters) {
724
+ if (filters.categoryId !== void 0 && expense.categoryId !== filters.categoryId) return false;
725
+ if (filters.payeeRef !== void 0 && expense.payeeRef !== filters.payeeRef) return false;
726
+ return true;
727
+ }
728
+ __name(expenseMatchesFilters, "expenseMatchesFilters");
729
+
730
+ // src/reminder.ts
731
+ var REMINDER_KINDS = [
732
+ "before",
733
+ "due_today",
734
+ "overdue"
735
+ ];
736
+ var REMINDER_CHANNELS = [
737
+ "email",
738
+ "whatsapp",
739
+ "push"
740
+ ];
741
+ var DEFAULT_REMINDER_SETTINGS = {
742
+ dailySummaryEnabled: false,
743
+ dailySummaryHour: 8,
744
+ daysBefore: 3,
745
+ enabledChannels: [
746
+ "email"
747
+ ],
748
+ maxOverdueNotices: 3
749
+ };
750
+ var DAY_MS = 864e5;
751
+ var CIVIL_DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})$/u;
752
+ var CHANNEL_ORDER = [
753
+ "email",
754
+ "whatsapp",
755
+ "push"
756
+ ];
757
+ function civilDayNumber(value) {
758
+ const match = CIVIL_DATE_REGEX.exec(value);
759
+ if (match === null) throw new Error(`data civil inv\xE1lida: ${value}`);
760
+ const [, year, month, day] = match;
761
+ return Date.UTC(Number(year), Number(month) - 1, Number(day)) / DAY_MS;
762
+ }
763
+ __name(civilDayNumber, "civilDayNumber");
764
+ function civilDaysBetween(from, to) {
765
+ return civilDayNumber(to) - civilDayNumber(from);
766
+ }
767
+ __name(civilDaysBetween, "civilDaysBetween");
768
+ function reminderKindOn(input) {
769
+ const daysUntil = civilDaysBetween(input.today, input.dueDate);
770
+ if (daysUntil === 0) return "due_today";
771
+ if (daysUntil > 0) {
772
+ return input.settings.daysBefore > 0 && daysUntil === input.settings.daysBefore ? "before" : null;
773
+ }
774
+ return -daysUntil <= input.settings.maxOverdueNotices ? "overdue" : null;
775
+ }
776
+ __name(reminderKindOn, "reminderKindOn");
777
+ function daysUntilDue(input) {
778
+ return civilDaysBetween(input.today, input.dueDate);
779
+ }
780
+ __name(daysUntilDue, "daysUntilDue");
781
+ function belongsToDailySummary(input) {
782
+ return input.status === "open" && civilDaysBetween(input.today, input.dueDate) <= 0;
783
+ }
784
+ __name(belongsToDailySummary, "belongsToDailySummary");
785
+ function isReminderHour(input) {
786
+ return input.hourOfDay >= input.settings.dailySummaryHour;
787
+ }
788
+ __name(isReminderHour, "isReminderHour");
789
+ function isBarredFromReminders(facts) {
790
+ const neutral = facts.neutralRoles ?? [];
791
+ const isField = facts.isFieldStaff === true || facts.roles.some((role) => facts.fieldRoles.includes(role));
792
+ const hasOfficeRole = facts.roles.some((role) => !facts.fieldRoles.includes(role) && !neutral.includes(role));
793
+ return isField && !hasOfficeRole;
794
+ }
795
+ __name(isBarredFromReminders, "isBarredFromReminders");
796
+ function personalReminderChannels(facts) {
797
+ return CHANNEL_ORDER.filter((channel) => {
798
+ if (channel === "email") return facts.hasEmail;
799
+ if (channel === "whatsapp") return facts.whatsappOptIn && facts.hasVerifiedWhatsapp;
800
+ return facts.pushOptIn;
801
+ });
802
+ }
803
+ __name(personalReminderChannels, "personalReminderChannels");
804
+ function effectiveReminderChannels(input) {
805
+ return CHANNEL_ORDER.filter((channel) => input.recipient.channels.includes(channel) && input.companyChannels.includes(channel));
806
+ }
807
+ __name(effectiveReminderChannels, "effectiveReminderChannels");
808
+ function chooseReminderRecipients(input) {
809
+ const reachable = /* @__PURE__ */ __name((recipient) => {
810
+ const channels = effectiveReminderChannels({
811
+ companyChannels: input.companyChannels,
812
+ recipient
813
+ });
814
+ return channels.length === 0 ? null : {
815
+ channels,
816
+ userId: recipient.userId
817
+ };
818
+ }, "reachable");
819
+ if (input.responsible !== null) {
820
+ const responsible = reachable(input.responsible);
821
+ if (responsible !== null) return {
822
+ reason: "responsible",
823
+ recipients: [
824
+ responsible
825
+ ]
826
+ };
827
+ }
828
+ const seen = /* @__PURE__ */ new Set();
829
+ const admins = input.admins.map(reachable).filter((recipient) => recipient !== null).filter((recipient) => seen.has(recipient.userId) ? false : (seen.add(recipient.userId), true));
830
+ return {
831
+ reason: input.responsible === null ? "no_responsible" : "responsible_unreachable",
832
+ recipients: admins
833
+ };
834
+ }
835
+ __name(chooseReminderRecipients, "chooseReminderRecipients");
836
+
837
+ // src/reminderText.ts
838
+ var PLACEHOLDER_REGEX = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/gu;
839
+ var EMPTY_FIELD = "\u2014";
840
+ var HTML_ESCAPE_MAP = {
841
+ '"': "&quot;",
842
+ "&": "&amp;",
843
+ "'": "&#39;",
844
+ "<": "&lt;",
845
+ ">": "&gt;"
846
+ };
847
+ function escapeHtml(value) {
848
+ return value.replace(/[&<>"']/gu, (character) => HTML_ESCAPE_MAP[character] ?? character);
849
+ }
850
+ __name(escapeHtml, "escapeHtml");
851
+ function formatCivilDateBr(value) {
852
+ const [year, month, day] = value.split("-");
853
+ return `${day}/${month}/${year}`;
854
+ }
855
+ __name(formatCivilDateBr, "formatCivilDateBr");
856
+ function formatCompetenceBr(value) {
857
+ const [year, month] = value.split("-");
858
+ return `${month}/${year}`;
859
+ }
860
+ __name(formatCompetenceBr, "formatCompetenceBr");
861
+ function describeDueSituation(daysUntilDue2) {
862
+ if (daysUntilDue2 > 1) return `vence em ${daysUntilDue2} dias`;
863
+ if (daysUntilDue2 === 1) return "vence amanh\xE3";
864
+ if (daysUntilDue2 === 0) return "vence hoje";
865
+ if (daysUntilDue2 === -1) return "venceu ontem";
866
+ return `venceu h\xE1 ${-daysUntilDue2} dias`;
867
+ }
868
+ __name(describeDueSituation, "describeDueSituation");
869
+ function buildExpenseReminderValues(facts, options = {}) {
870
+ return {
871
+ categoria: facts.categoryName,
872
+ competencia: formatCompetenceBr(facts.competence),
873
+ conta: facts.expenseName,
874
+ favorecido: facts.payeeName ?? EMPTY_FIELD,
875
+ responsavel: facts.recipientName,
876
+ situacao: describeDueSituation(civilDaysBetween(facts.today, facts.dueDate)),
877
+ valor: formatBrl(facts.amount),
878
+ vencimento: formatCivilDateBr(facts.dueDate),
879
+ [options.companyVariable ?? "empresa"]: facts.companyDisplayName
880
+ };
881
+ }
882
+ __name(buildExpenseReminderValues, "buildExpenseReminderValues");
883
+ function buildExpenseDailySummaryValues(input, options = {}) {
884
+ const total = input.lines.reduce((sum, line) => sum + (parseMoneyToCents(line.amount) ?? 0n), 0n);
885
+ const count = input.lines.length;
886
+ return {
887
+ dia: formatCivilDateBr(input.today),
888
+ quantidade: `${count} ${count === 1 ? "conta" : "contas"}`,
889
+ responsavel: input.recipientName,
890
+ totalAberto: formatBrl(total),
891
+ [options.companyVariable ?? "empresa"]: input.companyDisplayName
892
+ };
893
+ }
894
+ __name(buildExpenseDailySummaryValues, "buildExpenseDailySummaryValues");
895
+ var DEFAULT_EXPENSE_MAIL_PALETTE = {
896
+ border: "#e6e1d8",
897
+ muted: "#6b7c85",
898
+ primary: "#d58a47",
899
+ text: "#10222c"
900
+ };
901
+ function buildExpenseMailButtonHtml(input) {
902
+ if (input.url === null || !/^https:\/\//u.test(input.url)) return "";
903
+ const palette = input.palette ?? DEFAULT_EXPENSE_MAIL_PALETTE;
904
+ const background = input.primary ? palette.primary : "#ffffff";
905
+ const border = input.primary ? palette.primary : palette.text;
906
+ return [
907
+ '<tr><td style="padding:8px 28px">',
908
+ '<table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>',
909
+ `<td style="background:${background};border:1px solid ${border};padding:12px 22px;">`,
910
+ `<a href="${escapeHtml(input.url)}" style="color:${palette.text};font-size:15px;font-weight:bold;text-decoration:none;font-family:Arial,Helvetica,sans-serif;">${escapeHtml(input.label)}</a>`,
911
+ "</td></tr></table>",
912
+ "</td></tr>"
913
+ ].join("");
914
+ }
915
+ __name(buildExpenseMailButtonHtml, "buildExpenseMailButtonHtml");
916
+ function buildExpenseSummaryTableHtml(input) {
917
+ const palette = input.palette ?? DEFAULT_EXPENSE_MAIL_PALETTE;
918
+ const rows = input.lines.map((line, index) => {
919
+ const border = index === 0 ? "" : `border-top:1px solid ${palette.border};`;
920
+ const situation = describeDueSituation(civilDaysBetween(input.today, line.dueDate));
921
+ return [
922
+ "<tr>",
923
+ `<td style="padding:10px 14px;${border}font-weight:bold;">${escapeHtml(line.expenseName)}</td>`,
924
+ `<td style="padding:10px 14px;${border}color:${palette.muted};">${escapeHtml(`${formatCivilDateBr(line.dueDate)} \xB7 ${situation}`)}</td>`,
925
+ `<td style="padding:10px 14px;${border}text-align:right;white-space:nowrap;">${escapeHtml(formatBrl(line.amount))}</td>`,
926
+ "</tr>"
927
+ ].join("");
928
+ });
929
+ return [
930
+ '<tr><td style="padding:8px 28px">',
931
+ `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border:1px solid ${palette.border};font-size:14px;line-height:1.5;font-family:Arial,Helvetica,sans-serif;color:${palette.text};">`,
932
+ ...rows,
933
+ "</table>",
934
+ "</td></tr>"
935
+ ].join("");
936
+ }
937
+ __name(buildExpenseSummaryTableHtml, "buildExpenseSummaryTableHtml");
938
+ function renderPlainTemplate(body, values) {
939
+ return body.replace(PLACEHOLDER_REGEX, (_match, name) => Object.hasOwn(values, name) ? values[name] ?? "" : "").trim();
940
+ }
941
+ __name(renderPlainTemplate, "renderPlainTemplate");
942
+ var DEFAULT_EXPENSE_REMINDER_WHATSAPP_TEXT = [
943
+ "\u{1F4B8} *Conta {{situacao}}*",
944
+ "",
945
+ "*{{conta}}* ({{categoria}})",
946
+ "Valor: {{valor}}",
947
+ "Vencimento: {{vencimento}}",
948
+ "",
949
+ "J\xE1 pagou? Responda *paguei* para dar baixa."
950
+ ].join("\n");
951
+ var DEFAULT_EXPENSE_SUMMARY_WHATSAPP_TEXT = [
952
+ "\u{1F4CB} *Contas de {{dia}}*",
953
+ "",
954
+ "{{quantidade}} vencendo hoje ou em atraso, total de {{totalAberto}}."
955
+ ].join("\n");
956
+
957
+ // src/whatsappInput.ts
958
+ var MAX_CENTS = 99999999999n;
959
+ function normalizeChatText(text) {
960
+ return text.normalize("NFD").replace(/[̀-ͯ]/gu, "").toLowerCase().replace(/[^a-z0-9 ]/gu, " ").replace(/\s+/gu, " ").trim();
961
+ }
962
+ __name(normalizeChatText, "normalizeChatText");
963
+ function parseExpenseAmount(text) {
964
+ const cleaned = text.replace(/r\$/giu, "").replace(/\s+/gu, "").replace(/\.(?=\d{3}(?:\D|$))/gu, "").replace(",", ".");
965
+ const match = /^(\d+)(?:\.(\d{1,2}))?$/u.exec(cleaned);
966
+ if (match?.[1] === void 0) return void 0;
967
+ const cents2 = BigInt(match[1]) * 100n + BigInt((match[2] ?? "").padEnd(2, "0") || "0");
968
+ if (cents2 <= 0n || cents2 > MAX_CENTS) return void 0;
969
+ return formatCents(cents2);
970
+ }
971
+ __name(parseExpenseAmount, "parseExpenseAmount");
972
+ function parseExpenseDueDate(text, today) {
973
+ const normalized = text.trim().toLowerCase().normalize("NFD").replace(/\p{Diacritic}/gu, "");
974
+ if (normalized === "hoje") return today;
975
+ if (normalized === "amanha") return addCivilDays(today, 1);
976
+ const match = /^(\d{1,2})\/(\d{1,2})(?:\/(\d{4}))?$/u.exec(normalized);
977
+ if (match?.[1] === void 0 || match[2] === void 0) return void 0;
978
+ const day = match[1].padStart(2, "0");
979
+ const month = match[2].padStart(2, "0");
980
+ if (match[3] !== void 0) {
981
+ const full = `${match[3]}-${month}-${day}`;
982
+ return isCivilDate(full) ? full : void 0;
983
+ }
984
+ const year = Number(today.slice(0, 4));
985
+ const thisYear = `${year}-${month}-${day}`;
986
+ if (!isCivilDate(thisYear)) return void 0;
987
+ if (thisYear >= today) return thisYear;
988
+ const nextYear = `${year + 1}-${month}-${day}`;
989
+ return isCivilDate(nextYear) ? nextYear : void 0;
990
+ }
991
+ __name(parseExpenseDueDate, "parseExpenseDueDate");
992
+ function parseExpenseDueDay(text) {
993
+ const match = /^(?:dia\s*)?(\d{1,2})$/iu.exec(text.trim());
994
+ if (match?.[1] === void 0) return void 0;
995
+ const day = Number(match[1]);
996
+ return day >= 1 && day <= 31 ? day : void 0;
997
+ }
998
+ __name(parseExpenseDueDay, "parseExpenseDueDay");
999
+ var FINANCE_WORDS = /\b(contas?|boletos?|pagar|pagamentos?|lancar|despesas?|financeiro)\b/u;
1000
+ var OPENING_WORDS = /^(oi+|ola+|menu|opcoes?|ajuda|bom dia|boa tarde|boa noite|e ai|eai|inicio|comecar)$/u;
1001
+ function isDirectExpenseIntent(text) {
1002
+ const normalized = normalizeChatText(text);
1003
+ if (normalized === "") return false;
1004
+ return FINANCE_WORDS.test(normalized) || OPENING_WORDS.test(normalized);
1005
+ }
1006
+ __name(isDirectExpenseIntent, "isDirectExpenseIntent");
1007
+ var FIELD_FINANCE_WORDS = /\b(contas?|despesas?|financeiro)\b|\b(lancar|pagar|cadastrar)\s+(um\s+|uma\s+)?boletos?\b/u;
1008
+ function isFieldStaffFinanceIntent(text) {
1009
+ return FIELD_FINANCE_WORDS.test(normalizeChatText(text));
1010
+ }
1011
+ __name(isFieldStaffFinanceIntent, "isFieldStaffFinanceIntent");
1012
+ function parseSettlementReply(text) {
1013
+ const normalized = normalizeChatText(text);
1014
+ if (!/\b(ja\s+)?(paguei|pago|quitei|quitado|pagamos)\b/u.test(normalized)) return null;
1015
+ if (/\b(nao|ainda nao)\s+(paguei|pago|quitei)\b/u.test(normalized)) return null;
1016
+ const amountMatch = /(r\$\s*)?\d[\d.,]*/iu.exec(text);
1017
+ const amount = amountMatch === null ? void 0 : parseExpenseAmount(amountMatch[0]);
1018
+ return amount === void 0 ? {} : {
1019
+ amount
1020
+ };
1021
+ }
1022
+ __name(parseSettlementReply, "parseSettlementReply");
1023
+
1024
+ // src/conversation.ts
1025
+ var EXPENSE_NAME_MIN_LENGTH = 2;
1026
+ var EXPENSE_NAME_MAX_LENGTH = 80;
1027
+ var EXPENSE_CONVERSATION_STEPS = [
1028
+ "kind",
1029
+ "name",
1030
+ "category",
1031
+ "amount",
1032
+ "recurrence",
1033
+ "due_day",
1034
+ "due_date",
1035
+ "confirm",
1036
+ "done",
1037
+ "cancelled"
1038
+ ];
1039
+ var EXPENSE_CONVERSATION_ANSWER = {
1040
+ cancel: "cancel",
1041
+ confirm: "confirm",
1042
+ fix: "fix"
1043
+ };
1044
+ var EXPENSE_RECURRENCE_OPTIONS = [
1045
+ [
1046
+ "monthly",
1047
+ "\u{1F4C6} Mensal"
1048
+ ],
1049
+ [
1050
+ "bimonthly",
1051
+ "\u{1F4C6} Bimestral"
1052
+ ],
1053
+ [
1054
+ "quarterly",
1055
+ "\u{1F4C6} Trimestral"
1056
+ ],
1057
+ [
1058
+ "yearly",
1059
+ "\u{1F4C6} Anual"
1060
+ ]
1061
+ ];
1062
+ var EXPENSE_CONVERSATION_TEXT = {
1063
+ amount: "Qual o valor? Por exemplo: 1500 ou 1.500,50",
1064
+ amountInvalid: "N\xE3o entendi o valor. Digite s\xF3 n\xFAmeros, por exemplo: 1500 ou 1.500,50",
1065
+ cancelled: "Certo, n\xE3o lancei nada.",
1066
+ categoryChoice: "Em qual categoria?",
1067
+ categoryInvalid: "Escolha uma categoria da lista acima.",
1068
+ confirm: "Confere a conta?",
1069
+ dueDate: "Qual o vencimento? Por exemplo: 20/11, 20/11/2026, hoje ou amanh\xE3.",
1070
+ dueDateInvalid: "N\xE3o entendi a data. Use 20/11, 20/11/2026, hoje ou amanh\xE3.",
1071
+ dueDay: "Em que dia do m\xEAs ela vence? De 1 a 31.",
1072
+ dueDayInvalid: "Digite o dia do m\xEAs, de 1 a 31.",
1073
+ kindChoice: "Que tipo de conta voc\xEA quer lan\xE7ar?",
1074
+ kindInvalid: "Escolha Fixa (todo m\xEAs) ou Vari\xE1vel (uma vez s\xF3).",
1075
+ name: "Qual o nome da conta? Por exemplo: Aluguel do galp\xE3o.",
1076
+ nameInvalid: `O nome precisa ter de ${EXPENSE_NAME_MIN_LENGTH} a ${EXPENSE_NAME_MAX_LENGTH} letras. Digite de novo.`,
1077
+ noCategories: "N\xE3o h\xE1 categoria ativa para lan\xE7ar. Cadastre uma em Contas, no painel.",
1078
+ recurrenceChoice: "Com que frequ\xEAncia ela vence?",
1079
+ recurrenceInvalid: "Escolha a frequ\xEAncia da lista acima.",
1080
+ saved: /* @__PURE__ */ __name((name) => `\u2705 Conta *${name}* lan\xE7ada.`, "saved")
1081
+ };
1082
+ var KIND_OPTIONS = [
1083
+ {
1084
+ id: "fixed",
1085
+ title: "\u{1F501} Fixa"
1086
+ },
1087
+ {
1088
+ id: "variable",
1089
+ title: "\u{1F9FE} Vari\xE1vel"
1090
+ }
1091
+ ];
1092
+ var CONFIRM_OPTIONS = [
1093
+ {
1094
+ id: EXPENSE_CONVERSATION_ANSWER.confirm,
1095
+ title: "\u2705 Confirmar"
1096
+ },
1097
+ {
1098
+ id: EXPENSE_CONVERSATION_ANSWER.fix,
1099
+ title: "\u270F\uFE0F Corrigir"
1100
+ },
1101
+ {
1102
+ id: EXPENSE_CONVERSATION_ANSWER.cancel,
1103
+ title: "\u274C Cancelar"
1104
+ }
1105
+ ];
1106
+ var CANCEL_WORDS = /* @__PURE__ */ new Set([
1107
+ "cancelar",
1108
+ "cancela",
1109
+ "sair",
1110
+ "parar",
1111
+ EXPENSE_CONVERSATION_ANSWER.cancel
1112
+ ]);
1113
+ function startExpenseConversation() {
1114
+ return {
1115
+ prompt: {
1116
+ options: KIND_OPTIONS,
1117
+ text: EXPENSE_CONVERSATION_TEXT.kindChoice
1118
+ },
1119
+ state: {
1120
+ draft: {},
1121
+ step: "kind"
1122
+ }
1123
+ };
1124
+ }
1125
+ __name(startExpenseConversation, "startExpenseConversation");
1126
+ function matchConversationOption(input, options) {
1127
+ const trimmed = input.trim();
1128
+ const byId = options.find((option) => option.id === trimmed);
1129
+ if (byId !== void 0) return byId;
1130
+ if (/^\d{1,2}$/u.test(trimmed)) return options[Number(trimmed) - 1];
1131
+ const normalized = normalizeChatText(trimmed);
1132
+ if (normalized === "") return void 0;
1133
+ return options.find((option) => normalizeChatText(option.title) === normalized) ?? options.find((option) => normalizeChatText(option.title).startsWith(normalized));
1134
+ }
1135
+ __name(matchConversationOption, "matchConversationOption");
1136
+ function categoryOptions(categories) {
1137
+ return categories.map((category) => ({
1138
+ id: category.id,
1139
+ title: category.name
1140
+ }));
1141
+ }
1142
+ __name(categoryOptions, "categoryOptions");
1143
+ function recurrenceOptions() {
1144
+ return EXPENSE_RECURRENCE_OPTIONS.map(([id, title]) => ({
1145
+ id,
1146
+ title
1147
+ }));
1148
+ }
1149
+ __name(recurrenceOptions, "recurrenceOptions");
1150
+ var RECURRENCE_LABEL = {
1151
+ bimonthly: "bimestral",
1152
+ fortnightly: "quinzenal",
1153
+ monthly: "mensal",
1154
+ quarterly: "trimestral",
1155
+ yearly: "anual"
1156
+ };
1157
+ function describeExpenseDraft(draft) {
1158
+ const lines = [
1159
+ `*${draft.name ?? ""}*`,
1160
+ `Categoria: ${draft.categoryName ?? "\u2014"}`,
1161
+ `Valor: ${draft.amount === void 0 ? "\u2014" : formatBrl(draft.amount)}`
1162
+ ];
1163
+ if (draft.kind === "fixed") {
1164
+ lines.push(`Tipo: fixa, ${draft.recurrence === void 0 ? "" : RECURRENCE_LABEL[draft.recurrence]}`.trim());
1165
+ lines.push(`Vence todo dia ${draft.dueDay ?? "\u2014"}`);
1166
+ } else {
1167
+ lines.push("Tipo: vari\xE1vel (uma vez s\xF3)");
1168
+ lines.push(`Vencimento: ${draft.dueDate === void 0 ? "\u2014" : formatCivilDateBr(draft.dueDate)}`);
1169
+ }
1170
+ return lines.join("\n");
1171
+ }
1172
+ __name(describeExpenseDraft, "describeExpenseDraft");
1173
+ function ask(step, draft, prompt) {
1174
+ return {
1175
+ prompt,
1176
+ state: {
1177
+ draft,
1178
+ step
1179
+ }
1180
+ };
1181
+ }
1182
+ __name(ask, "ask");
1183
+ function askConfirm(draft) {
1184
+ return ask("confirm", draft, {
1185
+ options: CONFIRM_OPTIONS,
1186
+ text: `${EXPENSE_CONVERSATION_TEXT.confirm}
1187
+
1188
+ ${describeExpenseDraft(draft)}`
1189
+ });
1190
+ }
1191
+ __name(askConfirm, "askConfirm");
1192
+ function askCategory(draft, categories, invalid = false) {
1193
+ if (categories.length === 0) {
1194
+ return {
1195
+ prompt: {
1196
+ text: EXPENSE_CONVERSATION_TEXT.noCategories
1197
+ },
1198
+ state: {
1199
+ draft,
1200
+ step: "cancelled"
1201
+ }
1202
+ };
1203
+ }
1204
+ return ask("category", draft, {
1205
+ options: categoryOptions(categories),
1206
+ text: invalid ? EXPENSE_CONVERSATION_TEXT.categoryInvalid : EXPENSE_CONVERSATION_TEXT.categoryChoice
1207
+ });
1208
+ }
1209
+ __name(askCategory, "askCategory");
1210
+ function advanceExpenseConversation(params) {
1211
+ const { categories, input, state, today } = params;
1212
+ const draft = state.draft;
1213
+ const normalized = normalizeChatText(input);
1214
+ if (CANCEL_WORDS.has(normalized) || input.trim() === EXPENSE_CONVERSATION_ANSWER.cancel) {
1215
+ return {
1216
+ prompt: {
1217
+ text: EXPENSE_CONVERSATION_TEXT.cancelled
1218
+ },
1219
+ state: {
1220
+ draft: {},
1221
+ step: "cancelled"
1222
+ }
1223
+ };
1224
+ }
1225
+ switch (state.step) {
1226
+ case "done":
1227
+ case "cancelled":
1228
+ return startExpenseConversation();
1229
+ case "kind": {
1230
+ const choice = matchConversationOption(input, KIND_OPTIONS);
1231
+ const kind = choice?.id === "fixed" || /\b(fixa|fixo|mensal|todo mes)\b/u.test(normalized) ? "fixed" : choice?.id === "variable" || /\b(variavel|avulsa|uma vez)\b/u.test(normalized) ? "variable" : void 0;
1232
+ if (kind === void 0) {
1233
+ return ask("kind", draft, {
1234
+ options: KIND_OPTIONS,
1235
+ text: EXPENSE_CONVERSATION_TEXT.kindInvalid
1236
+ });
1237
+ }
1238
+ return ask("name", {
1239
+ kind
1240
+ }, {
1241
+ text: EXPENSE_CONVERSATION_TEXT.name
1242
+ });
1243
+ }
1244
+ case "name": {
1245
+ const name = input.trim().replace(/\s+/gu, " ");
1246
+ if (name.length < EXPENSE_NAME_MIN_LENGTH || name.length > EXPENSE_NAME_MAX_LENGTH) {
1247
+ return ask("name", draft, {
1248
+ text: EXPENSE_CONVERSATION_TEXT.nameInvalid
1249
+ });
1250
+ }
1251
+ return askCategory({
1252
+ ...draft,
1253
+ name
1254
+ }, categories);
1255
+ }
1256
+ case "category": {
1257
+ const choice = matchConversationOption(input, categoryOptions(categories));
1258
+ if (choice === void 0) return askCategory(draft, categories, true);
1259
+ return ask("amount", {
1260
+ ...draft,
1261
+ categoryId: choice.id,
1262
+ categoryName: choice.title
1263
+ }, {
1264
+ text: EXPENSE_CONVERSATION_TEXT.amount
1265
+ });
1266
+ }
1267
+ case "amount": {
1268
+ const amount = parseExpenseAmount(input);
1269
+ if (amount === void 0) return ask("amount", draft, {
1270
+ text: EXPENSE_CONVERSATION_TEXT.amountInvalid
1271
+ });
1272
+ const next = {
1273
+ ...draft,
1274
+ amount
1275
+ };
1276
+ return draft.kind === "fixed" ? ask("recurrence", next, {
1277
+ options: recurrenceOptions(),
1278
+ text: EXPENSE_CONVERSATION_TEXT.recurrenceChoice
1279
+ }) : ask("due_date", next, {
1280
+ text: EXPENSE_CONVERSATION_TEXT.dueDate
1281
+ });
1282
+ }
1283
+ case "recurrence": {
1284
+ const choice = matchConversationOption(input, recurrenceOptions());
1285
+ if (choice === void 0) {
1286
+ return ask("recurrence", draft, {
1287
+ options: recurrenceOptions(),
1288
+ text: EXPENSE_CONVERSATION_TEXT.recurrenceInvalid
1289
+ });
1290
+ }
1291
+ return ask("due_day", {
1292
+ ...draft,
1293
+ recurrence: choice.id
1294
+ }, {
1295
+ text: EXPENSE_CONVERSATION_TEXT.dueDay
1296
+ });
1297
+ }
1298
+ case "due_day": {
1299
+ const dueDay = parseExpenseDueDay(input);
1300
+ if (dueDay === void 0) return ask("due_day", draft, {
1301
+ text: EXPENSE_CONVERSATION_TEXT.dueDayInvalid
1302
+ });
1303
+ return askConfirm({
1304
+ ...draft,
1305
+ dueDay
1306
+ });
1307
+ }
1308
+ case "due_date": {
1309
+ const dueDate = parseExpenseDueDate(input, today);
1310
+ if (dueDate === void 0) return ask("due_date", draft, {
1311
+ text: EXPENSE_CONVERSATION_TEXT.dueDateInvalid
1312
+ });
1313
+ return askConfirm({
1314
+ ...draft,
1315
+ dueDate
1316
+ });
1317
+ }
1318
+ case "confirm": {
1319
+ const choice = matchConversationOption(input, CONFIRM_OPTIONS);
1320
+ const answer = choice?.id ?? (/\b(sim|ok|isso|confirmo|confirmar)\b/u.test(normalized) ? "confirm" : void 0);
1321
+ if (answer === EXPENSE_CONVERSATION_ANSWER.fix) return startExpenseConversation();
1322
+ if (answer !== EXPENSE_CONVERSATION_ANSWER.confirm) return askConfirm(draft);
1323
+ const submit = toSubmit(draft);
1324
+ if (submit === null) return startExpenseConversation();
1325
+ return {
1326
+ prompt: {
1327
+ text: EXPENSE_CONVERSATION_TEXT.saved(submit.name)
1328
+ },
1329
+ state: {
1330
+ draft: {},
1331
+ step: "done"
1332
+ },
1333
+ submit
1334
+ };
1335
+ }
1336
+ }
1337
+ }
1338
+ __name(advanceExpenseConversation, "advanceExpenseConversation");
1339
+ function toSubmit(draft) {
1340
+ if (draft.kind === void 0 || draft.name === void 0 || draft.categoryId === void 0 || draft.amount === void 0) {
1341
+ return null;
1342
+ }
1343
+ if (draft.kind === "fixed") {
1344
+ if (draft.recurrence === void 0 || draft.dueDay === void 0) return null;
1345
+ return {
1346
+ categoryId: draft.categoryId,
1347
+ dueDay: draft.dueDay,
1348
+ expectedAmount: draft.amount,
1349
+ kind: "fixed",
1350
+ name: draft.name,
1351
+ recurrence: draft.recurrence
1352
+ };
1353
+ }
1354
+ if (draft.dueDate === void 0) return null;
1355
+ return {
1356
+ categoryId: draft.categoryId,
1357
+ dueDate: draft.dueDate,
1358
+ expectedAmount: draft.amount,
1359
+ kind: "variable",
1360
+ name: draft.name
1361
+ };
1362
+ }
1363
+ __name(toSubmit, "toSubmit");
1364
+
1365
+ // src/summary.ts
1366
+ function dueStateOf(dueDate, today) {
1367
+ const days = civilDaysBetween(today, dueDate);
1368
+ if (days > 0) return "upcoming";
1369
+ return days === 0 ? "due_today" : "overdue";
1370
+ }
1371
+ __name(dueStateOf, "dueStateOf");
1372
+ function cents(value) {
1373
+ return value === null ? 0n : parseStoredMoneyToCents(value) ?? 0n;
1374
+ }
1375
+ __name(cents, "cents");
1376
+ function summarizeExpenseOccurrences(occurrences, today) {
1377
+ let open = 0n;
1378
+ let overdue = 0n;
1379
+ let paid = 0n;
1380
+ const count = {
1381
+ canceled: 0,
1382
+ open: 0,
1383
+ overdue: 0,
1384
+ paid: 0
1385
+ };
1386
+ const categories = /* @__PURE__ */ new Map();
1387
+ for (const occurrence of occurrences) {
1388
+ if (occurrence.status === "canceled") {
1389
+ count.canceled += 1;
1390
+ continue;
1391
+ }
1392
+ const key = occurrence.categoryId ?? "sem-categoria";
1393
+ const bucket = categories.get(key) ?? {
1394
+ expected: 0n,
1395
+ name: occurrence.categoryName ?? "Sem categoria",
1396
+ open: 0n,
1397
+ paid: 0n
1398
+ };
1399
+ if (occurrence.status === "paid") {
1400
+ const value = cents(occurrence.paidAmount ?? occurrence.expectedAmount);
1401
+ paid += value;
1402
+ bucket.paid += value;
1403
+ bucket.expected += value;
1404
+ count.paid += 1;
1405
+ } else {
1406
+ const value = cents(occurrence.expectedAmount);
1407
+ open += value;
1408
+ bucket.open += value;
1409
+ bucket.expected += value;
1410
+ count.open += 1;
1411
+ if (dueStateOf(occurrence.dueDate, today) === "overdue") {
1412
+ overdue += value;
1413
+ count.overdue += 1;
1414
+ }
1415
+ }
1416
+ categories.set(key, bucket);
1417
+ }
1418
+ return {
1419
+ byCategory: [
1420
+ ...categories.entries()
1421
+ ].map(([categoryId, bucket]) => ({
1422
+ categoryId,
1423
+ categoryName: bucket.name,
1424
+ expected: formatCents(bucket.expected),
1425
+ open: formatCents(bucket.open),
1426
+ paid: formatCents(bucket.paid)
1427
+ })).sort((left, right) => {
1428
+ const diff = parseStoredMoneyToCents(right.expected) - parseStoredMoneyToCents(left.expected);
1429
+ return diff > 0n ? 1 : diff < 0n ? -1 : left.categoryName.localeCompare(right.categoryName, "pt-BR");
1430
+ }),
1431
+ count,
1432
+ open: formatCents(open),
1433
+ overdue: formatCents(overdue),
1434
+ paid: formatCents(paid),
1435
+ total: formatCents(open + paid)
1436
+ };
1437
+ }
1438
+ __name(summarizeExpenseOccurrences, "summarizeExpenseOccurrences");
1439
+ export {
1440
+ ALLOCATABLE_COST_GROUPS,
1441
+ ALLOCATION_CRITERIA,
1442
+ DEFAULT_ALLOCATION_SETTINGS,
1443
+ DEFAULT_EXPENSE_CATEGORIES,
1444
+ DEFAULT_EXPENSE_MAIL_PALETTE,
1445
+ DEFAULT_EXPENSE_REMINDER_WHATSAPP_TEXT,
1446
+ DEFAULT_EXPENSE_SUMMARY_WHATSAPP_TEXT,
1447
+ DEFAULT_OUT_OF_PATTERN_THRESHOLD_PERCENT,
1448
+ DEFAULT_REMINDER_SETTINGS,
1449
+ EXPENSE_AMOUNT_CHANGE_KINDS,
1450
+ EXPENSE_CHANNELS,
1451
+ EXPENSE_CONVERSATION_ANSWER,
1452
+ EXPENSE_CONVERSATION_STEPS,
1453
+ EXPENSE_CONVERSATION_TEXT,
1454
+ EXPENSE_COST_GROUPS,
1455
+ EXPENSE_ERROR,
1456
+ EXPENSE_ERROR_MESSAGES,
1457
+ EXPENSE_GENERATION_WINDOW_MONTHS,
1458
+ EXPENSE_KINDS,
1459
+ EXPENSE_NAME_MAX_LENGTH,
1460
+ EXPENSE_NAME_MIN_LENGTH,
1461
+ EXPENSE_OCCURRENCE_STATUSES,
1462
+ EXPENSE_RECURRENCES,
1463
+ EXPENSE_RECURRENCE_OPTIONS,
1464
+ EXPENSE_RESULT_FILTER_KEYS,
1465
+ ExpenseError,
1466
+ FORECAST_BAND_FLOOR_PERCENT,
1467
+ FORECAST_FULL_MONTHS,
1468
+ FORECAST_MIN_MONTHS,
1469
+ NO_ASSET_ID,
1470
+ NO_CUSTOMER_ID,
1471
+ OUT_OF_PATTERN_MONTHS,
1472
+ REMINDER_CHANNELS,
1473
+ REMINDER_KINDS,
1474
+ addCivilDays,
1475
+ addCompetenceMonths,
1476
+ advanceExpenseConversation,
1477
+ allocateExpenses,
1478
+ amountInEffect,
1479
+ belongsToDailySummary,
1480
+ buildExpenseDailySummaryValues,
1481
+ buildExpenseMailButtonHtml,
1482
+ buildExpenseReminderValues,
1483
+ buildExpenseSummaryTableHtml,
1484
+ canTransitionOccurrence,
1485
+ chooseReminderRecipients,
1486
+ civilDateInTimeZone,
1487
+ civilDaysBetween,
1488
+ competenceBounds,
1489
+ competenceIndex,
1490
+ competenceOfDate,
1491
+ daysUntilDue,
1492
+ describeDueSituation,
1493
+ describeExpenseDraft,
1494
+ detectOutOfPattern,
1495
+ distributeByWeight,
1496
+ divideHalfUp,
1497
+ dueStateOf,
1498
+ effectiveReminderChannels,
1499
+ escapeHtml,
1500
+ expenseMatchesFilters,
1501
+ forecastNextMonth,
1502
+ formatBrl,
1503
+ formatCents,
1504
+ formatCivilDateBr,
1505
+ formatCompetenceBr,
1506
+ hasResultFilters,
1507
+ hourInTimeZone,
1508
+ isBarredFromReminders,
1509
+ isCivilDate,
1510
+ isCompetence,
1511
+ isDirectExpenseIntent,
1512
+ isExpenseError,
1513
+ isFieldStaffFinanceIntent,
1514
+ isReminderHour,
1515
+ listExpenseCompetenceWindow,
1516
+ matchConversationOption,
1517
+ normalizeChatText,
1518
+ normalizeMoney,
1519
+ parseExpenseAmount,
1520
+ parseExpenseDueDate,
1521
+ parseExpenseDueDay,
1522
+ parseMoneyToCents,
1523
+ parseSettlementReply,
1524
+ parseStoredMoneyToCents,
1525
+ personalReminderChannels,
1526
+ planAmountChange,
1527
+ planFixedExpenseOccurrences,
1528
+ reminderKindOn,
1529
+ renderPlainTemplate,
1530
+ resolveExpenseDueDate,
1531
+ resolveExpenseSlots,
1532
+ startExpenseConversation,
1533
+ summarizeExpenseOccurrences,
1534
+ unitMatchesFilters
1535
+ };
1536
+ //# sourceMappingURL=index.js.map