b2m-utils 0.0.229 → 0.0.231

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
@@ -367,6 +367,16 @@ function __generator(thisArg, body) {
367
367
  }
368
368
  }
369
369
 
370
+ function __spreadArray(to, from, pack) {
371
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
372
+ if (ar || !(i in from)) {
373
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
374
+ ar[i] = from[i];
375
+ }
376
+ }
377
+ return to.concat(ar || Array.prototype.slice.call(from));
378
+ }
379
+
370
380
  typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
371
381
  var e = new Error(message);
372
382
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
@@ -814,27 +824,39 @@ var calculateFee = function (ratecardLaneFee, cte, allFees, debug, allFeesForCal
814
824
  }
815
825
  };
816
826
 
817
- var getCteLane = function (cte) {
818
- var _a, _b, _c, _d, _e;
819
- if (cte === null || cte === void 0 ? void 0 : cte.carrier) {
820
- var carrier = cte === null || cte === void 0 ? void 0 : cte.carrier;
821
- if ((_a = carrier === null || carrier === void 0 ? void 0 : carrier.Ratecard) === null || _a === void 0 ? void 0 : _a.length) {
822
- var destinationUf_1 = (_c = (_b = cte === null || cte === void 0 ? void 0 : cte.cityDestination) === null || _b === void 0 ? void 0 : _b.state) === null || _c === void 0 ? void 0 : _c.uf;
823
- if (carrier === null || carrier === void 0 ? void 0 : carrier.Ratecard[0]) {
824
- var ratecard = carrier === null || carrier === void 0 ? void 0 : carrier.Ratecard[0];
825
- if (ratecard.RatecardLane && ((_d = ratecard.RatecardLane) === null || _d === void 0 ? void 0 : _d.length) > 0 && cte.cityOriginId && destinationUf_1) {
826
- var region = (_e = ratecard.RatecardRegionCity) === null || _e === void 0 ? void 0 : _e.find(function (it) { return it.cityId === cte.cityDestinationId; });
827
- var regionId_1 = (region === null || region === void 0 ? void 0 : region.ratecardRegionId) ? region.ratecardRegionId : (region === null || region === void 0 ? void 0 : region.regionId) ? region.regionId : 0;
828
- return ratecard.RatecardLane.find(function (i) {
829
- if (i.cityOriginId === cte.cityOriginId && i.ufDestination === destinationUf_1 && i.ratecardRegionId === regionId_1) {
830
- return true;
831
- }
832
- return false;
833
- });
834
- }
835
- }
836
- }
827
+ /**
828
+ * Calcula o valor do ICMS baseado no total das outras taxas
829
+ *
830
+ * @param totalFromAllFees - Array com os valores das outras taxas
831
+ * @param icmsRate - Alíquota do ICMS (ex: 0.12 para 12%)
832
+ * @returns Objeto com o valor calculado e detalhes do cálculo
833
+ */
834
+ var calculateIcms = function (totalFromAllFees, icmsRate) {
835
+ // Filtra valores válidos e soma
836
+ var totalValueFromAllFees = totalFromAllFees
837
+ .filter(function (value) { return !isNaN(+value) && +value > 0; })
838
+ .reduce(function (previous, current) { return +previous + +current; }, 0);
839
+ // Verifica se valor válido para cálculo
840
+ if (!totalValueFromAllFees || isNaN(+totalValueFromAllFees)) {
841
+ return {
842
+ total: 0,
843
+ totalValueFromAllFees: 0,
844
+ valueToDivide: 0,
845
+ firstTotal: 0,
846
+ isValid: false
847
+ };
837
848
  }
849
+ // Cálculo do ICMS: (soma / (1 - alíquota)) * alíquota
850
+ var valueToDivide = (1 - icmsRate).toFixed(2);
851
+ var firstTotal = +totalValueFromAllFees / +valueToDivide;
852
+ var total = +firstTotal * icmsRate;
853
+ return {
854
+ total: total,
855
+ totalValueFromAllFees: totalValueFromAllFees,
856
+ valueToDivide: valueToDivide,
857
+ firstTotal: firstTotal,
858
+ isValid: true
859
+ };
838
860
  };
839
861
 
840
862
  var verifyConditionalFee = function (conditionalFeeToVerify, cte) {
@@ -857,83 +879,220 @@ var verifyConditionalFee = function (conditionalFeeToVerify, cte) {
857
879
  return false;
858
880
  };
859
881
 
860
- var getLaneFeesToCalc = function (cte) {
861
- var _a, _b;
862
- var ratecard = getRatecardFromCte(cte);
863
- var lane = getCteLane(cte);
864
- if ((_a = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _a === void 0 ? void 0 : _a.length) {
865
- var newFilteredFees = (_b = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _b === void 0 ? void 0 : _b.filter(function (i) {
866
- var _a, _b, _c, _d, _e;
867
- var defaultConditionalFees = [
868
- exports.FeeEnum.TDA_FREIGHT,
869
- exports.FeeEnum.TDA_MIN,
870
- exports.FeeEnum.TDE_FREIGHT,
871
- exports.FeeEnum.TDE_MIN,
872
- ];
873
- var conditionalFeeToVerify;
874
- var conditionalFees = (_a = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardConditionalFee) === null || _a === void 0 ? void 0 : _a.filter(function (it) { var _a; return it.feeId === ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.id); });
875
- if (defaultConditionalFees.includes((_b = i.fee) === null || _b === void 0 ? void 0 : _b.id) && !(conditionalFees === null || conditionalFees === void 0 ? void 0 : conditionalFees.length)) {
876
- return false;
882
+ var getFilteredFeesToAudit = function (_a) {
883
+ var _b;
884
+ var lane = _a.lane, ratecard = _a.ratecard, cte = _a.cte;
885
+ var filteredFees = (_b = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _b === void 0 ? void 0 : _b.filter(function (i) {
886
+ var _a, _b, _c, _d, _e, _f, _g;
887
+ var defaultConditionalFees = [
888
+ exports.FeeEnum.SUFRAMA,
889
+ exports.FeeEnum.TDA_FREIGHT,
890
+ exports.FeeEnum.TDA_MIN,
891
+ exports.FeeEnum.TDE_FREIGHT,
892
+ exports.FeeEnum.TDE_MIN,
893
+ exports.FeeEnum.TRT_FREIGHT,
894
+ exports.FeeEnum.TRT_MIN,
895
+ 94,
896
+ ];
897
+ var collectFees = [
898
+ exports.FeeEnum.COLLECT_PERCENTAGE_TOTAL,
899
+ exports.FeeEnum.COLLECT_REVERSE_PERCENTAGE_TOTAL,
900
+ ];
901
+ if (collectFees.includes((_a = i.fee) === null || _a === void 0 ? void 0 : _a.id)) {
902
+ switch ((_b = i.fee) === null || _b === void 0 ? void 0 : _b.id) {
903
+ case exports.FeeEnum.COLLECT_PERCENTAGE_TOTAL:
904
+ return cte.isCollect;
905
+ case exports.FeeEnum.COLLECT_REVERSE_PERCENTAGE_TOTAL:
906
+ return cte.isCollectReverse;
877
907
  }
878
- if (conditionalFees && (conditionalFees === null || conditionalFees === void 0 ? void 0 : conditionalFees.length) > 0) {
879
- var _loop_1 = function (index) {
880
- var conditionalFee = conditionalFees[index];
881
- if (conditionalFee) {
882
- conditionalFeeToVerify = conditionalFee;
883
- }
884
- else if ((_c = i.fee) === null || _c === void 0 ? void 0 : _c.parentId) {
885
- var siblingFee_1 = (_d = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _d === void 0 ? void 0 : _d.find(function (it) { var _a, _b; return ((_a = it.fee) === null || _a === void 0 ? void 0 : _a.parentId) === i.fee.parentId && ((_b = it.fee) === null || _b === void 0 ? void 0 : _b.id) !== i.fee.id; });
886
- if (siblingFee_1) {
887
- var conditionalFeeSibling = (_e = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardConditionalFee) === null || _e === void 0 ? void 0 : _e.find(function (i) { var _a; return i.feeId === ((_a = siblingFee_1.fee) === null || _a === void 0 ? void 0 : _a.id); });
888
- if (conditionalFeeSibling) {
889
- conditionalFeeToVerify = conditionalFeeSibling;
890
- }
908
+ }
909
+ var conditionalFeeToVerify;
910
+ var conditionalFees = (_c = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardConditionalFee) === null || _c === void 0 ? void 0 : _c.filter(function (it) { var _a; return it.feeId === ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.id); });
911
+ if (defaultConditionalFees.includes((_d = i.fee) === null || _d === void 0 ? void 0 : _d.id) && !(conditionalFees === null || conditionalFees === void 0 ? void 0 : conditionalFees.length)) {
912
+ return false;
913
+ }
914
+ if (conditionalFees && (conditionalFees === null || conditionalFees === void 0 ? void 0 : conditionalFees.length) > 0) {
915
+ var _loop_1 = function (index) {
916
+ var conditionalFee = conditionalFees[index];
917
+ if (conditionalFee) {
918
+ conditionalFeeToVerify = conditionalFee;
919
+ }
920
+ else if ((_e = i.fee) === null || _e === void 0 ? void 0 : _e.parentId) {
921
+ var siblingFee_1 = (_f = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _f === void 0 ? void 0 : _f.find(function (it) { var _a, _b; return ((_a = it.fee) === null || _a === void 0 ? void 0 : _a.parentId) === i.fee.parentId && ((_b = it.fee) === null || _b === void 0 ? void 0 : _b.id) !== i.fee.id; });
922
+ if (siblingFee_1) {
923
+ var conditionalFeeSibling = (_g = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardConditionalFee) === null || _g === void 0 ? void 0 : _g.find(function (i) { var _a; return i.feeId === ((_a = siblingFee_1.fee) === null || _a === void 0 ? void 0 : _a.id); });
924
+ if (conditionalFeeSibling) {
925
+ conditionalFeeToVerify = conditionalFeeSibling;
891
926
  }
892
927
  }
893
- if (conditionalFeeToVerify === null || conditionalFeeToVerify === void 0 ? void 0 : conditionalFeeToVerify.id) {
894
- var result = verifyConditionalFee(conditionalFeeToVerify, cte);
895
- if (result) {
896
- return { value: true };
897
- }
898
- else if (index === conditionalFees.length - 1) {
899
- return { value: false };
900
- }
928
+ }
929
+ if (conditionalFeeToVerify === null || conditionalFeeToVerify === void 0 ? void 0 : conditionalFeeToVerify.id) {
930
+ var result = verifyConditionalFee(conditionalFeeToVerify, cte);
931
+ if (result) {
932
+ return { value: true };
933
+ }
934
+ else if (index === conditionalFees.length - 1) {
935
+ return { value: false };
901
936
  }
902
- };
903
- for (var index = 0; index < conditionalFees.length; index++) {
904
- var state_1 = _loop_1(index);
905
- if (typeof state_1 === "object")
906
- return state_1.value;
907
937
  }
938
+ };
939
+ for (var index = 0; index < conditionalFees.length; index++) {
940
+ var state_1 = _loop_1(index);
941
+ if (typeof state_1 === "object")
942
+ return state_1.value;
908
943
  }
909
- if (i.minWeight) {
910
- if (cte === null || cte === void 0 ? void 0 : cte.taxedWeight) {
911
- if (Math.ceil(+cte.taxedWeight) >= +i.minWeight) {
912
- if (Math.ceil(+cte.taxedWeight) <= +i.maxWeight) {
913
- return true;
914
- }
915
- else if (!i.maxWeight) {
916
- return true;
917
- }
918
- }
944
+ }
945
+ if (i.minKm !== null && i.minKm !== undefined) {
946
+ if (cte === null || cte === void 0 ? void 0 : cte.distance) {
947
+ var distanceInRange = +cte.distance >= +i.minKm && (!i.maxKm || +cte.distance <= +i.maxKm);
948
+ var vehicleTypeMatches = !i.vehicleTypeId || cte.vehicleTypeId === i.vehicleTypeId;
949
+ if (distanceInRange && vehicleTypeMatches) {
950
+ return true;
919
951
  }
920
952
  }
921
- else {
922
- return true;
953
+ }
954
+ else if (i.minWeight) {
955
+ if (cte === null || cte === void 0 ? void 0 : cte.taxedWeight) {
956
+ if (Math.ceil(+cte.taxedWeight) >= +i.minWeight) {
957
+ if (Math.ceil(+cte.taxedWeight) <= +i.maxWeight) {
958
+ return true;
959
+ }
960
+ else if (!i.maxWeight) {
961
+ return true;
962
+ }
963
+ }
923
964
  }
965
+ }
966
+ else {
967
+ return true;
968
+ }
969
+ return false;
970
+ });
971
+ // Remover fees duplicadas, mantendo apenas uma ocorrência de cada feeId
972
+ var seenFeeIds = new Set();
973
+ var uniqueFees = filteredFees === null || filteredFees === void 0 ? void 0 : filteredFees.filter(function (fee) {
974
+ if (fee.feeId && seenFeeIds.has(fee.feeId)) {
924
975
  return false;
925
- });
926
- if ((newFilteredFees === null || newFilteredFees === void 0 ? void 0 : newFilteredFees.length) > 0) {
927
- return newFilteredFees;
928
976
  }
977
+ if (fee.feeId) {
978
+ seenFeeIds.add(fee.feeId);
979
+ }
980
+ return true;
981
+ });
982
+ return uniqueFees;
983
+ };
984
+
985
+ var getAllFeesForCalculation = function (_a) {
986
+ var _b;
987
+ var lane = _a.lane, ratecard = _a.ratecard, cte = _a.cte;
988
+ // Obter taxas aplicáveis (função atual)
989
+ var applicableFees = getFilteredFeesToAudit({ lane: lane, ratecard: ratecard, cte: cte });
990
+ // Extrair tipos de taxas únicos das taxas aplicáveis
991
+ var feeTypes = Array.from(new Set(applicableFees === null || applicableFees === void 0 ? void 0 : applicableFees.map(function (fee) { var _a; return (_a = fee.fee) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean)));
992
+ // Encontrar taxas de intervalo do mesmo tipo
993
+ var intervalFees = (_b = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _b === void 0 ? void 0 : _b.filter(function (fee) {
994
+ var _a;
995
+ return feeTypes.includes((_a = fee.fee) === null || _a === void 0 ? void 0 : _a.id) &&
996
+ (fee.minWeight || fee.maxWeight);
997
+ });
998
+ // Combinar taxas aplicáveis com taxas de intervalo, removendo duplicatas
999
+ var allFees = __spreadArray(__spreadArray([], (applicableFees || []), true), (intervalFees || []), true);
1000
+ var uniqueFees = Array.from(new Map(allFees.map(function (fee) { return [fee.id, fee]; })).values());
1001
+ return uniqueFees;
1002
+ };
1003
+
1004
+ var getLaneFromRatecard = function (cte) {
1005
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
1006
+ var ratecard = getRatecardFromCte(cte);
1007
+ var cityOriginId = cte.cityOriginId, cityDestination = cte.cityDestination;
1008
+ var destinationUf = (_a = cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.state) === null || _a === void 0 ? void 0 : _a.uf;
1009
+ // Encontrar a ratecardRegion da cidade de destino
1010
+ var destinationRatecardRegionId = (_c = (_b = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardRegionCity) === null || _b === void 0 ? void 0 : _b.find(function (regionCity) { return regionCity.cityId === (cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.id); })) === null || _c === void 0 ? void 0 : _c.ratecardRegionId;
1011
+ if (!(ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardLane) || ((_d = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardLane) === null || _d === void 0 ? void 0 : _d.length) === 0) {
1012
+ return undefined;
1013
+ }
1014
+ // Lógica diferenciada por modal
1015
+ switch (ratecard.modalId) {
1016
+ case exports.RatecardModalEnum.ROAD_DOMESTIC_FTL:
1017
+ // FTL: Verificar rota por UF de destino
1018
+ if (destinationUf) {
1019
+ var directLane = ratecard.RatecardLane.find(function (i) {
1020
+ return i.ufDestination === destinationUf && i.ratecardRegionId === destinationRatecardRegionId;
1021
+ });
1022
+ if (directLane) {
1023
+ return directLane;
1024
+ }
1025
+ // Fallback: Verificar se existe lane única com fees de KM e cidade origem no ratecard_origin_cities
1026
+ var uniqueLane = ratecard.RatecardLane[0];
1027
+ // Verificar se a lane tem fees com intervalo de KM
1028
+ var hasKmFees = (_e = uniqueLane === null || uniqueLane === void 0 ? void 0 : uniqueLane.RatecardLaneFee) === null || _e === void 0 ? void 0 : _e.some(function (fee) { return fee.minKm !== null; });
1029
+ // Verificar se a cidade de origem está no ratecard_origin_cities
1030
+ var hasOriginCity = (_f = ratecard.ratecard_origin_cities) === null || _f === void 0 ? void 0 : _f.some(function (originCity) { return originCity.cityId === cityOriginId; });
1031
+ if (hasKmFees && hasOriginCity) {
1032
+ // Mockar informações para exibição no frontend
1033
+ return __assign(__assign({}, uniqueLane), { city: cte.cityOrigin, ufDestination: destinationUf, ratecardRegion: uniqueLane.ratecardRegion || { name: destinationUf } });
1034
+ }
1035
+ // Rota inversa FTL: Verificar se cidade de destino está em ratecard_origin_cities
1036
+ var originUf_1 = (_h = (_g = cte.cityOrigin) === null || _g === void 0 ? void 0 : _g.state) === null || _h === void 0 ? void 0 : _h.uf;
1037
+ if (originUf_1) {
1038
+ // Verificar se existe lane com ufDestination = originUf
1039
+ var reverseLane = ratecard.RatecardLane.find(function (i) {
1040
+ return i.ufDestination === originUf_1;
1041
+ });
1042
+ if (reverseLane) {
1043
+ // Verificar se a cidade de destino está no ratecard_origin_cities
1044
+ var hasDestinationCity = (_j = ratecard.ratecard_origin_cities) === null || _j === void 0 ? void 0 : _j.some(function (originCity) { return originCity.cityId === (cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.id); });
1045
+ if (hasDestinationCity) {
1046
+ return reverseLane;
1047
+ }
1048
+ }
1049
+ // Fallback inverso: Lane única com cidade de destino em ratecard_origin_cities
1050
+ var hasDestinationCityInOrigins = (_k = ratecard.ratecard_origin_cities) === null || _k === void 0 ? void 0 : _k.some(function (originCity) { return originCity.cityId === (cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.id); });
1051
+ if (hasKmFees && hasDestinationCityInOrigins) {
1052
+ // Mockar informações para exibição no frontend (rota inversa)
1053
+ return __assign(__assign({}, uniqueLane), { city: cityDestination, ufDestination: originUf_1, ratecardRegion: uniqueLane.ratecardRegion || { name: originUf_1 } });
1054
+ }
1055
+ }
1056
+ }
1057
+ break;
1058
+ case exports.RatecardModalEnum.ROAD_DOMESTIC_LTL:
1059
+ default:
1060
+ // LTL: Lógica original (rota direta + inversa)
1061
+ if (cityOriginId && destinationUf) {
1062
+ // Primeiro, buscar rota direta (Origem -> Destino)
1063
+ var directLane = ratecard.RatecardLane.find(function (i) {
1064
+ return i.cityOriginId === cityOriginId && i.ufDestination === destinationUf && i.ratecardRegionId === destinationRatecardRegionId;
1065
+ });
1066
+ if (directLane) {
1067
+ return directLane;
1068
+ }
1069
+ // Se não encontrar rota direta, buscar rota inversa (Destino -> Origem)
1070
+ // Para isso, precisamos encontrar a UF da origem e sua ratecardRegion
1071
+ var originUf_2 = (_m = (_l = cte.cityOrigin) === null || _l === void 0 ? void 0 : _l.state) === null || _m === void 0 ? void 0 : _m.uf;
1072
+ // Encontrar a ratecardRegion da cidade de origem
1073
+ var originRatecardRegionId_1 = (_p = (_o = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardRegionCity) === null || _o === void 0 ? void 0 : _o.find(function (regionCity) { return regionCity.cityId === cityOriginId; })) === null || _p === void 0 ? void 0 : _p.ratecardRegionId;
1074
+ if (originUf_2) {
1075
+ var reverseLane = ratecard.RatecardLane.find(function (i) {
1076
+ return i.cityOriginId === (cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.id) && i.ufDestination === originUf_2 && i.ratecardRegionId === originRatecardRegionId_1;
1077
+ });
1078
+ if (reverseLane) {
1079
+ return reverseLane;
1080
+ }
1081
+ }
1082
+ }
1083
+ break;
929
1084
  }
1085
+ return undefined;
930
1086
  };
931
1087
 
932
- var getCtesFeesResult = function (feesToCalc, cte) {
933
- var _a, _b, _c, _d;
1088
+ var getCtesFeesResult = function (feesToCalc, cte, allFeesForCalc) {
1089
+ var _a, _b, _c;
934
1090
  var results = [];
1091
+ // Separar ICMS das outras fees
1092
+ var icmsFee = feesToCalc.find(function (f) { var _a; return ((_a = f.fee) === null || _a === void 0 ? void 0 : _a.id) === exports.FeeEnum.ICMS; });
1093
+ var nonIcmsFees = feesToCalc.filter(function (f) { var _a; return ((_a = f.fee) === null || _a === void 0 ? void 0 : _a.id) !== exports.FeeEnum.ICMS; });
935
1094
  var _loop_1 = function (item) {
936
- var feeTotal = calculateFee(item, cte, feesToCalc);
1095
+ var feeTotal = calculateFee(item, cte, feesToCalc, false, allFeesForCalc);
937
1096
  if (feeTotal === null || feeTotal === void 0 ? void 0 : feeTotal.totalFee) {
938
1097
  var totalFee = feeTotal.totalFee, resultFee = feeTotal.resultFee, feeValue = feeTotal.feeValue;
939
1098
  var totalToPush = totalFee;
@@ -942,9 +1101,9 @@ var getCtesFeesResult = function (feesToCalc, cte) {
942
1101
  var siblingFees = feesToCalc === null || feesToCalc === void 0 ? void 0 : feesToCalc.filter(function (i) { var _a, _b; return ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.parentId) === fee_1.parentId && ((_b = i.fee) === null || _b === void 0 ? void 0 : _b.id) !== fee_1.id; });
943
1102
  if (siblingFees && (siblingFees === null || siblingFees === void 0 ? void 0 : siblingFees.length) > 0) {
944
1103
  var siblingFeesResults = [];
945
- for (var _e = 0, siblingFees_1 = siblingFees; _e < siblingFees_1.length; _e++) {
946
- var item_1 = siblingFees_1[_e];
947
- var result = calculateFee(item_1, cte);
1104
+ for (var _d = 0, siblingFees_1 = siblingFees; _d < siblingFees_1.length; _d++) {
1105
+ var item_1 = siblingFees_1[_d];
1106
+ var result = calculateFee(item_1, cte, feesToCalc, false, allFeesForCalc);
948
1107
  siblingFeesResults.push(result);
949
1108
  }
950
1109
  siblingFeesResults.sort(function (a, b) {
@@ -962,24 +1121,45 @@ var getCtesFeesResult = function (feesToCalc, cte) {
962
1121
  }
963
1122
  if (!isNaN(+totalToPush)) {
964
1123
  results.push({
965
- total: totalToPush,
1124
+ total: +(totalToPush).toFixed(2),
966
1125
  resultFee: resultFee,
967
1126
  feeValue: feeValue,
968
- feeId: (_d = item.fee) === null || _d === void 0 ? void 0 : _d.id,
1127
+ feeId: item.feeId,
969
1128
  });
970
1129
  }
971
1130
  }
972
1131
  };
973
- for (var _i = 0, feesToCalc_1 = feesToCalc; _i < feesToCalc_1.length; _i++) {
974
- var item = feesToCalc_1[_i];
1132
+ // PRIMEIRA PASSADA: Calcular todas as fees exceto ICMS
1133
+ for (var _i = 0, nonIcmsFees_1 = nonIcmsFees; _i < nonIcmsFees_1.length; _i++) {
1134
+ var item = nonIcmsFees_1[_i];
975
1135
  _loop_1(item);
976
1136
  }
1137
+ // SEGUNDA PASSADA: Calcular ICMS com base nos resultados já filtrados
1138
+ if (icmsFee) {
1139
+ // Coletar apenas os valores das fees que realmente contam (total > 0)
1140
+ var valuesForIcms = results
1141
+ .filter(function (r) { return r.total > 0; })
1142
+ .map(function (r) { return r.total; });
1143
+ var icmsRate = (cte.icmsIncidence !== undefined && cte.icmsIncidence !== null && !isNaN(+cte.icmsIncidence))
1144
+ ? +(cte.icmsIncidence) / 100
1145
+ : icmsFee.value || 0;
1146
+ // Usar calculateIcms diretamente
1147
+ var icmsCalculation = calculateIcms(valuesForIcms, icmsRate);
1148
+ if (icmsCalculation.isValid && !isNaN(+icmsCalculation.total)) {
1149
+ results.push({
1150
+ total: +(icmsCalculation.total).toFixed(2),
1151
+ resultFee: "(".concat(icmsCalculation.totalValueFromAllFees.toFixed(2), " / ").concat(icmsCalculation.valueToDivide, ") x ").concat(icmsRate, " = ").concat(icmsCalculation.total.toFixed(2)),
1152
+ feeValue: icmsRate,
1153
+ feeId: icmsFee.feeId,
1154
+ });
1155
+ }
1156
+ }
977
1157
  return results;
978
1158
  };
979
1159
 
980
- var getCteLaneFeesTotal = function (feesToCalc, cte) {
1160
+ var getCteLaneFeesTotal = function (feesToCalc, cte, allFeesForCalc) {
981
1161
  if ((feesToCalc === null || feesToCalc === void 0 ? void 0 : feesToCalc.length) > 0) {
982
- var results = getCtesFeesResult(feesToCalc, cte);
1162
+ var results = getCtesFeesResult(feesToCalc, cte, allFeesForCalc);
983
1163
  /*const results = [];
984
1164
 
985
1165
  for (const item of feesToCalc) {
@@ -1052,9 +1232,26 @@ var getCteLaneFeesTotal = function (feesToCalc, cte) {
1052
1232
  };
1053
1233
 
1054
1234
  var getAuditTotalFromCte = function (cte) {
1055
- var laneFees = getLaneFeesToCalc(cte);
1056
- var total = getCteLaneFeesTotal(laneFees !== null && laneFees !== void 0 ? laneFees : [], cte);
1057
- if (cte.id === 38) ;
1235
+ var lane = getLaneFromRatecard(cte);
1236
+ var ratecard = getRatecardFromCte(cte);
1237
+ // Obter taxas filtradas com lógica de coleta
1238
+ var laneFees = lane && ratecard ?
1239
+ getFilteredFeesToAudit({ lane: lane, ratecard: ratecard, cte: cte }) : [];
1240
+ // Obter todas as taxas para cálculo
1241
+ var allFeesForCalc = lane && ratecard ?
1242
+ getAllFeesForCalculation({
1243
+ lane: lane,
1244
+ ratecard: ratecard,
1245
+ cte: cte
1246
+ }) : [];
1247
+ var total = getCteLaneFeesTotal(laneFees || [], cte, allFeesForCalc);
1248
+ // Se for reentrega, verificar o valor mínimo
1249
+ if (cte.isRedelivery && total) {
1250
+ var ratecard_1 = getRatecardFromCte(cte);
1251
+ if ((ratecard_1 === null || ratecard_1 === void 0 ? void 0 : ratecard_1.redeliveryMinValue) && total < ratecard_1.redeliveryMinValue) {
1252
+ return +ratecard_1.redeliveryMinValue;
1253
+ }
1254
+ }
1058
1255
  return total !== null && total !== void 0 ? total : 0;
1059
1256
  };
1060
1257
 
@@ -7189,176 +7386,99 @@ var getCteDateRange = function (ctes) {
7189
7386
  return "".concat(formatDate(oldest), " - ").concat(formatDate(newest));
7190
7387
  };
7191
7388
 
7192
- var getFilteredFeesToAudit = function (_a) {
7193
- var _b;
7194
- var lane = _a.lane, ratecard = _a.ratecard, cte = _a.cte;
7195
- var filteredFees = (_b = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _b === void 0 ? void 0 : _b.filter(function (i) {
7196
- var _a, _b, _c, _d, _e;
7197
- var defaultConditionalFees = [
7198
- exports.FeeEnum.SUFRAMA,
7199
- exports.FeeEnum.TDA_FREIGHT,
7200
- exports.FeeEnum.TDA_MIN,
7201
- exports.FeeEnum.TDE_FREIGHT,
7202
- exports.FeeEnum.TDE_MIN,
7203
- ];
7204
- var conditionalFeeToVerify;
7205
- var conditionalFees = (_a = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardConditionalFee) === null || _a === void 0 ? void 0 : _a.filter(function (it) { var _a; return it.feeId === ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.id); });
7206
- if (defaultConditionalFees.includes((_b = i.fee) === null || _b === void 0 ? void 0 : _b.id) && !(conditionalFees === null || conditionalFees === void 0 ? void 0 : conditionalFees.length)) {
7207
- return false;
7208
- }
7209
- if (conditionalFees && (conditionalFees === null || conditionalFees === void 0 ? void 0 : conditionalFees.length) > 0) {
7210
- var _loop_1 = function (index) {
7211
- var conditionalFee = conditionalFees[index];
7212
- if (conditionalFee) {
7213
- conditionalFeeToVerify = conditionalFee;
7214
- }
7215
- else if ((_c = i.fee) === null || _c === void 0 ? void 0 : _c.parentId) {
7216
- var siblingFee_1 = (_d = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _d === void 0 ? void 0 : _d.find(function (it) { var _a, _b; return ((_a = it.fee) === null || _a === void 0 ? void 0 : _a.parentId) === i.fee.parentId && ((_b = it.fee) === null || _b === void 0 ? void 0 : _b.id) !== i.fee.id; });
7217
- if (siblingFee_1) {
7218
- var conditionalFeeSibling = (_e = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardConditionalFee) === null || _e === void 0 ? void 0 : _e.find(function (i) { var _a; return i.feeId === ((_a = siblingFee_1.fee) === null || _a === void 0 ? void 0 : _a.id); });
7219
- if (conditionalFeeSibling) {
7220
- conditionalFeeToVerify = conditionalFeeSibling;
7389
+ var getCteLane = function (cte) {
7390
+ var _a, _b, _c, _d, _e;
7391
+ if (cte === null || cte === void 0 ? void 0 : cte.carrier) {
7392
+ var carrier = cte === null || cte === void 0 ? void 0 : cte.carrier;
7393
+ if ((_a = carrier === null || carrier === void 0 ? void 0 : carrier.Ratecard) === null || _a === void 0 ? void 0 : _a.length) {
7394
+ var destinationUf_1 = (_c = (_b = cte === null || cte === void 0 ? void 0 : cte.cityDestination) === null || _b === void 0 ? void 0 : _b.state) === null || _c === void 0 ? void 0 : _c.uf;
7395
+ if (carrier === null || carrier === void 0 ? void 0 : carrier.Ratecard[0]) {
7396
+ var ratecard = carrier === null || carrier === void 0 ? void 0 : carrier.Ratecard[0];
7397
+ if (ratecard.RatecardLane && ((_d = ratecard.RatecardLane) === null || _d === void 0 ? void 0 : _d.length) > 0 && cte.cityOriginId && destinationUf_1) {
7398
+ var region = (_e = ratecard.RatecardRegionCity) === null || _e === void 0 ? void 0 : _e.find(function (it) { return it.cityId === cte.cityDestinationId; });
7399
+ var regionId_1 = (region === null || region === void 0 ? void 0 : region.ratecardRegionId) ? region.ratecardRegionId : (region === null || region === void 0 ? void 0 : region.regionId) ? region.regionId : 0;
7400
+ return ratecard.RatecardLane.find(function (i) {
7401
+ if (i.cityOriginId === cte.cityOriginId && i.ufDestination === destinationUf_1 && i.ratecardRegionId === regionId_1) {
7402
+ return true;
7221
7403
  }
7222
- }
7223
- }
7224
- if (conditionalFeeToVerify === null || conditionalFeeToVerify === void 0 ? void 0 : conditionalFeeToVerify.id) {
7225
- var result = verifyConditionalFee(conditionalFeeToVerify, cte);
7226
- if (result) {
7227
- return { value: true };
7228
- }
7229
- else if (index === conditionalFees.length - 1) {
7230
- return { value: false };
7231
- }
7232
- }
7233
- };
7234
- for (var index = 0; index < conditionalFees.length; index++) {
7235
- var state_1 = _loop_1(index);
7236
- if (typeof state_1 === "object")
7237
- return state_1.value;
7238
- }
7239
- }
7240
- if (i.minKm !== null && i.minKm !== undefined) {
7241
- if (cte === null || cte === void 0 ? void 0 : cte.distance) {
7242
- var distanceInRange = +cte.distance >= +i.minKm && (!i.maxKm || +cte.distance <= +i.maxKm);
7243
- var vehicleTypeMatches = !i.vehicleTypeId || cte.vehicleTypeId === i.vehicleTypeId;
7244
- if (distanceInRange && vehicleTypeMatches) {
7245
- return true;
7246
- }
7247
- }
7248
- }
7249
- else if (i.minWeight) {
7250
- if (cte === null || cte === void 0 ? void 0 : cte.taxedWeight) {
7251
- if (Math.ceil(+cte.taxedWeight) >= +i.minWeight) {
7252
- if (Math.ceil(+cte.taxedWeight) <= +i.maxWeight) {
7253
- return true;
7254
- }
7255
- else if (!i.maxWeight) {
7256
- return true;
7257
- }
7404
+ return false;
7405
+ });
7258
7406
  }
7259
7407
  }
7260
7408
  }
7261
- else {
7262
- return true;
7263
- }
7264
- return false;
7265
- });
7266
- // Remover fees duplicadas, mantendo apenas uma ocorrência de cada feeId
7267
- var seenFeeIds = new Set();
7268
- var uniqueFees = filteredFees === null || filteredFees === void 0 ? void 0 : filteredFees.filter(function (fee) {
7269
- if (fee.feeId && seenFeeIds.has(fee.feeId)) {
7270
- return false;
7271
- }
7272
- if (fee.feeId) {
7273
- seenFeeIds.add(fee.feeId);
7274
- }
7275
- return true;
7276
- });
7277
- return uniqueFees;
7409
+ }
7278
7410
  };
7279
7411
 
7280
- var getLaneFromRatecard = function (cte) {
7281
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
7412
+ var getLaneFeesToCalc = function (cte) {
7413
+ var _a, _b;
7282
7414
  var ratecard = getRatecardFromCte(cte);
7283
- var cityOriginId = cte.cityOriginId, cityDestination = cte.cityDestination;
7284
- var destinationUf = (_a = cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.state) === null || _a === void 0 ? void 0 : _a.uf;
7285
- // Encontrar a ratecardRegion da cidade de destino
7286
- var destinationRatecardRegionId = (_c = (_b = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardRegionCity) === null || _b === void 0 ? void 0 : _b.find(function (regionCity) { return regionCity.cityId === (cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.id); })) === null || _c === void 0 ? void 0 : _c.ratecardRegionId;
7287
- if (!(ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardLane) || ((_d = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardLane) === null || _d === void 0 ? void 0 : _d.length) === 0) {
7288
- return undefined;
7289
- }
7290
- // Lógica diferenciada por modal
7291
- switch (ratecard.modalId) {
7292
- case exports.RatecardModalEnum.ROAD_DOMESTIC_FTL:
7293
- // FTL: Verificar rota por UF de destino
7294
- if (destinationUf) {
7295
- var directLane = ratecard.RatecardLane.find(function (i) {
7296
- return i.ufDestination === destinationUf && i.ratecardRegionId === destinationRatecardRegionId;
7297
- });
7298
- if (directLane) {
7299
- return directLane;
7300
- }
7301
- // Fallback: Verificar se existe lane única com fees de KM e cidade origem no ratecard_origin_cities
7302
- var uniqueLane = ratecard.RatecardLane[0];
7303
- // Verificar se a lane tem fees com intervalo de KM
7304
- var hasKmFees = (_e = uniqueLane === null || uniqueLane === void 0 ? void 0 : uniqueLane.RatecardLaneFee) === null || _e === void 0 ? void 0 : _e.some(function (fee) { return fee.minKm !== null; });
7305
- // Verificar se a cidade de origem está no ratecard_origin_cities
7306
- var hasOriginCity = (_f = ratecard.ratecard_origin_cities) === null || _f === void 0 ? void 0 : _f.some(function (originCity) { return originCity.cityId === cityOriginId; });
7307
- if (hasKmFees && hasOriginCity) {
7308
- // Mockar informações para exibição no frontend
7309
- return __assign(__assign({}, uniqueLane), { city: cte.cityOrigin, ufDestination: destinationUf, ratecardRegion: uniqueLane.ratecardRegion || { name: destinationUf } });
7310
- }
7311
- // Rota inversa FTL: Verificar se cidade de destino está em ratecard_origin_cities
7312
- var originUf_1 = (_h = (_g = cte.cityOrigin) === null || _g === void 0 ? void 0 : _g.state) === null || _h === void 0 ? void 0 : _h.uf;
7313
- if (originUf_1) {
7314
- // Verificar se existe lane com ufDestination = originUf
7315
- var reverseLane = ratecard.RatecardLane.find(function (i) {
7316
- return i.ufDestination === originUf_1;
7317
- });
7318
- if (reverseLane) {
7319
- // Verificar se a cidade de destino está no ratecard_origin_cities
7320
- var hasDestinationCity = (_j = ratecard.ratecard_origin_cities) === null || _j === void 0 ? void 0 : _j.some(function (originCity) { return originCity.cityId === (cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.id); });
7321
- if (hasDestinationCity) {
7322
- return reverseLane;
7415
+ var lane = getCteLane(cte);
7416
+ if ((_a = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _a === void 0 ? void 0 : _a.length) {
7417
+ var newFilteredFees = (_b = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _b === void 0 ? void 0 : _b.filter(function (i) {
7418
+ var _a, _b, _c, _d, _e;
7419
+ var defaultConditionalFees = [
7420
+ exports.FeeEnum.TDA_FREIGHT,
7421
+ exports.FeeEnum.TDA_MIN,
7422
+ exports.FeeEnum.TDE_FREIGHT,
7423
+ exports.FeeEnum.TDE_MIN,
7424
+ ];
7425
+ var conditionalFeeToVerify;
7426
+ var conditionalFees = (_a = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardConditionalFee) === null || _a === void 0 ? void 0 : _a.filter(function (it) { var _a; return it.feeId === ((_a = i.fee) === null || _a === void 0 ? void 0 : _a.id); });
7427
+ if (defaultConditionalFees.includes((_b = i.fee) === null || _b === void 0 ? void 0 : _b.id) && !(conditionalFees === null || conditionalFees === void 0 ? void 0 : conditionalFees.length)) {
7428
+ return false;
7429
+ }
7430
+ if (conditionalFees && (conditionalFees === null || conditionalFees === void 0 ? void 0 : conditionalFees.length) > 0) {
7431
+ var _loop_1 = function (index) {
7432
+ var conditionalFee = conditionalFees[index];
7433
+ if (conditionalFee) {
7434
+ conditionalFeeToVerify = conditionalFee;
7435
+ }
7436
+ else if ((_c = i.fee) === null || _c === void 0 ? void 0 : _c.parentId) {
7437
+ var siblingFee_1 = (_d = lane === null || lane === void 0 ? void 0 : lane.RatecardLaneFee) === null || _d === void 0 ? void 0 : _d.find(function (it) { var _a, _b; return ((_a = it.fee) === null || _a === void 0 ? void 0 : _a.parentId) === i.fee.parentId && ((_b = it.fee) === null || _b === void 0 ? void 0 : _b.id) !== i.fee.id; });
7438
+ if (siblingFee_1) {
7439
+ var conditionalFeeSibling = (_e = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardConditionalFee) === null || _e === void 0 ? void 0 : _e.find(function (i) { var _a; return i.feeId === ((_a = siblingFee_1.fee) === null || _a === void 0 ? void 0 : _a.id); });
7440
+ if (conditionalFeeSibling) {
7441
+ conditionalFeeToVerify = conditionalFeeSibling;
7442
+ }
7323
7443
  }
7324
7444
  }
7325
- // Fallback inverso: Lane única com cidade de destino em ratecard_origin_cities
7326
- var hasDestinationCityInOrigins = (_k = ratecard.ratecard_origin_cities) === null || _k === void 0 ? void 0 : _k.some(function (originCity) { return originCity.cityId === (cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.id); });
7327
- if (hasKmFees && hasDestinationCityInOrigins) {
7328
- // Mockar informações para exibição no frontend (rota inversa)
7329
- return __assign(__assign({}, uniqueLane), { city: cityDestination, ufDestination: originUf_1, ratecardRegion: uniqueLane.ratecardRegion || { name: originUf_1 } });
7445
+ if (conditionalFeeToVerify === null || conditionalFeeToVerify === void 0 ? void 0 : conditionalFeeToVerify.id) {
7446
+ var result = verifyConditionalFee(conditionalFeeToVerify, cte);
7447
+ if (result) {
7448
+ return { value: true };
7449
+ }
7450
+ else if (index === conditionalFees.length - 1) {
7451
+ return { value: false };
7452
+ }
7330
7453
  }
7454
+ };
7455
+ for (var index = 0; index < conditionalFees.length; index++) {
7456
+ var state_1 = _loop_1(index);
7457
+ if (typeof state_1 === "object")
7458
+ return state_1.value;
7331
7459
  }
7332
7460
  }
7333
- break;
7334
- case exports.RatecardModalEnum.ROAD_DOMESTIC_LTL:
7335
- default:
7336
- // LTL: Lógica original (rota direta + inversa)
7337
- if (cityOriginId && destinationUf) {
7338
- // Primeiro, buscar rota direta (Origem -> Destino)
7339
- var directLane = ratecard.RatecardLane.find(function (i) {
7340
- return i.cityOriginId === cityOriginId && i.ufDestination === destinationUf && i.ratecardRegionId === destinationRatecardRegionId;
7341
- });
7342
- if (directLane) {
7343
- return directLane;
7344
- }
7345
- // Se não encontrar rota direta, buscar rota inversa (Destino -> Origem)
7346
- // Para isso, precisamos encontrar a UF da origem e sua ratecardRegion
7347
- var originUf_2 = (_m = (_l = cte.cityOrigin) === null || _l === void 0 ? void 0 : _l.state) === null || _m === void 0 ? void 0 : _m.uf;
7348
- // Encontrar a ratecardRegion da cidade de origem
7349
- var originRatecardRegionId_1 = (_p = (_o = ratecard === null || ratecard === void 0 ? void 0 : ratecard.RatecardRegionCity) === null || _o === void 0 ? void 0 : _o.find(function (regionCity) { return regionCity.cityId === cityOriginId; })) === null || _p === void 0 ? void 0 : _p.ratecardRegionId;
7350
- if (originUf_2) {
7351
- var reverseLane = ratecard.RatecardLane.find(function (i) {
7352
- return i.cityOriginId === (cityDestination === null || cityDestination === void 0 ? void 0 : cityDestination.id) && i.ufDestination === originUf_2 && i.ratecardRegionId === originRatecardRegionId_1;
7353
- });
7354
- if (reverseLane) {
7355
- return reverseLane;
7461
+ if (i.minWeight) {
7462
+ if (cte === null || cte === void 0 ? void 0 : cte.taxedWeight) {
7463
+ if (Math.ceil(+cte.taxedWeight) >= +i.minWeight) {
7464
+ if (Math.ceil(+cte.taxedWeight) <= +i.maxWeight) {
7465
+ return true;
7466
+ }
7467
+ else if (!i.maxWeight) {
7468
+ return true;
7469
+ }
7356
7470
  }
7357
7471
  }
7358
7472
  }
7359
- break;
7473
+ else {
7474
+ return true;
7475
+ }
7476
+ return false;
7477
+ });
7478
+ if ((newFilteredFees === null || newFilteredFees === void 0 ? void 0 : newFilteredFees.length) > 0) {
7479
+ return newFilteredFees;
7480
+ }
7360
7481
  }
7361
- return undefined;
7362
7482
  };
7363
7483
 
7364
7484
  var getNormalizedCityName = function (name) {
@@ -7558,9 +7678,11 @@ var setFormattedDatesInObjects = function (objectFormat) { return __awaiter(void
7558
7678
 
7559
7679
  exports.applyRedeliveryMultiplier = applyRedeliveryMultiplier;
7560
7680
  exports.calculateFee = calculateFee;
7681
+ exports.calculateIcms = calculateIcms;
7561
7682
  exports.convertNumberToCurrency = convertNumberToCurrency;
7562
7683
  exports.filterSiblingFees = filterSiblingFees;
7563
7684
  exports.formatDateString = formatDateString;
7685
+ exports.getAllFeesForCalculation = getAllFeesForCalculation;
7564
7686
  exports.getAuditTotalFromCte = getAuditTotalFromCte;
7565
7687
  exports.getConfigurationFromDomain = getConfigurationFromDomain;
7566
7688
  exports.getContractFromFreight = getContractFromFreight;