vtlab-rates-utils
v1.0.1
Published
A utility library for calculating shipping rates based on various factors.
Readme
Pelikane VTLAB Rates Utils
A utility library for calculating shipping rates based on various factors.
Installation
npm install pelikane-vtlab-rates-utilsUsage
const ratesCalculator = require('pelikane-vtlab-rates-utils');
// Example usage of a function
// const applicableRates = ratesCalculator.filterApplicableRates(expedition, ratesList);API
The following functions are available:
matchDeliveryZoneAndItem(expedition, zone)filterApplicableRates(expedition, ratesList)selectBestRateAndZone(expedition, zonesList, ratesList)computeWeightValues(expedition, rateConfig)lookupBasePrice(usedWeight, deliveryZoneItemId, rateConfig, isReturn)computeExtras(rateConfig, baseAmount)buildEstimation(expedition, rateConfig, deliveryZone, deliveryZoneItem)
For more details on the parameters for each function, please refer to the JSDoc comments in ratesCalculator.js.
Core Concepts
The estimation process is broken down into two main steps, exposed by two high-level functions:
selectBestRateAndZone: Finds the correct delivery zone and rate configuration for a given shipment (which we call an "Expedition").buildEstimation: Takes the results from the first step and calculates the final price, including weight calculations and extra fees.
Usage Workflow
To get a rate estimation, you should follow these steps in order:
1. Prepare Your Data
Before calling the calculator, you need to have three pieces of information ready, typically loaded from your own database or API:
ExpeditionObject: A plain JavaScript object that describes the shipment you want to estimate. It contains origin/destination info, weight, service type, etc.zonesListArray: An array of all possible "Delivery Zone" documents that could apply to the expedition.ratesListArray: An array of all possible "Rate" documents that could apply.
Note: For the exact data structure required for each of these objects, please refer to the JSDoc type definitions at the top of the ratesCalculator.js file.
2. Create the Expedition Object
Build the Expedition object by mapping data from your application's models (e.g., Orders, Shipments).
Example Expedition:
const expedition = {
ownerAccountId: "owner_account_id_123",
carrierAccountId: "carrier_account_id_456",
// Origin Info
originCenterId: "center_id_789",
originPostalCode: "28001",
originRegion: "Madrid",
originCountry: "Spain",
// Destination Info
destinationPostalCode: "08001",
destinationRegion: "Barcelona",
destinationCountry: "Spain",
destinationCountryExtraNames: ["España"],
// Service Info
carrierServiceReference: "UPS-Standard",
carrierServiceName: "Standard",
// Weight/Volume
weight: 15.5, // in kg
volume: 0.1, // in cubic meters
// Shipment Date
shipmentDate: new Date("2023-10-27T10:00:00Z"),
// Flag for returns
isReturn: false
};3. Select the Best Rate and Zone
Pass your prepared data to the selectBestRateAndZone function. It will find the best-matching delivery zone and the most applicable rate configuration.
const { selectBestRateAndZone } = require("./ratesCalculator");
// Assume zonesList and ratesList are loaded from your DB
const allZones = [/* ... your delivery zone documents ... */];
const allRates = [/* ... your rate documents ... */];
try {
const { rateConfig, deliveryZone, deliveryZoneItem } = selectBestRateAndZone(expedition, allZones, allRates);
// Now, proceed to the next step with this data...
} catch (e) {
console.error(`Could not find a valid rate: ${e.message}`);
// e.g., "pelikane.rates.invoicesAnalysis.error.deliveryZoneNotFound"
}This function returns an object containing the three key pieces of configuration needed for the final calculation.
4. Build the Final Estimation
Finally, pass the expedition object and the results from the previous step to the buildEstimation function.
const { buildEstimation } = require("./ratesCalculator");
// ... continuing from the previous step
// const { rateConfig, deliveryZone, deliveryZoneItem } = ...
try {
const finalEstimate = buildEstimation(expedition, rateConfig, deliveryZone, deliveryZoneItem);
console.log("Rate Estimation Successful:");
console.log(finalEstimate);
} catch (e) {
console.error(`Error during estimation: ${e.key || e.message}`);
}The Result
The finalEstimate object will look something like this:
{
date: "2023-10-27T12:00:00.000Z",
rateId: "rate_id_abc",
zoneId: "zone_id_def",
weightBaseUsed: "maxBetweenVolumetricAndReal",
weightUnit: "kg",
weightValue: 25, // The final weight used for calculation
coin: "EUR",
extras: [/* ...special services config... */],
carrierServiceName: "Standard",
calculatedAmount: "8.50",
totalExtras: "2.00",
totalRate: "10.50",
description: "Tarifa: Standard Rate\nPeso utilizado: Máximo entre Volumetrico y Real\nValor: 25\n..."
}Error Handling
The functions in this module throw errors when a valid estimation cannot be made. These errors are typically objects containing a key property that you can use for programmatic error handling or translation. Always wrap calls to these functions in a try...catch block.
