b2m-utils 0.0.296 → 0.0.298

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.
@@ -0,0 +1,9 @@
1
+ import { Cte, RatecardLaneFee } from "../../types";
2
+ /**
3
+ * Calcula o total de fees de forma consistente, usando cálculo iterativo para TOTAL_PERCENTAGE
4
+ * @param fees - Array de fees a calcular
5
+ * @param cte - CTE para cálculo
6
+ * @param allFeesForCalc - Todas as fees disponíveis para cálculo
7
+ * @returns Total calculado
8
+ */
9
+ export declare const calculateFeesTotal: (fees: RatecardLaneFee[], cte: Cte, allFeesForCalc?: RatecardLaneFee[]) => number;
@@ -1,5 +1,6 @@
1
1
  export * from './applyRedeliveryMultiplier';
2
2
  export * from './calculateFee';
3
+ export * from './calculateFeesTotal';
3
4
  export * from './calculateIcms';
4
5
  export * from './calculateTotalPercentageFees';
5
6
  export * from './convertNumberToCurrency';
@@ -962,41 +962,6 @@ var calculateFee = function (ratecardLaneFee, cte, allFees, debug, allFeesForCal
962
962
  }
963
963
  };
964
964
 
965
- /**
966
- * Calcula o valor do ICMS baseado no total das outras taxas
967
- *
968
- * @param totalFromAllFees - Array com os valores das outras taxas
969
- * @param icmsRate - Alíquota do ICMS (ex: 0.12 para 12%)
970
- * @returns Objeto com o valor calculado e detalhes do cálculo
971
- */
972
- var calculateIcms = function (totalFromAllFees, icmsRate) {
973
- // Filtra valores válidos e soma
974
- var totalValueFromAllFees = totalFromAllFees
975
- .filter(function (value) { return !isNaN(+value) && +value > 0; })
976
- .reduce(function (previous, current) { return +previous + +current; }, 0);
977
- // Verifica se há valor válido para cálculo
978
- if (!totalValueFromAllFees || isNaN(+totalValueFromAllFees)) {
979
- return {
980
- total: 0,
981
- totalValueFromAllFees: 0,
982
- valueToDivide: 0,
983
- firstTotal: 0,
984
- isValid: false
985
- };
986
- }
987
- // Cálculo do ICMS: (soma / (1 - alíquota)) * alíquota
988
- var valueToDivide = (1 - icmsRate).toFixed(2);
989
- var firstTotal = +totalValueFromAllFees / +valueToDivide;
990
- var total = +firstTotal * icmsRate;
991
- return {
992
- total: total,
993
- totalValueFromAllFees: totalValueFromAllFees,
994
- valueToDivide: valueToDivide,
995
- firstTotal: firstTotal,
996
- isValid: true
997
- };
998
- };
999
-
1000
965
  /**
1001
966
  * Calcula todas as fees do tipo TOTAL_PERCENTAGE de forma iterativa
1002
967
  * para resolver a interdependência entre elas (ex: TRT e GAC)
@@ -1091,6 +1056,105 @@ var calculateTotalPercentageFees = function (allFees, cte, allFeesForCalc, preCa
1091
1056
  return results;
1092
1057
  };
1093
1058
 
1059
+ /**
1060
+ * Calcula o valor do ICMS baseado no total das outras taxas
1061
+ *
1062
+ * @param totalFromAllFees - Array com os valores das outras taxas
1063
+ * @param icmsRate - Alíquota do ICMS (ex: 0.12 para 12%)
1064
+ * @returns Objeto com o valor calculado e detalhes do cálculo
1065
+ */
1066
+ var calculateIcms = function (totalFromAllFees, icmsRate) {
1067
+ // Filtra valores válidos e soma
1068
+ var totalValueFromAllFees = totalFromAllFees
1069
+ .filter(function (value) { return !isNaN(+value) && +value > 0; })
1070
+ .reduce(function (previous, current) { return +previous + +current; }, 0);
1071
+ // Verifica se há valor válido para cálculo
1072
+ if (!totalValueFromAllFees || isNaN(+totalValueFromAllFees)) {
1073
+ return {
1074
+ total: 0,
1075
+ totalValueFromAllFees: 0,
1076
+ valueToDivide: 0,
1077
+ firstTotal: 0,
1078
+ isValid: false
1079
+ };
1080
+ }
1081
+ // Cálculo do ICMS: (soma / (1 - alíquota)) * alíquota
1082
+ var valueToDivide = (1 - icmsRate).toFixed(2);
1083
+ var firstTotal = +totalValueFromAllFees / +valueToDivide;
1084
+ var total = +firstTotal * icmsRate;
1085
+ return {
1086
+ total: total,
1087
+ totalValueFromAllFees: totalValueFromAllFees,
1088
+ valueToDivide: valueToDivide,
1089
+ firstTotal: firstTotal,
1090
+ isValid: true
1091
+ };
1092
+ };
1093
+
1094
+ /**
1095
+ * Calcula o total de fees de forma consistente, usando cálculo iterativo para TOTAL_PERCENTAGE
1096
+ * @param fees - Array de fees a calcular
1097
+ * @param cte - CTE para cálculo
1098
+ * @param allFeesForCalc - Todas as fees disponíveis para cálculo
1099
+ * @returns Total calculado
1100
+ */
1101
+ var calculateFeesTotal = function (fees, cte, allFeesForCalc) {
1102
+ if (!fees || fees.length === 0)
1103
+ return 0;
1104
+ var cache = {};
1105
+ // PASSADA 1: Calcular fees normais (não TOTAL_PERCENTAGE, não ICMS)
1106
+ fees.forEach(function (fee, idx) {
1107
+ var _a, _b;
1108
+ if (((_a = fee.fee) === null || _a === void 0 ? void 0 : _a.feeCalculationTypeId) !== FeeCalculationTypeEnum.TOTAL_PERCENTAGE &&
1109
+ ((_b = fee.fee) === null || _b === void 0 ? void 0 : _b.id) !== FeeEnum.ICMS) {
1110
+ cache[idx] = calculateFee(fee, cte, fees, true, allFeesForCalc);
1111
+ }
1112
+ });
1113
+ // PASSADA 2: Calcular TOTAL_PERCENTAGE de forma iterativa
1114
+ var percentageFeesCache = calculateTotalPercentageFees(fees, cte, allFeesForCalc);
1115
+ fees.forEach(function (fee, idx) {
1116
+ var _a, _b;
1117
+ if (((_a = fee.fee) === null || _a === void 0 ? void 0 : _a.feeCalculationTypeId) === FeeCalculationTypeEnum.TOTAL_PERCENTAGE &&
1118
+ ((_b = fee.fee) === null || _b === void 0 ? void 0 : _b.id)) {
1119
+ var cachedResult = percentageFeesCache.get(fee.fee.id);
1120
+ if (cachedResult) {
1121
+ cache[idx] = {
1122
+ totalToCalc: Number((cachedResult.totalToCalc || 0).toFixed(2)),
1123
+ };
1124
+ }
1125
+ }
1126
+ });
1127
+ // PASSADA 3: Calcular ICMS
1128
+ fees.forEach(function (fee, idx) {
1129
+ var _a;
1130
+ if (((_a = fee.fee) === null || _a === void 0 ? void 0 : _a.id) === FeeEnum.ICMS) {
1131
+ var icmsRate = (cte.icmsIncidence !== undefined && cte.icmsIncidence !== null && !isNaN(+cte.icmsIncidence))
1132
+ ? +(cte.icmsIncidence) / 100
1133
+ : fee.value || 0;
1134
+ var valuesWithoutIcms = Object.entries(cache)
1135
+ .filter(function (_a) {
1136
+ var _b;
1137
+ var key = _a[0];
1138
+ var feeIdx = Number(key);
1139
+ var f = fees[feeIdx];
1140
+ return ((_b = f.fee) === null || _b === void 0 ? void 0 : _b.id) !== FeeEnum.ICMS;
1141
+ })
1142
+ .map(function (_a) {
1143
+ var calcFee = _a[1];
1144
+ return (calcFee === null || calcFee === void 0 ? void 0 : calcFee.totalToCalc) || 0;
1145
+ })
1146
+ .filter(function (val) { return val > 0; });
1147
+ var icmsCalculation = calculateIcms(valuesWithoutIcms, icmsRate);
1148
+ if (icmsCalculation.isValid) {
1149
+ cache[idx] = {
1150
+ totalToCalc: Number(icmsCalculation.total.toFixed(2)),
1151
+ };
1152
+ }
1153
+ }
1154
+ });
1155
+ return Object.values(cache).reduce(function (sum, calcFee) { return sum + ((calcFee === null || calcFee === void 0 ? void 0 : calcFee.totalToCalc) || 0); }, 0);
1156
+ };
1157
+
1094
1158
  var verifyConditionalFee = function (conditionalFeeToVerify, cte) {
1095
1159
  var _a, _b;
1096
1160
  if (conditionalFeeToVerify === null || conditionalFeeToVerify === void 0 ? void 0 : conditionalFeeToVerify.id) {
@@ -1442,7 +1506,17 @@ var getCtesFeesResult = function (feesToCalc, cte, allFeesForCalc) {
1442
1506
  if (totalPercentageFees.length > 0) {
1443
1507
  console.log("\n\uD83D\uDD04 [getCtesFeesResult] Calculando ".concat(totalPercentageFees.length, " fees TOTAL_PERCENTAGE"));
1444
1508
  console.log("\uD83D\uDCCB Fees: ".concat(totalPercentageFees.map(function (f) { var _a; return "".concat((_a = f.fee) === null || _a === void 0 ? void 0 : _a.name, " (").concat(f.value, "%)"); }).join(', ')));
1445
- var percentageFeesCache = calculateTotalPercentageFees(feesToCalc, cte, allFeesForCalc);
1509
+ // Criar Map com valores já calculados das fees normais (respeitando lógica de siblings)
1510
+ var preCalculatedValues_1 = new Map();
1511
+ results.forEach(function (r) {
1512
+ var _a;
1513
+ var fee = feesToCalc.find(function (f) { return f.feeId === r.feeId; });
1514
+ if ((_a = fee === null || fee === void 0 ? void 0 : fee.fee) === null || _a === void 0 ? void 0 : _a.id) {
1515
+ preCalculatedValues_1.set(fee.fee.id, r.total);
1516
+ }
1517
+ });
1518
+ console.log("\uD83D\uDCCA Usando ".concat(preCalculatedValues_1.size, " valores pr\u00E9-calculados"));
1519
+ var percentageFeesCache = calculateTotalPercentageFees(feesToCalc, cte, allFeesForCalc, preCalculatedValues_1);
1446
1520
  console.log("\u2705 Cache gerado com ".concat(percentageFeesCache.size, " fees"));
1447
1521
  for (var _g = 0, totalPercentageFees_1 = totalPercentageFees; _g < totalPercentageFees_1.length; _g++) {
1448
1522
  var item = totalPercentageFees_1[_g];
@@ -8121,5 +8195,5 @@ var isTariffMatch = function (chargedName, auditedTariffName) {
8121
8195
  });
8122
8196
  };
8123
8197
 
8124
- export { ApplicationColumnNameEnum, ApplicationEnum, CarrierDocumentConfigTypeKeyEnum, CountryEnum, CteStatusEnum, CteVehicleTypeEnum, CurrencyEnum, DocumentTypeEnum, DomainConfigurationEnum, DomainTypeEnum, EXPORT_CTE_COLUMN_LABELS, EXPORT_CTE_TYPE_LABELS, ExportCteColumn, ExportCteTypeEnum, FeeCalculationTypeEnum, FeeCategoryEnum, FeeEnum, FreightRegionEnum, ImapHostsEnum, InputTypeEnum, ModalEnum, NotificationTypeEnum, PermissionEnum, RatecardConditionalFeeTypeEnum, RatecardFeeConfigKeyEnum, RatecardFeeConfigTypeEnum, RatecardModalEnum, SlaRegionEnum, SpotStatusEnum, TARIFF_MAPPING, TrackProcessProviderTypeEnum, addTariffMapping, applyRedeliveryMultiplier, buildDynamicMapping, calculateFee, calculateIcms, calculateTotalPercentageFees, convertNumberToCurrency, filterSiblingFees, findAuditedMatch, formatDateString, getAllFeesForCalculation, getAuditTotalFromCte, getConfigurationFromDomain, getContractFromFreight, getContractRouteFromFreight, getCookies, getCteDateRange, getCteLane, getCteLaneFeesTotal, getCtesFeesResult, getDataFromToken, getFilteredFeesToAudit, getFormattedFreightPlaceName, getLaneFeesToCalc, getLaneFromRatecard, getNormalizedCityName, getRatecardFromCte, getRouteDeliveryTimeFromFreight, getRouteOnTimeFromFreight, getTariffVariations, isTariffMatch, matchAllTariffs, normalizeString, parseAliases, setFormattedDatesInObjects, verifyConditionalFee, verifyDefaultFees };
8198
+ export { ApplicationColumnNameEnum, ApplicationEnum, CarrierDocumentConfigTypeKeyEnum, CountryEnum, CteStatusEnum, CteVehicleTypeEnum, CurrencyEnum, DocumentTypeEnum, DomainConfigurationEnum, DomainTypeEnum, EXPORT_CTE_COLUMN_LABELS, EXPORT_CTE_TYPE_LABELS, ExportCteColumn, ExportCteTypeEnum, FeeCalculationTypeEnum, FeeCategoryEnum, FeeEnum, FreightRegionEnum, ImapHostsEnum, InputTypeEnum, ModalEnum, NotificationTypeEnum, PermissionEnum, RatecardConditionalFeeTypeEnum, RatecardFeeConfigKeyEnum, RatecardFeeConfigTypeEnum, RatecardModalEnum, SlaRegionEnum, SpotStatusEnum, TARIFF_MAPPING, TrackProcessProviderTypeEnum, addTariffMapping, applyRedeliveryMultiplier, buildDynamicMapping, calculateFee, calculateFeesTotal, calculateIcms, calculateTotalPercentageFees, convertNumberToCurrency, filterSiblingFees, findAuditedMatch, formatDateString, getAllFeesForCalculation, getAuditTotalFromCte, getConfigurationFromDomain, getContractFromFreight, getContractRouteFromFreight, getCookies, getCteDateRange, getCteLane, getCteLaneFeesTotal, getCtesFeesResult, getDataFromToken, getFilteredFeesToAudit, getFormattedFreightPlaceName, getLaneFeesToCalc, getLaneFromRatecard, getNormalizedCityName, getRatecardFromCte, getRouteDeliveryTimeFromFreight, getRouteOnTimeFromFreight, getTariffVariations, isTariffMatch, matchAllTariffs, normalizeString, parseAliases, setFormattedDatesInObjects, verifyConditionalFee, verifyDefaultFees };
8125
8199
  //# sourceMappingURL=index.esm.js.map
Binary file