b2m-utils 0.0.311 → 0.0.313

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.
@@ -1,7 +1,7 @@
1
- import { RatecardLaneFee } from "../../types";
1
+ import { Ratecard } from "../../types";
2
2
  /**
3
3
  * Constrói um Map de exclusões de fees baseado nas configurações do tarifário
4
- * @param fees - Array de fees do tarifário
4
+ * @param ratecard - Tarifário contendo as configurações de fees
5
5
  * @returns Map onde a chave é o feeId e o valor é um Set de feeIds excluídos da base de cálculo
6
6
  */
7
- export declare const buildFeeExclusionsMap: (fees: RatecardLaneFee[]) => Map<number, Set<number>>;
7
+ export declare const buildFeeExclusionsMap: (ratecard?: Ratecard) => Map<number, Set<number>>;
@@ -1,4 +1,4 @@
1
- import { Cte, RatecardLaneFee } from "../../types";
1
+ import { Cte, RatecardLaneFee, Ratecard } from "../../types";
2
2
  export interface FeeCalculationResult {
3
3
  totalFee: number;
4
4
  totalToCalc: number;
@@ -17,6 +17,8 @@ export interface CalculateFeesCacheOptions {
17
17
  preCalculatedValues?: Map<number, number>;
18
18
  /** IDs de fees que foram editadas manualmente e não devem ser recalculadas */
19
19
  manuallyEditedFeeIds?: Set<number>;
20
+ /** Tarifário (opcional, será extraído do CTE se não fornecido) */
21
+ ratecard?: Ratecard;
20
22
  }
21
23
  /**
22
24
  * Calcula todas as fees em 3 passadas (normais, TOTAL_PERCENTAGE, ICMS) e retorna um cache detalhado
@@ -1,9 +1,10 @@
1
- import { Cte, RatecardLaneFee } from "../../types";
1
+ import { Cte, RatecardLaneFee, Ratecard } from "../../types";
2
2
  /**
3
3
  * Calcula o total de fees de forma consistente, usando cálculo iterativo para TOTAL_PERCENTAGE
4
4
  * @param fees - Array de fees a calcular
5
5
  * @param cte - CTE para cálculo
6
6
  * @param allFeesForCalc - Todas as fees disponíveis para cálculo
7
+ * @param ratecard - Tarifário (opcional, será extraído do CTE se não fornecido)
7
8
  * @returns Total calculado
8
9
  */
9
- export declare const calculateFeesTotal: (fees: RatecardLaneFee[], cte: Cte, allFeesForCalc?: RatecardLaneFee[]) => number;
10
+ export declare const calculateFeesTotal: (fees: RatecardLaneFee[], cte: Cte, allFeesForCalc?: RatecardLaneFee[], ratecard?: Ratecard) => number;
@@ -418,28 +418,57 @@ var applyRedeliveryMultiplier = function (total, cte) {
418
418
 
419
419
  /**
420
420
  * Constrói um Map de exclusões de fees baseado nas configurações do tarifário
421
- * @param fees - Array de fees do tarifário
421
+ * @param ratecard - Tarifário contendo as configurações de fees
422
422
  * @returns Map onde a chave é o feeId e o valor é um Set de feeIds excluídos da base de cálculo
423
423
  */
424
- var buildFeeExclusionsMap = function (fees) {
424
+ var buildFeeExclusionsMap = function (ratecard) {
425
+ var _a;
425
426
  var exclusionsMap = new Map();
426
- fees.forEach(function (fee) {
427
- var _a;
428
- if (!((_a = fee.fee) === null || _a === void 0 ? void 0 : _a.id) || !fee.fee.RatecardFeeConfig)
429
- return;
430
- // Procurar pela configuração de exclusão
431
- var excludeConfig = fee.fee.RatecardFeeConfig.find(function (config) { var _a; return ((_a = config.feeConfig) === null || _a === void 0 ? void 0 : _a.configKey) === RatecardFeeConfigKeyEnum.EXCLUDE_FROM_TOTAL_PERCENTAGE; });
432
- if (excludeConfig === null || excludeConfig === void 0 ? void 0 : excludeConfig.configValue) {
427
+ console.log('[buildFeeExclusionsMap] Iniciando construção do mapa de exclusões', {
428
+ ratecardId: ratecard === null || ratecard === void 0 ? void 0 : ratecard.id,
429
+ hasConfigs: !!(ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardFeeConfig),
430
+ configsCount: ((_a = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardFeeConfig) === null || _a === void 0 ? void 0 : _a.length) || 0
431
+ });
432
+ if (!(ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardFeeConfig)) {
433
+ console.log('[buildFeeExclusionsMap] Nenhuma configuração encontrada, retornando mapa vazio');
434
+ return exclusionsMap;
435
+ }
436
+ // Iterar sobre todas as configurações de fees do ratecard
437
+ ratecard.RatecardFeeConfig.forEach(function (config) {
438
+ var _a, _b;
439
+ // Verificar se é uma configuração de exclusão
440
+ if (((_a = config.feeConfig) === null || _a === void 0 ? void 0 : _a.configKey) === RatecardFeeConfigKeyEnum.EXCLUDE_FROM_TOTAL_PERCENTAGE &&
441
+ config.configValue &&
442
+ config.feeId) {
443
+ console.log('[buildFeeExclusionsMap] Configuração de exclusão encontrada', {
444
+ feeId: config.feeId,
445
+ feeName: (_b = config.fee) === null || _b === void 0 ? void 0 : _b.name,
446
+ configValue: config.configValue
447
+ });
433
448
  // Parse dos IDs separados por vírgula
434
- var excludedIds = excludeConfig.configValue
449
+ var excludedIds = config.configValue
435
450
  .split(',')
436
451
  .map(function (id) { return parseInt(id.trim(), 10); })
437
452
  .filter(function (id) { return !isNaN(id); });
438
453
  if (excludedIds.length > 0) {
439
- exclusionsMap.set(fee.fee.id, new Set(excludedIds));
454
+ exclusionsMap.set(config.feeId, new Set(excludedIds));
455
+ console.log('[buildFeeExclusionsMap] Exclusões adicionadas ao mapa', {
456
+ feeId: config.feeId,
457
+ excludedIds: Array.from(excludedIds)
458
+ });
440
459
  }
441
460
  }
442
461
  });
462
+ console.log('[buildFeeExclusionsMap] Mapa de exclusões construído', {
463
+ totalExclusions: exclusionsMap.size,
464
+ exclusionsMap: Array.from(exclusionsMap.entries()).map(function (_a) {
465
+ var feeId = _a[0], excludedIds = _a[1];
466
+ return ({
467
+ feeId: feeId,
468
+ excludedIds: Array.from(excludedIds)
469
+ });
470
+ })
471
+ });
443
472
  return exclusionsMap;
444
473
  };
445
474
 
@@ -1042,17 +1071,31 @@ var calculateTotalPercentageFees = function (allFees, cte, allFeesForCalc, curre
1042
1071
  // Calcular base das fees não-percentuais
1043
1072
  // Se temos currentValues, usar eles; senão calcular normalmente
1044
1073
  var baseNonPercentage = 0;
1074
+ var nonPercentageDetails = [];
1045
1075
  if (currentValues) {
1046
1076
  // Usar valores atuais das fees não-percentuais
1047
1077
  baseNonPercentage = nonPercentageFees.reduce(function (sum, fee) {
1048
1078
  var _a;
1049
1079
  var value = ((_a = fee.fee) === null || _a === void 0 ? void 0 : _a.id) ? currentValues.get(fee.fee.id) : undefined;
1050
1080
  if (value !== undefined) {
1081
+ nonPercentageDetails.push({
1082
+ feeId: fee.fee.id,
1083
+ feeName: fee.fee.name || 'Unknown',
1084
+ value: value
1085
+ });
1051
1086
  return sum + value;
1052
1087
  }
1053
1088
  // Se não tem valor atual, calcular
1054
1089
  var calculated = calculateFee(fee, cte, allFees, false, allFeesForCalc);
1055
- return sum + ((calculated === null || calculated === void 0 ? void 0 : calculated.totalToCalc) || 0);
1090
+ var calcValue = (calculated === null || calculated === void 0 ? void 0 : calculated.totalToCalc) || 0;
1091
+ if (calcValue > 0) {
1092
+ nonPercentageDetails.push({
1093
+ feeId: fee.fee.id,
1094
+ feeName: fee.fee.name || 'Unknown',
1095
+ value: calcValue
1096
+ });
1097
+ }
1098
+ return sum + calcValue;
1056
1099
  }, 0);
1057
1100
  }
1058
1101
  else {
@@ -1060,8 +1103,24 @@ var calculateTotalPercentageFees = function (allFees, cte, allFeesForCalc, curre
1060
1103
  var nonPercentageResults = filterSiblingFees(nonPercentageFees.map(function (it) {
1061
1104
  return calculateFee(it, cte, allFees, false, allFeesForCalc);
1062
1105
  }));
1063
- baseNonPercentage = nonPercentageResults.reduce(function (sum, r) { return sum + (r.totalToCalc || 0); }, 0);
1106
+ baseNonPercentage = nonPercentageResults.reduce(function (sum, r) {
1107
+ var _a;
1108
+ var value = r.totalToCalc || 0;
1109
+ if (value > 0 && ((_a = r.fee) === null || _a === void 0 ? void 0 : _a.id)) {
1110
+ nonPercentageDetails.push({
1111
+ feeId: r.fee.id,
1112
+ feeName: r.fee.name || 'Unknown',
1113
+ value: value
1114
+ });
1115
+ }
1116
+ return sum + value;
1117
+ }, 0);
1064
1118
  }
1119
+ console.log('[calculateTotalPercentageFees] Base não-percentual calculada', {
1120
+ baseNonPercentage: baseNonPercentage,
1121
+ nonPercentageFeesCount: nonPercentageFees.length,
1122
+ nonPercentageDetails: nonPercentageDetails
1123
+ });
1065
1124
  // Calcular fees percentuais iterativamente até convergir
1066
1125
  var maxIterations = 10;
1067
1126
  var tolerance = 0.01; // Tolerância de 1 centavo
@@ -1084,6 +1143,14 @@ var calculateTotalPercentageFees = function (allFees, cte, allFeesForCalc, curre
1084
1143
  }
1085
1144
  // Calcular base: fees não-percentuais + outras fees percentuais (exceto ela mesma e excluídas)
1086
1145
  var excludedFeeIds = (feeExclusions === null || feeExclusions === void 0 ? void 0 : feeExclusions.get(pf.fee.id)) || new Set();
1146
+ console.log('[calculateTotalPercentageFees] Calculando fee TOTAL_PERCENTAGE', {
1147
+ feeId: pf.fee.id,
1148
+ feeName: pf.fee.name,
1149
+ percentValue: pf.value,
1150
+ hasExclusions: excludedFeeIds.size > 0,
1151
+ excludedFeeIds: Array.from(excludedFeeIds),
1152
+ iteration: iteration
1153
+ });
1087
1154
  var basePercentage = Array.from(previousValues.entries())
1088
1155
  .filter(function (_a) {
1089
1156
  var feeId = _a[0];
@@ -1096,6 +1163,23 @@ var calculateTotalPercentageFees = function (allFees, cte, allFeesForCalc, curre
1096
1163
  var baseValue = baseNonPercentage + basePercentage;
1097
1164
  var percentValue = (+pf.value / 100);
1098
1165
  var calculatedValue = baseValue * percentValue;
1166
+ console.log('[calculateTotalPercentageFees] Base calculada', {
1167
+ feeId: pf.fee.id,
1168
+ feeName: pf.fee.name,
1169
+ baseNonPercentage: baseNonPercentage,
1170
+ basePercentage: basePercentage,
1171
+ baseValue: baseValue,
1172
+ percentValue: "".concat(pf.value, "%"),
1173
+ calculatedValue: calculatedValue,
1174
+ allPreviousValues: Array.from(previousValues.entries()).map(function (_a) {
1175
+ var id = _a[0], val = _a[1];
1176
+ return ({
1177
+ feeId: id,
1178
+ value: val,
1179
+ excluded: excludedFeeIds.has(id)
1180
+ });
1181
+ })
1182
+ });
1099
1183
  previousValues.set(pf.fee.id, calculatedValue);
1100
1184
  // Armazenar resultado
1101
1185
  results.set(pf.fee.id, __assign(__assign({}, pf), { totalFee: calculatedValue, totalToCalc: calculatedValue, resultFee: "".concat(convertNumberToCurrency(baseValue, 'pt-br'), " x ").concat(+pf.value, "% = ").concat(convertNumberToCurrency(calculatedValue, 'pt-br')) }));
@@ -1171,12 +1255,14 @@ var calculateIcms = function (totalFromAllFees, icmsRate) {
1171
1255
  * Esta função centraliza a lógica de cálculo que estava duplicada em vários lugares do ModalCte.
1172
1256
  */
1173
1257
  var calculateFeesCacheWithDetails = function (options) {
1174
- var fees = options.fees, cte = options.cte, allFeesForCalc = options.allFeesForCalc, _a = options.excludedIndexes, excludedIndexes = _a === void 0 ? new Set() : _a, preCalculatedValues = options.preCalculatedValues, manuallyEditedFeeIds = options.manuallyEditedFeeIds;
1258
+ var fees = options.fees, cte = options.cte, allFeesForCalc = options.allFeesForCalc, _a = options.excludedIndexes, excludedIndexes = _a === void 0 ? new Set() : _a, preCalculatedValues = options.preCalculatedValues, manuallyEditedFeeIds = options.manuallyEditedFeeIds, ratecard = options.ratecard;
1175
1259
  var cache = {};
1176
1260
  // Filtrar fees não excluídas
1177
1261
  var nonExcludedFees = fees.filter(function (_, idx) { return !excludedIndexes.has(idx); });
1178
- // Construir mapa de exclusões a partir das configurações
1179
- var feeExclusions = buildFeeExclusionsMap(fees);
1262
+ // Obter ratecard se não foi fornecido
1263
+ var ratecardToUse = ratecard || getRatecardFromCte(cte) || undefined;
1264
+ // Construir mapa de exclusões a partir das configurações do ratecard
1265
+ var feeExclusions = buildFeeExclusionsMap(ratecardToUse);
1180
1266
  // PASSADA 1: Calcular fees normais (não TOTAL_PERCENTAGE, não ICMS)
1181
1267
  fees.forEach(function (fee, idx) {
1182
1268
  var _a, _b;
@@ -1261,14 +1347,17 @@ var calculateFeesTotalFromCache = function (options) {
1261
1347
  * @param fees - Array de fees a calcular
1262
1348
  * @param cte - CTE para cálculo
1263
1349
  * @param allFeesForCalc - Todas as fees disponíveis para cálculo
1350
+ * @param ratecard - Tarifário (opcional, será extraído do CTE se não fornecido)
1264
1351
  * @returns Total calculado
1265
1352
  */
1266
- var calculateFeesTotal = function (fees, cte, allFeesForCalc) {
1353
+ var calculateFeesTotal = function (fees, cte, allFeesForCalc, ratecard) {
1267
1354
  if (!fees || fees.length === 0)
1268
1355
  return 0;
1269
1356
  var cache = {};
1270
- // Construir mapa de exclusões a partir das configurações
1271
- var feeExclusions = buildFeeExclusionsMap(fees);
1357
+ // Obter ratecard se não foi fornecido
1358
+ var ratecardToUse = ratecard || getRatecardFromCte(cte) || undefined;
1359
+ // Construir mapa de exclusões a partir das configurações do ratecard
1360
+ var feeExclusions = buildFeeExclusionsMap(ratecardToUse);
1272
1361
  // PASSADA 1: Calcular fees normais (não TOTAL_PERCENTAGE, não ICMS)
1273
1362
  fees.forEach(function (fee, idx) {
1274
1363
  var _a, _b;
Binary file