@heuristical/trackit
Version:
This module allows you to connect to many shipping carriers like UPS and FedEx and download tracking data for your packages in a common schema
230 lines • 9.91 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DhlClient = void 0;
/* eslint-disable
constructor-super,
no-constant-condition,
no-eval,
no-this-before-super,
no-unused-vars,
standard/no-callback-literal,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS001: Remove Babel/TypeScript constructor workaround
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const xml2js_1 = require("xml2js");
const moment_timezone_1 = __importDefault(require("moment-timezone"));
const shipper_1 = require("./shipper");
function __guard__(value, transform) {
return (typeof value !== 'undefined' && value !== null) ? transform(value) : undefined;
}
class DhlClient extends shipper_1.ShipperClient {
constructor(options) {
super();
this.STATUS_MAP = new Map([
['AD', shipper_1.STATUS_TYPES.EN_ROUTE],
['AF', shipper_1.STATUS_TYPES.EN_ROUTE],
['AR', shipper_1.STATUS_TYPES.EN_ROUTE],
['BA', shipper_1.STATUS_TYPES.DELAYED],
['BN', shipper_1.STATUS_TYPES.EN_ROUTE],
['BR', shipper_1.STATUS_TYPES.EN_ROUTE],
['CA', shipper_1.STATUS_TYPES.DELAYED],
['CC', shipper_1.STATUS_TYPES.OUT_FOR_DELIVERY],
['CD', shipper_1.STATUS_TYPES.DELAYED],
['CM', shipper_1.STATUS_TYPES.DELAYED],
['CR', shipper_1.STATUS_TYPES.EN_ROUTE],
['CS', shipper_1.STATUS_TYPES.DELAYED],
['DD', shipper_1.STATUS_TYPES.DELIVERED],
['DF', shipper_1.STATUS_TYPES.EN_ROUTE],
['DS', shipper_1.STATUS_TYPES.DELAYED],
['FD', shipper_1.STATUS_TYPES.EN_ROUTE],
['HP', shipper_1.STATUS_TYPES.DELAYED],
['IC', shipper_1.STATUS_TYPES.EN_ROUTE],
['MC', shipper_1.STATUS_TYPES.DELAYED],
['MD', shipper_1.STATUS_TYPES.EN_ROUTE],
['MS', shipper_1.STATUS_TYPES.DELAYED],
['ND', shipper_1.STATUS_TYPES.DELAYED],
['NH', shipper_1.STATUS_TYPES.DELAYED],
['OH', shipper_1.STATUS_TYPES.DELAYED],
['OK', shipper_1.STATUS_TYPES.DELIVERED],
['PD', shipper_1.STATUS_TYPES.EN_ROUTE],
['PL', shipper_1.STATUS_TYPES.EN_ROUTE],
['PO', shipper_1.STATUS_TYPES.EN_ROUTE],
['PU', shipper_1.STATUS_TYPES.EN_ROUTE],
['RD', shipper_1.STATUS_TYPES.DELAYED],
['RR', shipper_1.STATUS_TYPES.DELAYED],
['RT', shipper_1.STATUS_TYPES.DELAYED],
['SA', shipper_1.STATUS_TYPES.SHIPPING],
['SC', shipper_1.STATUS_TYPES.DELAYED],
['SS', shipper_1.STATUS_TYPES.DELAYED],
['TD', shipper_1.STATUS_TYPES.DELAYED],
['TP', shipper_1.STATUS_TYPES.OUT_FOR_DELIVERY],
['TR', shipper_1.STATUS_TYPES.EN_ROUTE],
['UD', shipper_1.STATUS_TYPES.DELAYED],
['WC', shipper_1.STATUS_TYPES.OUT_FOR_DELIVERY],
['WX', shipper_1.STATUS_TYPES.DELAYED],
]);
this.options = options;
this.parser = new xml2js_1.Parser();
}
get userId() { return this.options.userId; }
;
get password() { return this.options.password; }
;
generateRequest(trk) {
return `\
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<req:KnownTrackingRequest xmlns:req="http://www.dhl.com">
<Request>
<ServiceHeader>
<SiteID>${this.userId}</SiteID>
<Password>${this.password}</Password>
</ServiceHeader>
</Request>
<LanguageCode>en</LanguageCode>
<AWBNumber>${trk}</AWBNumber>
<LevelOfDetails>ALL_CHECK_POINTS</LevelOfDetails>
</req:KnownTrackingRequest>\
`;
}
validateResponse(response, cb) {
function handleResponse(xmlErr, trackResult) {
if ((xmlErr != null) || (trackResult == null)) {
return cb(xmlErr);
}
const trackingResponse = trackResult['req:TrackingResponse'];
if (trackingResponse == null) {
return cb({ error: 'no tracking response' });
}
const awbInfo = trackingResponse.AWBInfo != null ? trackingResponse.AWBInfo[0] : undefined;
if (awbInfo == null) {
return cb({ error: 'no AWBInfo in response' });
}
const shipment = awbInfo.ShipmentInfo != null ? awbInfo.ShipmentInfo[0] : undefined;
if (shipment == null) {
return cb({ error: 'could not find shipment' });
}
const trackStatus = awbInfo.Status != null ? awbInfo.Status[0] : undefined;
const statusCode = trackStatus != null ? trackStatus.ActionStatus : undefined;
if (statusCode.toString() !== 'success') {
return cb({ error: `unexpected track status code=${statusCode}` });
}
return cb(null, shipment);
}
this.parser.reset();
return this.parser.parseString(response, handleResponse);
}
getEta(shipment) {
const eta = shipment.EstDlvyDate != null ? shipment.EstDlvyDate[0] : undefined;
const formatSpec = 'YYYYMMDD HHmmss ZZ';
if (eta != null) {
return moment_timezone_1.default(eta, formatSpec).toDate();
}
}
getService(shipment) { }
getWeight(shipment) {
const weight = shipment.Weight != null ? shipment.Weight[0] : undefined;
if (weight != null) {
return `${weight} LB`;
}
}
presentTimestamp(dateString, timeString) {
if (dateString == null) {
return;
}
if (timeString == null) {
timeString = '00:00';
}
const inputString = `${dateString} ${timeString} +0000`;
const formatSpec = 'YYYYMMDD HHmmss ZZ';
return moment_timezone_1.default(inputString, formatSpec).toDate();
}
presentAddress(rawAddress) {
let city, countryCode, stateCode;
if (rawAddress == null) {
return;
}
const firstComma = rawAddress.indexOf(',');
const firstDash = rawAddress.indexOf('-', firstComma);
if ((firstComma > -1) && (firstDash > -1)) {
city = rawAddress.substring(0, firstComma).trim();
stateCode = rawAddress.substring(firstComma + 1, firstDash).trim();
countryCode = rawAddress.substring(firstDash + 1).trim();
}
else if ((firstComma < 0) && (firstDash > -1)) {
city = rawAddress.substring(0, firstDash).trim();
stateCode = null;
countryCode = rawAddress.substring(firstDash + 1).trim();
}
else {
return rawAddress;
}
city = city.replace(' HUB', '');
city = city.replace(' GATEWAY', '');
return this.presentLocation({ city, stateCode, countryCode, postalCode: null });
}
presentDetails(rawAddress, rawDetails) {
if (rawDetails == null) {
return;
}
if (rawAddress == null) {
return rawDetails;
}
return rawDetails.replace(/\s\s+/, ' ').trim().replace(new RegExp(`(?: at| in)? ${rawAddress.trim()}$`), '');
}
presentStatus(status) {
return this.STATUS_MAP.get(status) || shipper_1.STATUS_TYPES.UNKNOWN;
}
getActivitiesAndStatus(shipment) {
const activities = [];
let status = null;
let rawActivities = shipment.ShipmentEvent;
if (rawActivities == null) {
rawActivities = [];
}
rawActivities.reverse();
for (const rawActivity of Array.from(rawActivities || [])) {
const rawLocation = __guard__(__guard__(rawActivity.ServiceArea != null ? rawActivity.ServiceArea[0] : undefined, x1 => x1.Description), x => x[0]);
const location = this.presentAddress(rawLocation);
const timestamp = this.presentTimestamp(rawActivity.Date != null ? rawActivity.Date[0] : undefined, rawActivity.Time != null ? rawActivity.Time[0] : undefined);
let details = this.presentDetails(rawLocation, __guard__(__guard__(rawActivity.ServiceEvent != null ? rawActivity.ServiceEvent[0] : undefined, x3 => x3.Description), x2 => x2[0]));
if ((details != null) && (timestamp != null)) {
details = details.slice(-1) === '.' ? details.slice(0, +-2 + 1 || undefined) : details;
const activity = { timestamp, location, details };
activities.push(activity);
}
if (!status) {
status = this.presentStatus(__guard__(__guard__(rawActivity.ServiceEvent != null ? rawActivity.ServiceEvent[0] : undefined, x5 => x5.EventCode), x4 => x4[0]));
}
}
return { activities, status };
}
getDestination(shipment) {
const destination = __guard__(__guard__(shipment.DestinationServiceArea != null ? shipment.DestinationServiceArea[0] : undefined, x1 => x1.Description), x => x[0]);
if (destination == null) {
return;
}
return this.presentAddress(destination);
}
requestOptions({ trackingNumber }) {
return {
method: 'POST',
uri: 'http://xmlpi-ea.dhl.com/XMLShippingServlet',
body: this.generateRequest(trackingNumber)
};
}
}
exports.DhlClient = DhlClient;
//# sourceMappingURL=dhl.js.map