b2m-utils 0.0.289 → 0.0.290

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/build/index.js CHANGED
@@ -583,71 +583,9 @@ var calculateFee = function (ratecardLaneFee, cte, allFees, debug, allFeesForCal
583
583
  case exports.FeeCalculationTypeEnum.TOTAL_PERCENTAGE:
584
584
  if (allFees && Array.isArray(allFees) && (allFees === null || allFees === void 0 ? void 0 : allFees.length) > 0) {
585
585
  var filteredFees = allFees.filter(function (i) { var _a, _b, _c; return ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.id) !== fee_1.id && ((_b = i.fee) === null || _b === void 0 ? void 0 : _b.id) !== exports.FeeEnum.ICMS && ((_c = i.fee) === null || _c === void 0 ? void 0 : _c.parentId) !== fee_1.parentId; });
586
- // Separar fees em dois grupos
587
- var nonPercentageFees = filteredFees.filter(function (i) { var _a; return ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.feeCalculationTypeId) !== exports.FeeCalculationTypeEnum.TOTAL_PERCENTAGE; });
588
- var percentageFees_1 = filteredFees.filter(function (i) { var _a; return ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.feeCalculationTypeId) === exports.FeeCalculationTypeEnum.TOTAL_PERCENTAGE; });
589
- // Calcular fees não-percentuais (base fixa)
590
- var nonPercentageResults_1 = filterSiblingFees(nonPercentageFees.map(function (it) {
586
+ var filteredFeesResults = filterSiblingFees(filteredFees.map(function (it) {
591
587
  return calculateFee(it, cte, allFees, debug, allFeesForCalc);
592
588
  }));
593
- // Calcular fees percentuais iterativamente até convergir
594
- var percentageResults = [];
595
- var maxIterations = 10;
596
- var tolerance_1 = 0.01; // Tolerância de 1 centavo
597
- // Inicializar com valores zerados
598
- var previousValues_1 = new Map();
599
- percentageFees_1.forEach(function (pf) { return previousValues_1.set(pf.fee.id, 0); });
600
- console.log("\n\uD83D\uDD04 Iniciando c\u00E1lculo iterativo para fee ".concat(fee_1.id, " (").concat(fee_1.name, ")"));
601
- console.log("\uD83D\uDCCA Base n\u00E3o-percentual: R$ ".concat(nonPercentageResults_1.reduce(function (sum, r) { return sum + (r.totalToCalc || 0); }, 0).toFixed(2)));
602
- console.log("\uD83D\uDCCB Fees percentuais a calcular: ".concat(percentageFees_1.map(function (f) { var _a; return "".concat((_a = f.fee) === null || _a === void 0 ? void 0 : _a.name, " (").concat(f.value, "%)"); }).join(', ')));
603
- var _loop_1 = function (iteration) {
604
- console.log("\n--- Itera\u00E7\u00E3o ".concat(iteration + 1, " ---"));
605
- // Calcular cada fee percentual com base nos valores atuais das outras
606
- var currentResults = percentageFees_1.map(function (pf) {
607
- var _a;
608
- // Criar uma lista temporária com os valores já calculados das outras fees percentuais
609
- var tempFees = percentageFees_1
610
- .filter(function (f) { return f.fee.id !== pf.fee.id; })
611
- .map(function (f) { return (__assign(__assign({}, f), { totalFee: previousValues_1.get(f.fee.id) || 0, totalToCalc: previousValues_1.get(f.fee.id) || 0 })); });
612
- // Calcular base: fees não-percentuais + outras fees percentuais
613
- var baseNonPercentage = nonPercentageResults_1.reduce(function (sum, r) { return sum + (r.totalToCalc || 0); }, 0);
614
- var basePercentage = tempFees.reduce(function (sum, f) { return sum + (f.totalFee || 0); }, 0);
615
- var baseValue = baseNonPercentage + basePercentage;
616
- var percentValue = (+pf.value / 100);
617
- var calculatedValue = baseValue * percentValue;
618
- console.log(" ".concat((_a = pf.fee) === null || _a === void 0 ? void 0 : _a.name, ": base=").concat(baseValue.toFixed(2), " (").concat(baseNonPercentage.toFixed(2), " + ").concat(basePercentage.toFixed(2), ") \u00D7 ").concat(pf.value, "% = ").concat(calculatedValue.toFixed(2)));
619
- return __assign(__assign({}, pf), { totalFee: calculatedValue, totalToCalc: calculatedValue, fee: pf.fee, feeValue: pf.value, resultFee: "".concat(convertNumberToCurrency(baseValue, 'pt-br'), " x ").concat(+pf.value, "% = ").concat(convertNumberToCurrency(calculatedValue, 'pt-br')) });
620
- });
621
- // Verificar convergência
622
- var hasConverged = true;
623
- currentResults.forEach(function (result) {
624
- var _a;
625
- var prevValue = previousValues_1.get(result.feeId) || 0;
626
- var diff = Math.abs(result.totalFee - prevValue);
627
- if (diff > tolerance_1) {
628
- hasConverged = false;
629
- }
630
- console.log(" ".concat((_a = result.fee) === null || _a === void 0 ? void 0 : _a.name, ": anterior=").concat(prevValue.toFixed(2), ", atual=").concat(result.totalFee.toFixed(2), ", diff=").concat(diff.toFixed(4)));
631
- previousValues_1.set(result.feeId, result.totalFee);
632
- });
633
- percentageResults = currentResults;
634
- if (hasConverged) {
635
- console.log("\u2705 Convergiu na itera\u00E7\u00E3o ".concat(iteration + 1, "!"));
636
- return "break";
637
- }
638
- };
639
- for (var iteration = 0; iteration < maxIterations; iteration++) {
640
- var state_1 = _loop_1(iteration);
641
- if (state_1 === "break")
642
- break;
643
- }
644
- console.log("\n\uD83D\uDCC8 Resultado final das fees percentuais:");
645
- percentageResults.forEach(function (r) {
646
- var _a;
647
- console.log(" ".concat((_a = r.fee) === null || _a === void 0 ? void 0 : _a.name, ": R$ ").concat((r.totalFee || 0).toFixed(2)));
648
- });
649
- // Combinar resultados
650
- var filteredFeesResults = __spreadArray(__spreadArray([], nonPercentageResults_1, true), percentageResults, true);
651
589
  var totalFromAllFees = filteredFeesResults.map(function (result) {
652
590
  if (result === null || result === void 0 ? void 0 : result.totalToCalc) {
653
591
  return result.totalToCalc;
@@ -1055,6 +993,91 @@ var calculateIcms = function (totalFromAllFees, icmsRate) {
1055
993
  };
1056
994
  };
1057
995
 
996
+ /**
997
+ * Calcula todas as fees do tipo TOTAL_PERCENTAGE de forma iterativa
998
+ * para resolver a interdependência entre elas (ex: TRT e GAC)
999
+ */
1000
+ var calculateTotalPercentageFees = function (allFees, cte, allFeesForCalc) {
1001
+ var results = new Map();
1002
+ // Separar fees em dois grupos
1003
+ var nonPercentageFees = allFees.filter(function (i) { var _a; return ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.feeCalculationTypeId) !== exports.FeeCalculationTypeEnum.TOTAL_PERCENTAGE; });
1004
+ var percentageFees = allFees.filter(function (i) { var _a; return ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.feeCalculationTypeId) === exports.FeeCalculationTypeEnum.TOTAL_PERCENTAGE; });
1005
+ // Se não houver fees percentuais, retornar vazio
1006
+ if (percentageFees.length === 0) {
1007
+ return results;
1008
+ }
1009
+ console.log("\n\uD83D\uDD04 Calculando ".concat(percentageFees.length, " fees TOTAL_PERCENTAGE de forma iterativa"));
1010
+ console.log("\uD83D\uDCCB Fees: ".concat(percentageFees.map(function (f) { var _a; return "".concat((_a = f.fee) === null || _a === void 0 ? void 0 : _a.name, " (").concat(f.value, "%)"); }).join(', ')));
1011
+ // Calcular fees não-percentuais (base fixa)
1012
+ var nonPercentageResults = filterSiblingFees(nonPercentageFees.map(function (it) {
1013
+ return calculateFee(it, cte, allFees, false, allFeesForCalc);
1014
+ }));
1015
+ var baseNonPercentage = nonPercentageResults.reduce(function (sum, r) { return sum + (r.totalToCalc || 0); }, 0);
1016
+ console.log("\uD83D\uDCCA Base n\u00E3o-percentual: R$ ".concat(baseNonPercentage.toFixed(2)));
1017
+ // Calcular fees percentuais iterativamente até convergir
1018
+ var maxIterations = 10;
1019
+ var tolerance = 0.01; // Tolerância de 1 centavo
1020
+ // Inicializar com valores zerados
1021
+ var previousValues = new Map();
1022
+ percentageFees.forEach(function (pf) { return previousValues.set(pf.fee.id, 0); });
1023
+ var _loop_1 = function (iteration) {
1024
+ console.log("\n--- Itera\u00E7\u00E3o ".concat(iteration + 1, " ---"));
1025
+ // Calcular cada fee percentual com base nos valores atuais das outras
1026
+ percentageFees.forEach(function (pf) {
1027
+ var _a;
1028
+ // Calcular base: fees não-percentuais + outras fees percentuais (exceto ela mesma)
1029
+ var basePercentage = Array.from(previousValues.entries())
1030
+ .filter(function (_a) {
1031
+ var feeId = _a[0];
1032
+ return feeId !== pf.fee.id;
1033
+ })
1034
+ .reduce(function (sum, _a) {
1035
+ var value = _a[1];
1036
+ return sum + value;
1037
+ }, 0);
1038
+ var baseValue = baseNonPercentage + basePercentage;
1039
+ var percentValue = (+pf.value / 100);
1040
+ var calculatedValue = baseValue * percentValue;
1041
+ console.log(" ".concat((_a = pf.fee) === null || _a === void 0 ? void 0 : _a.name, ": base=").concat(baseValue.toFixed(2), " (").concat(baseNonPercentage.toFixed(2), " + ").concat(basePercentage.toFixed(2), ") \u00D7 ").concat(pf.value, "% = ").concat(calculatedValue.toFixed(2)));
1042
+ previousValues.set(pf.fee.id, calculatedValue);
1043
+ // Armazenar resultado
1044
+ 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')) }));
1045
+ });
1046
+ // Verificar convergência
1047
+ var hasConverged = true;
1048
+ var currentIteration = iteration;
1049
+ if (currentIteration > 0) {
1050
+ percentageFees.forEach(function (pf) {
1051
+ var currentValue = previousValues.get(pf.fee.id) || 0;
1052
+ var result = results.get(pf.fee.id);
1053
+ var prevValue = (result === null || result === void 0 ? void 0 : result.totalFee) || 0;
1054
+ var diff = Math.abs(currentValue - prevValue);
1055
+ if (diff > tolerance) {
1056
+ hasConverged = false;
1057
+ }
1058
+ });
1059
+ }
1060
+ else {
1061
+ hasConverged = false;
1062
+ }
1063
+ if (hasConverged) {
1064
+ console.log("\u2705 Convergiu na itera\u00E7\u00E3o ".concat(iteration + 1, "!"));
1065
+ return "break";
1066
+ }
1067
+ };
1068
+ for (var iteration = 0; iteration < maxIterations; iteration++) {
1069
+ var state_1 = _loop_1(iteration);
1070
+ if (state_1 === "break")
1071
+ break;
1072
+ }
1073
+ console.log("\n\uD83D\uDCC8 Resultado final das fees percentuais:");
1074
+ results.forEach(function (result, feeId) {
1075
+ var _a;
1076
+ console.log(" ".concat((_a = result.fee) === null || _a === void 0 ? void 0 : _a.name, " (").concat(feeId, "): R$ ").concat((result.totalFee || 0).toFixed(2)));
1077
+ });
1078
+ return results;
1079
+ };
1080
+
1058
1081
  var verifyConditionalFee = function (conditionalFeeToVerify, cte) {
1059
1082
  var _a, _b;
1060
1083
  if (conditionalFeeToVerify === null || conditionalFeeToVerify === void 0 ? void 0 : conditionalFeeToVerify.id) {
@@ -8077,6 +8100,7 @@ exports.applyRedeliveryMultiplier = applyRedeliveryMultiplier;
8077
8100
  exports.buildDynamicMapping = buildDynamicMapping;
8078
8101
  exports.calculateFee = calculateFee;
8079
8102
  exports.calculateIcms = calculateIcms;
8103
+ exports.calculateTotalPercentageFees = calculateTotalPercentageFees;
8080
8104
  exports.convertNumberToCurrency = convertNumberToCurrency;
8081
8105
  exports.filterSiblingFees = filterSiblingFees;
8082
8106
  exports.findAuditedMatch = findAuditedMatch;
package/build/index.js.gz CHANGED
Binary file