feat(v2.6.0): implement GlobalEnvelope, T1-T9 hardening, 12 tools, and CI acceptance test suite
This commit is contained in:
@@ -4,16 +4,16 @@ import { PathaoAdapter } from "./pathao.js";
|
||||
|
||||
export class FraudRiskEngine {
|
||||
/**
|
||||
* 100% Real Live Multi-Carrier Fraud & Delivery Risk Evaluation
|
||||
* Queries Pathao Nationwide Customer Delivery Database (/aladdin/api/v1/user/success)
|
||||
* and Steadfast Nationwide Logistics Database (/fraud_check/{phone})
|
||||
* Real-Time Multi-Carrier Fraud & Delivery Risk Evaluation (T6)
|
||||
* Queries Pathao Nationwide Customer Delivery Database (/aladdin/api/v1/user/success),
|
||||
* Steadfast Nationwide Logistics Database (/fraud_check/{phone}), and BD Operator Prefix Validator.
|
||||
*/
|
||||
public static async evaluateRisk(
|
||||
phoneNumber: string,
|
||||
steadfastAdapter?: SteadfastAdapter,
|
||||
pathaoAdapter?: PathaoAdapter
|
||||
): Promise<FraudRiskScoreResponse> {
|
||||
const rawDigits = phoneNumber.replace(/[^0-9]/g, "");
|
||||
const rawDigits = String(phoneNumber || "").replace(/[^0-9]/g, "");
|
||||
const cleanPhone = rawDigits.startsWith("880") && rawDigits.length === 13 ? rawDigits.slice(2) : rawDigits;
|
||||
|
||||
// Valid BD Mobile format check (11 digits starting with 013, 014, 015, 016, 017, 018, 019)
|
||||
@@ -22,17 +22,20 @@ export class FraudRiskEngine {
|
||||
if (!isValidBDOperator) {
|
||||
return {
|
||||
phone: phoneNumber,
|
||||
risk_level: "CRITICAL",
|
||||
delivery_success_rate: "0% (অবৈধ নম্বর / Invalid BD Number)",
|
||||
risk_level: "INVALID_NUMBER",
|
||||
delivery_success_rate: null,
|
||||
total_parcels: 0,
|
||||
total_delivered: 0,
|
||||
total_cancelled: 0,
|
||||
cancellation_rate: "100%",
|
||||
cancellation_rate: null,
|
||||
is_verified_buyer: false,
|
||||
recommendation:
|
||||
"🇧🇩 ভুল বা অকার্যকর বাংলাদেশি মোবাইল নম্বর। ম্যানুয়াল ভেরিফিকেশন ছাড়া পার্সেল বুক করবেন না। | 🇬🇧 Invalid Bangladesh mobile number (11 digits starting with 013–019 required). Do not dispatch without manual verification.",
|
||||
carrier_source: "operator_prefix_validator",
|
||||
carrier_source: "prefix_validator",
|
||||
carrier_verified: false,
|
||||
data_sources: ["prefix_validator"],
|
||||
sample_size: 0,
|
||||
coverage_note: "Validated against BTRC 11-digit mobile operator prefix rules (013–019).",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -40,10 +43,28 @@ export class FraudRiskEngine {
|
||||
let delivered = 0;
|
||||
let cancelled = 0;
|
||||
let verifiedByCarrier = false;
|
||||
const sources: string[] = [];
|
||||
const dataSources: string[] = [];
|
||||
let customerRating: string | undefined;
|
||||
|
||||
// 1. Query Pathao Nationwide Customer Delivery Database (POST /aladdin/api/v1/user/success)
|
||||
// 1. Query Steadfast Nationwide Fraud Database (GET /fraud_check/{phone})
|
||||
if (steadfastAdapter && steadfastAdapter.isConfigured()) {
|
||||
try {
|
||||
const sfData = await steadfastAdapter.fraudCheck(cleanPhone);
|
||||
const sfTotal = Number(sfData?.total_parcels ?? sfData?.data?.total_parcels ?? 0);
|
||||
const sfDelivered = Number(sfData?.total_delivered ?? sfData?.data?.total_delivered ?? 0);
|
||||
const sfCancelled = Number(sfData?.total_cancelled ?? sfData?.data?.total_cancelled ?? 0);
|
||||
|
||||
total += sfTotal;
|
||||
delivered += sfDelivered;
|
||||
cancelled += sfCancelled;
|
||||
verifiedByCarrier = true;
|
||||
dataSources.push("steadfast_nationwide");
|
||||
} catch (_) {
|
||||
// Continue to Pathao check
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Query Pathao Nationwide Customer Delivery Database (POST /aladdin/api/v1/user/success)
|
||||
if (pathaoAdapter && pathaoAdapter.isConfigured()) {
|
||||
try {
|
||||
const ptRes = await pathaoAdapter.fraudCheck(cleanPhone);
|
||||
@@ -57,50 +78,36 @@ export class FraudRiskEngine {
|
||||
delivered += ptDelivered;
|
||||
cancelled += ptCancelled;
|
||||
verifiedByCarrier = true;
|
||||
sources.push("pathao_nationwide_v2_api");
|
||||
dataSources.push("pathao_nationwide");
|
||||
if (ptData.customer_rating) {
|
||||
customerRating = String(ptData.customer_rating);
|
||||
}
|
||||
} catch (_) {
|
||||
// Continue to Steadfast check
|
||||
// Carrier lookup error handled gracefully
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Query Steadfast Nationwide Fraud Database (GET /fraud_check/{phone})
|
||||
if (steadfastAdapter && steadfastAdapter.isConfigured()) {
|
||||
try {
|
||||
const sfData = await steadfastAdapter.fraudCheck(cleanPhone);
|
||||
const sfTotal = Number(sfData?.total_parcels ?? sfData?.data?.total_parcels ?? 0);
|
||||
const sfDelivered = Number(sfData?.total_delivered ?? sfData?.data?.total_delivered ?? 0);
|
||||
const sfCancelled = Number(sfData?.total_cancelled ?? sfData?.data?.total_cancelled ?? 0);
|
||||
|
||||
total += sfTotal;
|
||||
delivered += sfDelivered;
|
||||
cancelled += sfCancelled;
|
||||
verifiedByCarrier = true;
|
||||
sources.push("steadfast_nationwide_api");
|
||||
} catch (_) {
|
||||
// Steadfast fraud endpoint may be restricted on some merchant keys; Pathao v2 covers nationwide
|
||||
}
|
||||
}
|
||||
dataSources.push("prefix_validator");
|
||||
const sourceLabel = dataSources.join("+");
|
||||
|
||||
if (verifiedByCarrier) {
|
||||
const sourceLabel = sources.join(" + ");
|
||||
|
||||
if (total === 0) {
|
||||
return {
|
||||
phone: cleanPhone,
|
||||
risk_level: "NEW_BUYER",
|
||||
delivery_success_rate: "N/A (নতুন ক্রেতা / New Buyer)",
|
||||
risk_level: "NO_HISTORY",
|
||||
delivery_success_rate: null,
|
||||
total_parcels: 0,
|
||||
total_delivered: 0,
|
||||
total_cancelled: 0,
|
||||
cancellation_rate: "0%",
|
||||
cancellation_rate: null,
|
||||
is_verified_buyer: true,
|
||||
recommendation:
|
||||
"🇧🇩 সারা দেশের কুরিয়ার ডেটাবেজে কোনো রিটার্ন রেকর্ড নেই (নতুন ক্রেতা)। ফোনে ঠিকানা কনফার্ম করে ক্যাশ অন ডেলিভারিতে পাঠানো যেতে পারে। | 🇬🇧 No prior return record in nationwide courier database (New Buyer). Safe to ship via COD after phone confirmation.",
|
||||
"🇧🇩 কুরিয়ার ডেটাবেজে পূর্বে কোনো অর্ডার বা রিটার্ন রেকর্ড নেই (নতুন ক্রেতা)। ফোনে ঠিকানা কনফার্ম করে পাঠানো যেতে পারে। | 🇬🇧 No prior delivery or return history found in queried courier databases. Confirm via phone call before COD dispatch.",
|
||||
carrier_source: sourceLabel,
|
||||
carrier_verified: true,
|
||||
data_sources: dataSources,
|
||||
sample_size: 0,
|
||||
coverage_note: `Queried ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")} live databases; 0 prior consignments recorded.`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -110,65 +117,58 @@ export class FraudRiskEngine {
|
||||
const cancelRateStr = `${cancelRatio.toFixed(1)}%`;
|
||||
const ratingNote = customerRating ? ` [Carrier Rating: ${customerRating}]` : "";
|
||||
|
||||
let riskLevel: "LOW" | "MEDIUM" | "HIGH" | "CRITICAL" = "LOW";
|
||||
let rec = "";
|
||||
|
||||
if (successRatio >= 80) {
|
||||
return {
|
||||
phone: cleanPhone,
|
||||
risk_level: "LOW",
|
||||
delivery_success_rate: successRateStr,
|
||||
total_parcels: total,
|
||||
total_delivered: delivered,
|
||||
total_cancelled: cancelled,
|
||||
cancellation_rate: cancelRateStr,
|
||||
is_verified_buyer: true,
|
||||
recommendation: `🇧🇩 কাস্টমার অত্যন্ত নির্ভরযোগ্য (সফল ডেলিভারি: ${delivered}/${total}টি, সাকসেস রেট: ${successRateStr})। ১০০% নির্দ্বিধায় ক্যাশ অন ডেলিভারি (COD) পাঠান। | 🇬🇧 Highly reliable buyer (${delivered}/${total} delivered, ${successRateStr} success rate)${ratingNote}. Safe for immediate COD dispatch.`,
|
||||
carrier_source: sourceLabel,
|
||||
carrier_verified: true,
|
||||
};
|
||||
riskLevel = "LOW";
|
||||
rec = `🇧🇩 কাস্টমার অত্যন্ত নির্ভরযোগ্য (সফল ডেলিভারি: ${delivered}/${total}টি, সাকসেস রেট: ${successRateStr})। নির্দ্বিধায় ক্যাশ অন ডেলিভারি (COD) পাঠান। | 🇬🇧 Highly reliable buyer (${delivered}/${total} delivered, ${successRateStr} success rate)${ratingNote}. Safe for immediate COD dispatch.`;
|
||||
} else if (successRatio >= 55) {
|
||||
return {
|
||||
phone: cleanPhone,
|
||||
risk_level: "MODERATE",
|
||||
delivery_success_rate: successRateStr,
|
||||
total_parcels: total,
|
||||
total_delivered: delivered,
|
||||
total_cancelled: cancelled,
|
||||
cancellation_rate: cancelRateStr,
|
||||
is_verified_buyer: true,
|
||||
recommendation: `🇧🇩 মাঝারি ঝুঁকি (সফল: ${delivered}টি, ক্যানসেল/রিটার্ন: ${cancelled}টি, ক্যানসেলেশন রেট: ${cancelRateStr})। পার্সেল পাঠানোর আগে কাস্টমারকে ফোন দিয়ে অর্ডার কনফার্ম করুন। | 🇬🇧 Moderate risk (${delivered} delivered, ${cancelled} returned, ${cancelRateStr} return rate)${ratingNote}. Confirm order via phone call before dispatch.`,
|
||||
carrier_source: sourceLabel,
|
||||
carrier_verified: true,
|
||||
};
|
||||
riskLevel = "MEDIUM";
|
||||
rec = `🇧🇩 মাঝারি ঝুঁকি (সফল: ${delivered}টি, ক্যানসেল/রিটার্ন: ${cancelled}টি, ক্যানসেলেশন রেট: ${cancelRateStr})। পার্সেল পাঠানোর আগে কাস্টমারকে ফোন দিয়ে অর্ডার কনফার্ম করুন। | 🇬🇧 Medium risk (${delivered} delivered, ${cancelled} returned, ${cancelRateStr} return rate)${ratingNote}. Confirm order via phone call before dispatch.`;
|
||||
} else if (successRatio >= 25) {
|
||||
riskLevel = "HIGH";
|
||||
rec = `🇧🇩 উচ্চ ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} ক্যানসেল/রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। ডেলিভারি চার্জ অগ্রিম নেওয়ার সুপারিশ করা হচ্ছে। | 🇬🇧 High fraud risk! Buyer cancelled/returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Collect advance delivery charge before shipping.`;
|
||||
} else {
|
||||
return {
|
||||
phone: cleanPhone,
|
||||
risk_level: "HIGH",
|
||||
delivery_success_rate: successRateStr,
|
||||
total_parcels: total,
|
||||
total_delivered: delivered,
|
||||
total_cancelled: cancelled,
|
||||
cancellation_rate: cancelRateStr,
|
||||
is_verified_buyer: false,
|
||||
recommendation: `🇧🇩 উচ্চ ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} ক্যানসেল/রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। পার্সেল পাঠানোর আগে ডেলিভারি চার্জ (১৫০৳) অগ্রিম নেওয়ার সুপারিশ করা হচ্ছে। | 🇬🇧 High fraud risk! Buyer cancelled/returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Collect advance delivery charge (150 BDT) before shipping.`,
|
||||
carrier_source: sourceLabel,
|
||||
carrier_verified: true,
|
||||
};
|
||||
riskLevel = "CRITICAL";
|
||||
rec = `🇧🇩 মারাত্মক ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। অগ্রিম পেমেন্ট ছাড়া পার্সেল পাঠাবেন না। | 🇬🇧 Critical return risk! Buyer returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Require advance payment before dispatch.`;
|
||||
}
|
||||
|
||||
return {
|
||||
phone: cleanPhone,
|
||||
risk_level: riskLevel,
|
||||
delivery_success_rate: successRateStr,
|
||||
total_parcels: total,
|
||||
total_delivered: delivered,
|
||||
total_cancelled: cancelled,
|
||||
cancellation_rate: cancelRateStr,
|
||||
is_verified_buyer: riskLevel === "LOW" || riskLevel === "MEDIUM",
|
||||
recommendation: rec,
|
||||
carrier_source: sourceLabel,
|
||||
carrier_verified: true,
|
||||
data_sources: dataSources,
|
||||
sample_size: total,
|
||||
coverage_note: `Aggregated ${total} historical consignments from ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")}.`,
|
||||
};
|
||||
}
|
||||
|
||||
// Honest fallback when no merchant API key is plugged in
|
||||
// Honest fallback when no carrier database returned history
|
||||
return {
|
||||
phone: cleanPhone,
|
||||
risk_level: "MODERATE",
|
||||
delivery_success_rate: "অজানা (ক্রেডেনশিয়াল প্রয়োজন) / Unknown (API Key Required)",
|
||||
risk_level: "NO_HISTORY",
|
||||
delivery_success_rate: null,
|
||||
total_parcels: 0,
|
||||
total_delivered: 0,
|
||||
total_cancelled: 0,
|
||||
cancellation_rate: "অজানা / Unknown",
|
||||
cancellation_rate: null,
|
||||
is_verified_buyer: false,
|
||||
recommendation:
|
||||
"🇧🇩 সঠিক বাংলাদেশি মোবাইল নম্বর। লাইভ কুরিয়ার হিস্ট্রি ও ফ্রড রেট চেক করতে Pathao অথবা Steadfast API Key কনফিগার করুন। | 🇬🇧 Valid BD mobile number. Configure Pathao or Steadfast API credentials in your AES-256 Vault to query live nationwide delivery history.",
|
||||
carrier_source: "bd_operator_validator_unverified",
|
||||
"🇧🇩 সঠিক বাংলাদেশি মোবাইল নম্বর, তবে কুরিয়ার হিস্ট্রি পাওয়া যায়নি। ফোনে নিশ্চিত হয়ে ডিসপ্যাচ করুন। | 🇬🇧 Valid BD mobile number, but no live carrier history was returned. Verify via phone call before dispatch.",
|
||||
carrier_source: "prefix_validator",
|
||||
carrier_verified: false,
|
||||
data_sources: ["prefix_validator"],
|
||||
sample_size: 0,
|
||||
coverage_note: "Validated format via BTRC prefix rules only; no upstream carrier history available.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+204
-241
@@ -1,4 +1,10 @@
|
||||
import axios from "axios";
|
||||
import { withGetRetry } from "../envelope.js";
|
||||
import {
|
||||
CARRIER_TARIFF_TABLE,
|
||||
classifyZoneFromAddressAndDistance,
|
||||
computeCourierQuote,
|
||||
} from "../tariffs.js";
|
||||
import {
|
||||
AddressValidationRequest,
|
||||
AddressValidationResponse,
|
||||
@@ -10,14 +16,9 @@ import {
|
||||
ZoneRateResponse,
|
||||
} from "../types.js";
|
||||
|
||||
// Google Maps Platform Skill Attribution & Governance
|
||||
// Attribution ID: gmp_git_agentskills_v1
|
||||
const GMP_ATTRIBUTION_ID = "gmp_git_agentskills_v1";
|
||||
|
||||
export class GoogleMapsAdapter {
|
||||
private apiKey: string;
|
||||
private defaultHub = {
|
||||
// Dhaka Central Logistics Hub (Tejgaon / Mirpur axis)
|
||||
lat: 23.7925,
|
||||
lng: 90.4078,
|
||||
name: "Aura Central Sorting Hub, Dhaka",
|
||||
@@ -32,9 +33,90 @@ export class GoogleMapsAdapter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API
|
||||
* Evaluate road/house/area token match quality and review warnings (T5)
|
||||
*/
|
||||
private buildQualityAssessment(
|
||||
req: AddressValidationRequest,
|
||||
formattedAddress: string,
|
||||
locType: string,
|
||||
rawConfidence: number,
|
||||
thanaResolved: string | null
|
||||
) {
|
||||
const addrIn = String(req.address || "");
|
||||
const fmtLower = String(formattedAddress || "").toLowerCase();
|
||||
|
||||
// Check road token
|
||||
const roadMatch = addrIn.match(/road\s*#?\s*(\d+[a-z]?)/i);
|
||||
let roadOk = true;
|
||||
if (roadMatch) {
|
||||
const roadNum = roadMatch[1].toLowerCase();
|
||||
roadOk =
|
||||
fmtLower.includes(`road ${roadNum}`) ||
|
||||
fmtLower.includes(`rd ${roadNum}`) ||
|
||||
fmtLower.includes(`road-${roadNum}`) ||
|
||||
fmtLower.includes(`road #${roadNum}`);
|
||||
}
|
||||
|
||||
// Check house token
|
||||
const houseMatch = addrIn.match(/house\s*#?\s*(\d+[a-z]?)/i);
|
||||
let houseOk = true;
|
||||
if (houseMatch) {
|
||||
const houseNum = houseMatch[1].toLowerCase();
|
||||
houseOk =
|
||||
fmtLower.includes(`house ${houseNum}`) ||
|
||||
fmtLower.includes(`house-${houseNum}`) ||
|
||||
fmtLower.includes(`house #${houseNum}`) ||
|
||||
(locType === "ROOFTOP" && fmtLower.includes(houseNum));
|
||||
}
|
||||
|
||||
// Check area token
|
||||
const areaTokens = addrIn
|
||||
.toLowerCase()
|
||||
.replace(/road\s*#?\s*\d+[a-z]?/gi, "")
|
||||
.replace(/house\s*#?\s*\d+[a-z]?/gi, "")
|
||||
.split(/[,.-]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length >= 4 && s !== "dhaka" && s !== "bangladesh");
|
||||
const areaOk = areaTokens.length === 0 || areaTokens.some((tok) => fmtLower.includes(tok));
|
||||
|
||||
// Cap confidence at 60 whenever location_type !== "ROOFTOP" (T5)
|
||||
let confidence = locType === "ROOFTOP" ? rawConfidence : Math.min(60, rawConfidence);
|
||||
if (!roadOk || !houseOk) {
|
||||
confidence = Math.min(confidence, 55);
|
||||
}
|
||||
|
||||
const warnings: string[] = [];
|
||||
if (locType !== "ROOFTOP") {
|
||||
warnings.push(`Geocode precision is ${locType} (not ROOFTOP); confidence capped at 60.`);
|
||||
}
|
||||
if (thanaResolved === null) {
|
||||
warnings.push("Thana/sublocality could not be resolved from geocoder components.");
|
||||
}
|
||||
if (req.thana && thanaResolved === null) {
|
||||
warnings.push(`Input thana '${req.thana}' was not independently verified by geocoder.`);
|
||||
}
|
||||
if (!roadOk) {
|
||||
warnings.push("Input road number was not cleanly matched in formatted address.");
|
||||
}
|
||||
if (!houseOk) {
|
||||
warnings.push("Input house number was not cleanly matched as a rooftop premise in formatted address.");
|
||||
}
|
||||
|
||||
const needsReview = confidence < 70 || thanaResolved === null || !roadOk || !houseOk;
|
||||
|
||||
return {
|
||||
confidence,
|
||||
matchQuality: { road: roadOk, house: houseOk, area: areaOk },
|
||||
needsReview,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API (T5)
|
||||
*/
|
||||
async validateAndGeocode(req: AddressValidationRequest): Promise<AddressValidationResponse> {
|
||||
const thanaInput = req.thana ? String(req.thana) : null;
|
||||
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"]
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
@@ -45,15 +127,17 @@ export class GoogleMapsAdapter {
|
||||
|
||||
try {
|
||||
const url = `https://maps.googleapis.com/maps/api/geocode/json`;
|
||||
const res = await axios.get(url, {
|
||||
params: {
|
||||
address: fullQuery,
|
||||
components: "country:BD",
|
||||
language: "bn,en",
|
||||
key: this.apiKey,
|
||||
},
|
||||
timeout: 8000,
|
||||
});
|
||||
const res = await withGetRetry(() =>
|
||||
axios.get(url, {
|
||||
params: {
|
||||
address: fullQuery,
|
||||
components: "country:BD",
|
||||
language: "en",
|
||||
key: this.apiKey,
|
||||
},
|
||||
timeout: 8000,
|
||||
})
|
||||
);
|
||||
|
||||
const data = res.data;
|
||||
if (data.status !== "OK" || !data.results || !data.results.length) {
|
||||
@@ -63,16 +147,24 @@ export class GoogleMapsAdapter {
|
||||
const result = data.results[0];
|
||||
const components = result.address_components || [];
|
||||
const location = result.geometry?.location || { lat: 23.8103, lng: 90.4125 };
|
||||
const locType = result.geometry?.location_type || "APPROXIMATE";
|
||||
const locType = String(result.geometry?.location_type || "APPROXIMATE");
|
||||
|
||||
let thana = "";
|
||||
// Derive thana_resolved strictly from Google address_components; NEVER echo thana_input!
|
||||
let thanaResolved: string | null = null;
|
||||
let district = "";
|
||||
let division = "";
|
||||
|
||||
for (const c of components) {
|
||||
const types = c.types || [];
|
||||
if (types.includes("sublocality") || types.includes("sublocality_level_1") || types.includes("neighborhood")) {
|
||||
thana = c.long_name;
|
||||
const types: string[] = c.types || [];
|
||||
if (
|
||||
types.includes("sublocality") ||
|
||||
types.includes("sublocality_level_1") ||
|
||||
types.includes("administrative_area_level_3") ||
|
||||
types.includes("neighborhood")
|
||||
) {
|
||||
if (!thanaResolved && c.long_name) {
|
||||
thanaResolved = String(c.long_name);
|
||||
}
|
||||
} else if (types.includes("administrative_area_level_2")) {
|
||||
district = c.long_name;
|
||||
} else if (types.includes("administrative_area_level_1")) {
|
||||
@@ -80,15 +172,25 @@ export class GoogleMapsAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
let confidence = 50;
|
||||
if (locType === "ROOFTOP") confidence = 98;
|
||||
else if (locType === "RANGE_INTERPOLATED") confidence = 85;
|
||||
else if (locType === "GEOMETRIC_CENTER") confidence = 70;
|
||||
let rawConf = 50;
|
||||
if (locType === "ROOFTOP") rawConf = 95;
|
||||
else if (locType === "RANGE_INTERPOLATED") rawConf = 60;
|
||||
else if (locType === "GEOMETRIC_CENTER") rawConf = 55;
|
||||
|
||||
const qa = this.buildQualityAssessment(
|
||||
req,
|
||||
result.formatted_address,
|
||||
locType,
|
||||
rawConf,
|
||||
thanaResolved
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
formatted_address: result.formatted_address,
|
||||
thana: thana || req.thana || "",
|
||||
thana_input: thanaInput,
|
||||
thana_resolved: thanaResolved,
|
||||
thana: thanaResolved || "",
|
||||
district: district || req.district || "Dhaka",
|
||||
division: division || "Dhaka Division",
|
||||
coordinates: {
|
||||
@@ -96,17 +198,20 @@ export class GoogleMapsAdapter {
|
||||
lng: location.lng,
|
||||
},
|
||||
location_type: locType,
|
||||
is_deliverable: confidence >= 60,
|
||||
confidence_score: confidence,
|
||||
is_deliverable: qa.confidence >= 50,
|
||||
confidence_score: qa.confidence,
|
||||
match_quality: qa.matchQuality,
|
||||
needs_review: qa.needsReview,
|
||||
warnings: qa.warnings,
|
||||
place_id: result.place_id,
|
||||
};
|
||||
} catch (err: any) {
|
||||
} catch (_) {
|
||||
return this.fallbackAddressParse(req);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute Road Distance & Classify Delivery Zone via Google Routes API
|
||||
* Compute Road Distance & Classify Delivery Zone from Single Tariff Source of Truth (T4)
|
||||
*/
|
||||
async calculateDeliveryZoneAndFee(req: ZoneRateRequest): Promise<ZoneRateResponse> {
|
||||
let destLat = req.destination_coords?.lat;
|
||||
@@ -148,47 +253,33 @@ export class GoogleMapsAdapter {
|
||||
} else {
|
||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||
}
|
||||
} catch (routesErr) {
|
||||
} catch (_) {
|
||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||
}
|
||||
} else if (destLat && destLng) {
|
||||
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
||||
}
|
||||
|
||||
const addr = req.recipient_address.toLowerCase();
|
||||
const isSubDhakaArea = /savar|gazipur|keraniganj|narayanganj|সাভার|গাজীপুর|কেরানীগঞ্জ|নারায়ণগঞ্জ/i.test(addr);
|
||||
|
||||
let zone: "inside_dhaka" | "sub_dhaka" | "outside_dhaka" = "outside_dhaka";
|
||||
let zoneTitle = "ঢাকার বাইরে (সারা বাংলাদেশ)";
|
||||
let fee = 150;
|
||||
let hours = "৭২–৯৬ ঘণ্টা";
|
||||
|
||||
if (roadDistanceKm > 0 && roadDistanceKm <= 22 && !isSubDhakaArea) {
|
||||
zone = "inside_dhaka";
|
||||
zoneTitle = "ঢাকার ভেতরে (মেট্রোপলিটন)";
|
||||
fee = 80;
|
||||
hours = "২৪–৪৮ ঘণ্টা (সরাসরি হোম ডেলিভারি)";
|
||||
} else if ((roadDistanceKm > 22 && roadDistanceKm <= 45) || isSubDhakaArea) {
|
||||
zone = "sub_dhaka";
|
||||
zoneTitle = "সাব-ঢাকা (আশপাশের অঞ্চল)";
|
||||
fee = 100;
|
||||
hours = "৪৮–৭২ ঘণ্টা";
|
||||
}
|
||||
const zoneDef = classifyZoneFromAddressAndDistance(req.recipient_address, roadDistanceKm);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
zone,
|
||||
zone_title: zoneTitle,
|
||||
zone: zoneDef.zone,
|
||||
zone_title: zoneDef.zone_title,
|
||||
distance_km: roadDistanceKm,
|
||||
road_distance_km: roadDistanceKm,
|
||||
estimated_delivery_hours: hours,
|
||||
standard_delivery_fee: fee,
|
||||
cod_charge_percentage: 1.0,
|
||||
sla_hours: zoneDef.sla_hours,
|
||||
estimated_delivery_hours: zoneDef.sla_label,
|
||||
standard_fee_bdt: zoneDef.standard_fee_bdt,
|
||||
standard_delivery_fee: zoneDef.standard_fee_bdt,
|
||||
cod_percent: zoneDef.cod_percent,
|
||||
cod_charge_percentage: zoneDef.cod_percent,
|
||||
route_summary: routeSummary || `Hub to Destination (~${roadDistanceKm} km)`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Enterprise Multi-Carrier Rate Comparison (Steadfast vs Pathao vs RedX vs Paperfly)
|
||||
* Multi-Carrier Rate Comparison backed by Single Tariff Source of Truth (T4)
|
||||
*/
|
||||
async compareRates(req: CourierRateComparisonRequest): Promise<CourierRateComparisonResponse> {
|
||||
const zoneInfo = await this.calculateDeliveryZoneAndFee({
|
||||
@@ -198,118 +289,37 @@ export class GoogleMapsAdapter {
|
||||
|
||||
const weight = req.weight_kg || 0.5;
|
||||
const cod = req.cod_amount || 0;
|
||||
const extraKg = Math.max(0, Math.ceil(weight - 1.0));
|
||||
const couriers: SupportedCourier[] = ["steadfast", "pathao", "redx", "paperfly"];
|
||||
|
||||
// Base rates per carrier based on real BD logistics market tariffs
|
||||
let sfBase = 70, ptBase = 60, rxBase = 80, pfBase = 80;
|
||||
let sfExtra = 20, ptExtra = 25, rxExtra = 20, pfExtra = 25;
|
||||
let sfHours = "২৪–৪৮ ঘণ্টা", ptHours = "১২–২৪ ঘণ্টা (Same-Day)", rxHours = "২৪–৪৮ ঘণ্টা", pfHours = "২৪–৪৮ ঘণ্টা";
|
||||
|
||||
if (zoneInfo.zone === "sub_dhaka") {
|
||||
sfBase = 100; ptBase = 110; rxBase = 110; pfBase = 110;
|
||||
sfHours = "৪৮–৭২ ঘণ্টা"; ptHours = "২৪–৪৮ ঘণ্টা"; rxHours = "৪৮–৭২ ঘণ্টা"; pfHours = "৪৮–৭২ ঘণ্টা";
|
||||
} else if (zoneInfo.zone === "outside_dhaka") {
|
||||
sfBase = 140; ptBase = 150; rxBase = 160; pfBase = 170;
|
||||
sfHours = "৭২–৯৬ ঘণ্টা"; ptHours = "৪৮–৭২ ঘণ্টা"; rxHours = "৭২–৯৬ ঘণ্টা"; pfHours = "৭২–৯৬ ঘণ্টা";
|
||||
}
|
||||
|
||||
const sfCod = Math.round(cod * 0.01);
|
||||
const ptCod = Math.round(cod * 0.01);
|
||||
const rxCod = Math.round(cod * 0.01);
|
||||
const pfCod = Math.round(cod * 0.015);
|
||||
|
||||
const sfTotal = sfBase + (extraKg * sfExtra) + sfCod;
|
||||
const ptTotal = ptBase + (extraKg * ptExtra) + ptCod;
|
||||
const rxTotal = rxBase + (extraKg * rxExtra) + rxCod;
|
||||
const pfTotal = pfBase + (extraKg * pfExtra) + pfCod;
|
||||
|
||||
const carrierQuotes: Array<{
|
||||
courier: SupportedCourier;
|
||||
name: string;
|
||||
base: number;
|
||||
extra: number;
|
||||
cod: number;
|
||||
total: number;
|
||||
hours: string;
|
||||
notes: string;
|
||||
}> = [
|
||||
{
|
||||
courier: "steadfast",
|
||||
name: "Steadfast Courier",
|
||||
base: sfBase,
|
||||
extra: extraKg * sfExtra,
|
||||
cod: sfCod,
|
||||
total: sfTotal,
|
||||
hours: sfHours,
|
||||
notes: "৬৪ জেলা ও সকল থানায় সরাসরি ক্যাশ অন ডেলিভারি হাব নেটওয়ার্ক।",
|
||||
},
|
||||
{
|
||||
courier: "pathao",
|
||||
name: "Pathao Express",
|
||||
base: ptBase,
|
||||
extra: extraKg * ptExtra,
|
||||
cod: ptCod,
|
||||
total: ptTotal,
|
||||
hours: ptHours,
|
||||
notes: "ঢাকা ও প্রধান মেট্রোপলিটন সিটিতে দ্রুততম অন-ডিমান্ড রাইডার পিকআপ।",
|
||||
},
|
||||
{
|
||||
courier: "redx",
|
||||
name: "RedX Delivery",
|
||||
base: rxBase,
|
||||
extra: extraKg * rxExtra,
|
||||
cod: rxCod,
|
||||
total: rxTotal,
|
||||
hours: rxHours,
|
||||
notes: "শক্তিশালী সাব-ডিস্ট্রিক্ট হাব ও বৃহৎ পার্সেল হ্যান্ডলিং নেটওয়ার্ক।",
|
||||
},
|
||||
{
|
||||
courier: "paperfly",
|
||||
name: "Paperfly Go",
|
||||
base: pfBase,
|
||||
extra: extraKg * pfExtra,
|
||||
cod: pfCod,
|
||||
total: pfTotal,
|
||||
hours: pfHours,
|
||||
notes: "প্রত্যন্ত ইউনিয়ন ও ডোরস্টেপ ডেলিভারি কভারেজ।",
|
||||
},
|
||||
];
|
||||
const rawQuotes = couriers.map((c) => computeCourierQuote(c, zoneInfo.zone, weight, cod));
|
||||
|
||||
let recommended: SupportedCourier = "steadfast";
|
||||
let reason = "সর্বনিম্ন খরচ ও ৬৪ জেলায় ৯৯.৮% সফল ডেলিভারি নেটওয়ার্ক";
|
||||
let reason = "Balanced nationwide coverage and cost efficiency.";
|
||||
|
||||
if (zoneInfo.zone === "inside_dhaka" && req.priority === "fastest") {
|
||||
recommended = "pathao";
|
||||
reason = "ঢাকা মেট্রোপলিটনে দ্রুততম সেম-ডে এক্সপ্রেস ডেলিভারি";
|
||||
} else if (req.priority === "cheapest") {
|
||||
const sorted = [...carrierQuotes].sort((a, b) => a.total - b.total);
|
||||
if (req.priority === "cheapest") {
|
||||
const sorted = [...rawQuotes].sort((a, b) => a.total_cost - b.total_cost);
|
||||
recommended = sorted[0].courier;
|
||||
reason = `${sorted[0].name} এই রুটে সর্বনিম্ন খরচে ডেলিভারি প্রদান করে (৳${sorted[0].total})।`;
|
||||
reason = `${sorted[0].courier_name} offers the lowest total tariff on this route (৳${sorted[0].total_cost}).`;
|
||||
} else if (zoneInfo.zone === "inside_dhaka") {
|
||||
recommended = ptTotal <= sfTotal ? "pathao" : "steadfast";
|
||||
reason = "ঢাকা মেট্রোপলিটনে সাশ্রয়ী ডেলিভারি ও দ্রুত পিকআপ";
|
||||
recommended = "pathao";
|
||||
reason = "Lowest base rate and high-density rider pickup within Inside Dhaka.";
|
||||
} else {
|
||||
recommended = "steadfast";
|
||||
reason = "ঢাকার বাইরে সারা বাংলাদেশের ৬৪ জেলায় সর্বোচ্চ কভারেজ ও সর্বনিম্ন রিটার্ন রেট";
|
||||
reason = "Lowest inter-district base tariff and 64-district doorstep COD coverage.";
|
||||
}
|
||||
|
||||
const quotes: CarrierQuote[] = carrierQuotes.map((cq) => ({
|
||||
courier: cq.courier,
|
||||
courier_name: cq.name,
|
||||
base_delivery_fee: cq.base,
|
||||
weight_surcharge: cq.extra,
|
||||
cod_charge: cq.cod,
|
||||
total_cost: cq.total,
|
||||
estimated_hours: cq.hours,
|
||||
coverage_notes: cq.notes,
|
||||
is_recommended: (cq.courier as string) === (recommended as string),
|
||||
const quotes: CarrierQuote[] = rawQuotes.map((rq) => ({
|
||||
...rq,
|
||||
is_recommended: rq.courier === recommended,
|
||||
}));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
zone: zoneInfo.zone,
|
||||
zone_title: zoneInfo.zone_title,
|
||||
distance_km: zoneInfo.distance_km,
|
||||
road_distance_km: zoneInfo.road_distance_km,
|
||||
sla_hours: zoneInfo.sla_hours,
|
||||
weight_kg: weight,
|
||||
cod_amount: cod,
|
||||
recommended_courier: recommended,
|
||||
@@ -319,104 +329,57 @@ export class GoogleMapsAdapter {
|
||||
}
|
||||
|
||||
private async fallbackAddressParse(req: AddressValidationRequest): Promise<AddressValidationResponse> {
|
||||
const thanaInput = req.thana ? String(req.thana) : null;
|
||||
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"].filter(Boolean).join(", ");
|
||||
const lower = fullQuery.toLowerCase();
|
||||
|
||||
// Tier 2: Live OpenStreetMap Nominatim Geocoding (Zero-Billing Fallback)
|
||||
try {
|
||||
const nomRes = await axios.get("https://nominatim.openstreetmap.org/search", {
|
||||
params: {
|
||||
q: fullQuery,
|
||||
countrycodes: "bd",
|
||||
format: "json",
|
||||
addressdetails: 1,
|
||||
limit: 1,
|
||||
},
|
||||
headers: { "User-Agent": "AuraCourierMCP/2.5 (https://courier.auraajenticai.cloud)" },
|
||||
timeout: 5500,
|
||||
});
|
||||
if (Array.isArray(nomRes.data) && nomRes.data.length > 0) {
|
||||
const hit = nomRes.data[0];
|
||||
const addr = hit.address || {};
|
||||
const lat = parseFloat(hit.lat);
|
||||
const lng = parseFloat(hit.lon);
|
||||
const thana = addr.suburb || addr.neighbourhood || addr.town || addr.municipality || addr.city_district || req.thana || "";
|
||||
const district = (addr.county || addr.city || addr.state_district || req.district || "Dhaka").replace(/\s*District$/i, "");
|
||||
const division = addr.state || "Dhaka Division";
|
||||
return {
|
||||
success: true,
|
||||
formatted_address: hit.display_name || fullQuery,
|
||||
thana,
|
||||
district,
|
||||
division,
|
||||
coordinates: { lat, lng },
|
||||
location_type: "GEOMETRIC_CENTER",
|
||||
is_deliverable: true,
|
||||
confidence_score: 88,
|
||||
place_id: `osm_${hit.place_id || Date.now()}`,
|
||||
};
|
||||
}
|
||||
} catch (_) {
|
||||
// Proceed to Tier 3 Spatial Gazetteer
|
||||
}
|
||||
|
||||
// Tier 3: Bangladesh 64-District & Dhaka Thana Spatial Gazetteer
|
||||
const raw = [req.address, req.thana, req.district].filter(Boolean).join(" ").toLowerCase();
|
||||
const gazetteer: Array<{ rx: RegExp; thana: string; district: string; division: string; lat: number; lng: number }> = [
|
||||
{ rx: /mirpur|মিরপুর|pallabi|পল্লবী|kazipara|shewrapara|কাজীপাড়া|শেওড়াপাড়া/, thana: "Mirpur", district: "Dhaka", division: "Dhaka Division", lat: 23.8042, lng: 90.3667 },
|
||||
{ rx: /uttara|উত্তরা|airport|বিমানবন্দর|sector|সেক্টর|dakshin khan|uttar khan/, thana: "Uttara", district: "Dhaka", division: "Dhaka Division", lat: 23.8759, lng: 90.3795 },
|
||||
{ rx: /dhanmondi|ধানমন্ডি|kalabagan|কলাবাগান|jigatola|জিগাতলা|shankar/, thana: "Dhanmondi", district: "Dhaka", division: "Dhaka Division", lat: 23.7461, lng: 90.3742 },
|
||||
{ rx: /gulshan|গুলশান|banani|বনানী|baridhara|বারিধারা|niketan|নিকেতন/, thana: "Gulshan", district: "Dhaka", division: "Dhaka Division", lat: 23.7925, lng: 90.4078 },
|
||||
{ rx: /mohammadpur|মোহাম্মদপুর|adabor|আদাবর|lalmatia|লালমাটিয়া|bosila|বসিলা/, thana: "Mohammadpur", district: "Dhaka", division: "Dhaka Division", lat: 23.7662, lng: 90.3589 },
|
||||
{ rx: /badda|বাড্ডা|rampura|রামপুরা|banasree|বনশ্রী|aftabnagar|আফতাবনগর|hatirjheel/, thana: "Badda", district: "Dhaka", division: "Dhaka Division", lat: 23.7805, lng: 90.4267 },
|
||||
{ rx: /bashundhara|বসুন্ধরা|vatara|ভাটারা|kuril|কুড়িল|nikunja|নিকুঞ্জ|khilkhet|খিলক্ষেত/, thana: "Vatara", district: "Dhaka", division: "Dhaka Division", lat: 23.8191, lng: 90.4526 },
|
||||
{ rx: /motijheel|মতিঝিল|paltan|পল্টন|kakrail|কাকরাইল|shantinagar|শান্তিনগর|malibagh|মালিবাগ|mogbazar|মগবাজার/, thana: "Motijheel", district: "Dhaka", division: "Dhaka Division", lat: 23.7330, lng: 90.4172 },
|
||||
{ rx: /shahbag|শাহবাগ|hatirpool|হাতিরপুল|motaleb|মোতালেব|eleph|এলিফ্যান্ট|new market|নিউ মার্কেট|farmgate|ফার্মগেট|tejgaon|তেজগাঁও|karwan|কারওয়ান/, thana: "Shahbagh", district: "Dhaka", division: "Dhaka Division", lat: 23.7415, lng: 90.3918 },
|
||||
{ rx: /jatrabari|যাত্রাবাড়ী|demra|ডেমরা|kadamtali|কদমতলী|shanir akhra|শনির আখড়া|wari|ওয়ারী|old dhaka|পুরান ঢাকা|lalbagh|লালবাগ|kotwali/, thana: "Jatrabari", district: "Dhaka", division: "Dhaka Division", lat: 23.7104, lng: 90.4348 },
|
||||
{ rx: /keraniganj|কেরানীগঞ্জ|ati bazar|আটি বাজার|atibazar|hasnabad/, thana: "Keraniganj", district: "Dhaka", division: "Dhaka Division", lat: 23.6942, lng: 90.3475 },
|
||||
{ rx: /savar|সাভার|ashulia|আশুলিয়া|hemayetpur|হেমায়েতপুর|dhamrai|ধামরাই/, thana: "Savar", district: "Dhaka", division: "Dhaka Division", lat: 23.8583, lng: 90.2667 },
|
||||
{ rx: /gazipur|গাজীপুর|tongi|টঙ্গী|board bazar|বোর্ড বাজার|joydebpur|জয়দেবপুর|konabari/, thana: "Tongi", district: "Gazipur", division: "Dhaka Division", lat: 23.9889, lng: 90.3950 },
|
||||
{ rx: /narayanganj|নারায়ণগঞ্জ|siddhirganj|সিদ্ধিরগঞ্জ|fatullah|ফতুল্লা|chashara|চাষাড়া|sonargaon|rupganj/, thana: "Narayanganj Sadar", district: "Narayanganj", division: "Dhaka Division", lat: 23.6238, lng: 90.5000 },
|
||||
{ rx: /chattogram|chittagong|চট্টগ্রাম|agrabad|আগ্রাবাদ|nasirabad|নাসিরাবাদ|halishahar|হালিশহর|panchlaish|gec|জিইসি|kotwali/, thana: "Panchlaish", district: "Chattogram", division: "Chattogram Division", lat: 22.3569, lng: 91.7832 },
|
||||
{ rx: /cox.?s?s*bazar|কক্সবাজার|chakaria|teknaf|ukhiya/, thana: "Cox's Bazar Sadar", district: "Cox's Bazar", division: "Chattogram Division", lat: 21.4272, lng: 92.0058 },
|
||||
{ rx: /cumilla|comilla|কুমিল্লা|kandirpar|কান্দিরপাড়|laksam|daudkandi/, thana: "Cumilla Sadar", district: "Cumilla", division: "Chattogram Division", lat: 23.4607, lng: 91.1809 },
|
||||
{ rx: /feni|ফেনী|noakhali|নোয়াখালী|maijdee|চৌমুহনী|lakshmipur|লক্ষ্মীপুর|chandpur|চাঁদপুর|brahmanbaria|ব্রাহ্মণবাড়িয়া/, thana: "Sadar", district: "Noakhali", division: "Chattogram Division", lat: 22.8724, lng: 91.0973 },
|
||||
{ rx: /sylhet|সিলেট|zindabazar|জিন্দাবাজার|amberkhana|আম্বরখানা|upashahar|উপশহর|moulvibazar|মৌলভীবাজার|sreemangal|habiganj|হবিগঞ্জ|sunamganj|সুনামগঞ্জ/, thana: "Sylhet Sadar", district: "Sylhet", division: "Sylhet Division", lat: 24.8949, lng: 91.8687 },
|
||||
{ rx: /rajshahi|রাজশাহী|boalia|বোয়ালিয়া|shaheb bazar|সাহেব বাজার|motihar|নাটোর|natore|naogaon|নওগাঁ|chapainawabganj|চাঁপাইনবাবগঞ্জ|pabna|পাবনা|sirajganj|সিরাজগঞ্জ/, thana: "Boalia", district: "Rajshahi", division: "Rajshahi Division", lat: 24.3745, lng: 88.6042 },
|
||||
{ rx: /bogura|bogra|বগুড়া|sherpur|শেরপুর|joypurhat|জয়পুরহাট/, thana: "Bogura Sadar", district: "Bogura", division: "Rajshahi Division", lat: 24.8481, lng: 89.3730 },
|
||||
{ rx: /khulna|খুলনা|sonadanga|সোনাডাঙ্গা|khalishpur|খালিশপুর|daulatpur|jashore|jessore|যশোর|kushtia|কুষ্টিয়া|satkhira|সাতক্ষীরা|bagerhat|বাগেরহাট|jhenaidah|ঝিনাইদহ/, thana: "Sonadanga", district: "Khulna", division: "Khulna Division", lat: 22.8456, lng: 89.5403 },
|
||||
{ rx: /barishal|barisal|বরিশাল|patukhali|পটুয়াখালী|bhola|ভোলা|pirojpur|পিরোজপুর|jhalokati|barguna/, thana: "Barishal Sadar", district: "Barishal", division: "Barishal Division", lat: 22.7010, lng: 90.3535 },
|
||||
{ rx: /rangpur|রংপুর|dinajpur|দিনাজপুর|thakurgaon|ঠাকুরগাঁও|panchagarh|পঞ্চগড়|nilphamari|নীলফামারী|saidpur|সৈয়দপুর|kurigram|কুড়িগ্রাম|gaibandha|গাইবান্ধা|lalmonirhat/, thana: "Rangpur Sadar", district: "Rangpur", division: "Rangpur Division", lat: 25.7439, lng: 89.2752 },
|
||||
{ rx: /mymensingh|ময়মনসিংহ|jamalpur|জামালপুর|netrokona|নেত্রকোনা|tangail|টাঙ্গাইল|kishoreganj|কিশোরগঞ্জ|faridpur|ফরিদপুর|madaripur|মাদারীপুর|gopalganj|গোপালগঞ্জ|shariatpur|শরীয়তপুর|rajbari|রাজবাড়ী|manikganj|মানিকগঞ্জ|munshiganj|মুন্সিগঞ্জ|narsingdi|নরসিংদী/, thana: "Mymensingh Sadar", district: "Mymensingh", division: "Mymensingh Division", lat: 24.7471, lng: 90.4203 },
|
||||
const BD_DISTRICTS: Array<{ match: RegExp; district: string; division: string; lat: number; lng: number }> = [
|
||||
{ match: /chattogram|chittagong|চট্টগ্রাম/, district: "Chattogram", division: "Chattogram Division", lat: 22.3569, lng: 91.7832 },
|
||||
{ match: /sylhet|সিলেট/, district: "Sylhet", division: "Sylhet Division", lat: 24.8949, lng: 91.8687 },
|
||||
{ match: /rajshahi|রাজশাহী/, district: "Rajshahi", division: "Rajshahi Division", lat: 24.3745, lng: 88.6042 },
|
||||
{ match: /khulna|খুলনা/, district: "Khulna", division: "Khulna Division", lat: 22.8456, lng: 89.5403 },
|
||||
{ match: /barishal|barisal|বরিশাল/, district: "Barishal", division: "Barishal Division", lat: 22.7010, lng: 90.3535 },
|
||||
{ match: /rangpur|রংপুর/, district: "Rangpur", division: "Rangpur Division", lat: 25.7439, lng: 89.2752 },
|
||||
{ match: /mymensingh|ময়মনসিংহ/, district: "Mymensingh", division: "Mymensingh Division", lat: 24.7471, lng: 90.4203 },
|
||||
{ match: /cumilla|comilla|কুমিল্লা/, district: "Cumilla", division: "Chattogram Division", lat: 23.4607, lng: 91.1809 },
|
||||
{ match: /gazipur|গাজীপুর|tongi|টঙ্গী/, district: "Gazipur", division: "Dhaka Division", lat: 23.9999, lng: 90.4203 },
|
||||
{ match: /narayanganj|নারায়ণগঞ্জ/, district: "Narayanganj", division: "Dhaka Division", lat: 23.6238, lng: 90.5000 },
|
||||
{ match: /savar|সাভার|ashulia|আশুলিয়া/, district: "Dhaka", division: "Dhaka Division", lat: 23.8583, lng: 90.2667 },
|
||||
{ match: /keraniganj|কেরানীগঞ্জ|ati bazar|atibazar/, district: "Dhaka", division: "Dhaka Division", lat: 23.7196, lng: 90.3125 },
|
||||
{ match: /uttara|উত্তরা/, district: "Dhaka", division: "Dhaka Division", lat: 23.8759, lng: 90.3795 },
|
||||
{ match: /mirpur|মিরপুর/, district: "Dhaka", division: "Dhaka Division", lat: 23.8042, lng: 90.3667 },
|
||||
{ match: /dhanmondi|ধানমন্ডি/, district: "Dhaka", division: "Dhaka Division", lat: 23.7461, lng: 90.3742 },
|
||||
{ match: /gulshan|গুলশান|banani|বনানী/, district: "Dhaka", division: "Dhaka Division", lat: 23.7925, lng: 90.4078 },
|
||||
];
|
||||
|
||||
for (const g of gazetteer) {
|
||||
if (g.rx.test(raw)) {
|
||||
return {
|
||||
success: true,
|
||||
formatted_address: `${req.address}, ${req.thana || g.thana}, ${req.district || g.district}, Bangladesh`,
|
||||
thana: req.thana || g.thana,
|
||||
district: req.district || g.district,
|
||||
division: g.division,
|
||||
coordinates: { lat: g.lat, lng: g.lng },
|
||||
location_type: "GEOMETRIC_CENTER",
|
||||
is_deliverable: true,
|
||||
confidence_score: 84,
|
||||
place_id: `bd_gazetteer_${g.district.toLowerCase().replace(/\s+/g, "_")}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
const matched = BD_DISTRICTS.find((d) => d.match.test(lower)) || {
|
||||
district: req.district || "Dhaka",
|
||||
division: "Dhaka Division",
|
||||
lat: 23.7805,
|
||||
lng: 90.4078,
|
||||
};
|
||||
|
||||
// Never echo thana_input into thana_resolved in fallback mode
|
||||
const thanaResolved: string | null = null;
|
||||
const locType = "APPROXIMATE";
|
||||
const qa = this.buildQualityAssessment(req, fullQuery, locType, 55, thanaResolved);
|
||||
|
||||
const isDhaka = /dhaka|ঢাকা/i.test(raw);
|
||||
return {
|
||||
success: true,
|
||||
formatted_address: req.address,
|
||||
thana: req.thana || (isDhaka ? "Dhaka Metro" : "Sadar"),
|
||||
district: req.district || (isDhaka ? "Dhaka" : "Outside Dhaka"),
|
||||
division: isDhaka ? "Dhaka Division" : "Bangladesh",
|
||||
coordinates: isDhaka ? { lat: 23.8103, lng: 90.4125 } : { lat: 24.0000, lng: 90.0000 },
|
||||
location_type: "APPROXIMATE",
|
||||
formatted_address: fullQuery,
|
||||
thana_input: thanaInput,
|
||||
thana_resolved: thanaResolved,
|
||||
thana: "",
|
||||
district: matched.district,
|
||||
division: matched.division,
|
||||
coordinates: { lat: matched.lat, lng: matched.lng },
|
||||
location_type: locType,
|
||||
is_deliverable: true,
|
||||
confidence_score: 72,
|
||||
confidence_score: qa.confidence,
|
||||
match_quality: qa.matchQuality,
|
||||
needs_review: true,
|
||||
warnings: qa.warnings,
|
||||
place_id: `bd_gazetteer_${matched.district.toLowerCase()}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -431,6 +394,6 @@ export class GoogleMapsAdapter {
|
||||
Math.sin(dLon / 2) *
|
||||
Math.sin(dLon / 2);
|
||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
return Math.round(R * c * 1.2 * 10) / 10;
|
||||
return Math.round(R * c * 1.25 * 10) / 10;
|
||||
}
|
||||
}
|
||||
|
||||
+29
-53
@@ -1,5 +1,6 @@
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
import { CourierAdapter } from "./base.js";
|
||||
import { McpToolError } from "../envelope.js";
|
||||
import {
|
||||
BalanceResponse,
|
||||
ParcelCreateRequest,
|
||||
@@ -75,15 +76,20 @@ export class PaperflyAdapter implements CourierAdapter {
|
||||
|
||||
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
||||
if (!this.enabled) {
|
||||
throw new Error("Paperfly credentials are not configured.");
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Paperfly credentials are not configured.",
|
||||
courier: "paperfly",
|
||||
});
|
||||
}
|
||||
if (!this.username || !this.password) {
|
||||
throw new Error(
|
||||
"Paperfly tracking needs your merchant-panel username & password (Basic Auth). Add them to use track_parcel."
|
||||
);
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Paperfly tracking requires merchant-panel username and password.",
|
||||
courier: "paperfly",
|
||||
});
|
||||
}
|
||||
try {
|
||||
// Paperfly tracks by your merchant order reference (merchantOrderReference) via POST /API-Order-Tracking
|
||||
const response = await this.client.post(
|
||||
"/API-Order-Tracking",
|
||||
{ ReferenceNumber: trackingCode },
|
||||
@@ -91,14 +97,12 @@ export class PaperflyAdapter implements CourierAdapter {
|
||||
);
|
||||
const data = response.data;
|
||||
if (data?.error) {
|
||||
return {
|
||||
success: false,
|
||||
throw new McpToolError({
|
||||
code: "CONSIGNMENT_NOT_FOUND",
|
||||
message: `Consignment '${trackingCode}' was not found in Paperfly.`,
|
||||
retryable: false,
|
||||
courier: "paperfly",
|
||||
tracking_code: trackingCode,
|
||||
status: "not_found_in_paperfly",
|
||||
updated_at: new Date().toISOString(),
|
||||
raw_response: data,
|
||||
};
|
||||
});
|
||||
}
|
||||
const st = data?.success?.trackingStatus?.[0] || {};
|
||||
const stages: Array<[any, string]> = [
|
||||
@@ -120,59 +124,31 @@ export class PaperflyAdapter implements CourierAdapter {
|
||||
raw_response: data,
|
||||
};
|
||||
} catch (err: any) {
|
||||
if (err instanceof McpToolError) throw err;
|
||||
if (err?.response?.status === 400 || err?.response?.status === 404) {
|
||||
return {
|
||||
success: false,
|
||||
throw new McpToolError({
|
||||
code: "CONSIGNMENT_NOT_FOUND",
|
||||
message: `Consignment '${trackingCode}' was not found in Paperfly.`,
|
||||
retryable: false,
|
||||
courier: "paperfly",
|
||||
tracking_code: trackingCode,
|
||||
status: "not_found_in_paperfly",
|
||||
updated_at: new Date().toISOString(),
|
||||
raw_response: err.response?.data || { message: "No order found in Paperfly for this ReferenceNumber." },
|
||||
};
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 100% Live Paperfly Go Merchant Authentication & Account Settlement Verification
|
||||
* Verifies Basic Auth + paperflykey against https://api.paperfly.com.bd/API-Order-Tracking
|
||||
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
||||
*/
|
||||
async getBalance(): Promise<BalanceResponse> {
|
||||
if (!this.enabled) {
|
||||
throw new Error("Paperfly credentials are not configured.");
|
||||
}
|
||||
let liveVerified = false;
|
||||
let apiResponseCode = 200;
|
||||
try {
|
||||
const res = await this.client.post(
|
||||
"/API-Order-Tracking",
|
||||
{ ReferenceNumber: "AURA-AUTH-PROBE" },
|
||||
{
|
||||
headers: { paperflykey: this.apiKey },
|
||||
auth: { username: this.username, password: this.password },
|
||||
validateStatus: (s) => s < 500,
|
||||
}
|
||||
);
|
||||
apiResponseCode = res.status;
|
||||
liveVerified = res.status === 200 || (res.status === 400 && Boolean(res.data?.error));
|
||||
} catch (_) {
|
||||
liveVerified = false;
|
||||
}
|
||||
|
||||
return {
|
||||
success: liveVerified,
|
||||
success: true,
|
||||
courier: "paperfly",
|
||||
current_balance: 0,
|
||||
raw_response: {
|
||||
live_api_status: liveVerified
|
||||
? "Paperfly Go API Authenticated & Active"
|
||||
: `Paperfly Probe Status ${apiResponseCode}`,
|
||||
currency: "BDT",
|
||||
merchant_code: this.username,
|
||||
store_name: this.storeName || "Default Store",
|
||||
settlement_cycle: "Paperfly Direct BEFTN / Bank Auto-Disbursement",
|
||||
},
|
||||
amount_bdt: null,
|
||||
pending_bdt: null,
|
||||
current_balance: null,
|
||||
status: "UNSUPPORTED_BY_PROVIDER",
|
||||
hint: "Use Paperfly merchant portal",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+28
-83
@@ -1,5 +1,6 @@
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
import { CourierAdapter } from "./base.js";
|
||||
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||
import {
|
||||
BalanceResponse,
|
||||
LocationResolutionResponse,
|
||||
@@ -267,12 +268,18 @@ export class PathaoAdapter implements CourierAdapter {
|
||||
|
||||
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
||||
if (!this.isConfigured()) {
|
||||
throw new Error("Pathao credentials are not configured.");
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Pathao credentials are not configured.",
|
||||
courier: "pathao",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const client = await this.getClient();
|
||||
const response = await client.get(`/aladdin/api/v1/orders/${encodeURIComponent(trackingCode)}/info`);
|
||||
const response = await withGetRetry(() =>
|
||||
client.get(`/aladdin/api/v1/orders/${encodeURIComponent(trackingCode)}/info`)
|
||||
);
|
||||
const data = response.data?.data || {};
|
||||
|
||||
return {
|
||||
@@ -284,98 +291,32 @@ export class PathaoAdapter implements CourierAdapter {
|
||||
raw_response: response.data,
|
||||
};
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404 || err?.response?.status === 400 || err?.response?.status === 422) {
|
||||
return {
|
||||
success: false,
|
||||
const status = err?.response?.status;
|
||||
if (status === 404 || status === 400 || status === 422) {
|
||||
throw new McpToolError({
|
||||
code: "CONSIGNMENT_NOT_FOUND",
|
||||
message: `Consignment '${trackingCode}' was not found in Pathao.`,
|
||||
retryable: false,
|
||||
courier: "pathao",
|
||||
tracking_code: trackingCode,
|
||||
status: "not_found_in_pathao",
|
||||
updated_at: new Date().toISOString(),
|
||||
raw_response: err.response?.data || { message: "Consignment ID not found in Pathao database." },
|
||||
};
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 100% Live Pathao Merchant Balance & Order Settlement Telemetry
|
||||
* Queries GET /aladdin/api/v1/orders/all and GET /aladdin/api/v1/stores
|
||||
* Pathao does not expose a live wallet balance API endpoint (T3).
|
||||
* Returns amount_bdt: null, current_balance: null, status: UNSUPPORTED_BY_PROVIDER.
|
||||
*/
|
||||
async getBalance(): Promise<BalanceResponse> {
|
||||
if (!this.isConfigured()) {
|
||||
throw new Error("Pathao credentials are not configured.");
|
||||
}
|
||||
|
||||
const client = await this.getClient();
|
||||
const [ordersRes, storesRes] = await Promise.all([
|
||||
client.get("/aladdin/api/v1/orders/all?page=1&limit=50").catch(() => ({ data: { data: { data: [], total: 0 } } })),
|
||||
client.get("/aladdin/api/v1/stores").catch(() => ({ data: { data: { data: [] } } })),
|
||||
]);
|
||||
|
||||
const orders: any[] = ordersRes.data?.data?.data || [];
|
||||
const totalOrders = Number(ordersRes.data?.data?.total || orders.length);
|
||||
const stores: any[] = storesRes.data?.data?.data || [];
|
||||
const activeStore = stores.find((s: any) => s.is_active) || stores[0] || null;
|
||||
|
||||
let deliveredCount = 0;
|
||||
let inTransitCount = 0;
|
||||
let cancelledOrReturnedCount = 0;
|
||||
let deliveredCodBdt = 0;
|
||||
let inTransitCodBdt = 0;
|
||||
let totalFeesBdt = 0;
|
||||
let unpaidPendingBdt = 0;
|
||||
|
||||
for (const o of orders) {
|
||||
const st = String(o.order_status || "").toLowerCase();
|
||||
const amt = Number(o.order_amount || 0);
|
||||
const fee = Number(o.total_fee || o.delivery_fee || 0);
|
||||
const billing = String(o.billing_status || "").toLowerCase();
|
||||
|
||||
if (st.includes("cancel") || st.includes("return")) {
|
||||
cancelledOrReturnedCount++;
|
||||
} else if (st.includes("deliver") && !st.includes("hub") && !st.includes("way")) {
|
||||
deliveredCount++;
|
||||
deliveredCodBdt += amt;
|
||||
totalFeesBdt += fee;
|
||||
if (billing === "unpaid") {
|
||||
unpaidPendingBdt += Math.max(0, amt - fee);
|
||||
}
|
||||
} else {
|
||||
inTransitCount++;
|
||||
inTransitCodBdt += amt;
|
||||
}
|
||||
}
|
||||
|
||||
const netDeliveredPayoutBdt = Math.max(0, deliveredCodBdt - totalFeesBdt);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
courier: "pathao",
|
||||
current_balance: netDeliveredPayoutBdt,
|
||||
raw_response: {
|
||||
live_api_status: "OAuth 2.0 Authenticated & Synced",
|
||||
currency: "BDT",
|
||||
total_orders: totalOrders,
|
||||
recent_page_analyzed: orders.length,
|
||||
delivered_orders: deliveredCount,
|
||||
in_transit_orders: inTransitCount,
|
||||
cancelled_or_returned_orders: cancelledOrReturnedCount,
|
||||
delivered_cod_collected_bdt: deliveredCodBdt,
|
||||
in_transit_cod_bdt: inTransitCodBdt,
|
||||
total_carrier_fees_bdt: totalFeesBdt,
|
||||
net_merchant_payout_bdt: netDeliveredPayoutBdt,
|
||||
unpaid_pending_disbursement_bdt: unpaidPendingBdt,
|
||||
active_pickup_store: activeStore
|
||||
? {
|
||||
store_id: activeStore.store_id,
|
||||
store_name: activeStore.store_name,
|
||||
store_address: activeStore.store_address,
|
||||
city_id: activeStore.city_id,
|
||||
zone_id: activeStore.zone_id,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
amount_bdt: null,
|
||||
pending_bdt: null,
|
||||
current_balance: null,
|
||||
status: "UNSUPPORTED_BY_PROVIDER",
|
||||
hint: "Use Pathao merchant portal",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -385,7 +326,11 @@ export class PathaoAdapter implements CourierAdapter {
|
||||
*/
|
||||
async fraudCheck(phone: string): Promise<any> {
|
||||
if (!this.isConfigured()) {
|
||||
throw new Error("Pathao credentials are not configured.");
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Pathao credentials are not configured.",
|
||||
courier: "pathao",
|
||||
});
|
||||
}
|
||||
const cleanPhone = phone.replace(/\D/g, "").replace(/^88/, "");
|
||||
const client = await this.getClient();
|
||||
|
||||
+20
-27
@@ -1,5 +1,6 @@
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
import { CourierAdapter } from "./base.js";
|
||||
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||
import {
|
||||
BalanceResponse,
|
||||
ParcelCreateRequest,
|
||||
@@ -107,10 +108,16 @@ export class RedxAdapter implements CourierAdapter {
|
||||
|
||||
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
||||
if (!this.enabled) {
|
||||
throw new Error("RedX credentials are not configured.");
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "RedX credentials are not configured.",
|
||||
courier: "redx",
|
||||
});
|
||||
}
|
||||
try {
|
||||
const response = await this.client.get(`/parcel/track/${encodeURIComponent(trackingCode)}`);
|
||||
const response = await withGetRetry(() =>
|
||||
this.client.get(`/parcel/track/${encodeURIComponent(trackingCode)}`)
|
||||
);
|
||||
const data = response.data;
|
||||
const events: Array<{ message_en?: string; message_bn?: string; time?: string }> = data?.tracking || [];
|
||||
const latest = events[events.length - 1];
|
||||
@@ -125,43 +132,29 @@ export class RedxAdapter implements CourierAdapter {
|
||||
};
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404 || err?.response?.status === 400) {
|
||||
return {
|
||||
success: false,
|
||||
throw new McpToolError({
|
||||
code: "CONSIGNMENT_NOT_FOUND",
|
||||
message: `Consignment '${trackingCode}' was not found in RedX.`,
|
||||
retryable: false,
|
||||
courier: "redx",
|
||||
tracking_code: trackingCode,
|
||||
status: "not_found_in_redx",
|
||||
updated_at: new Date().toISOString(),
|
||||
raw_response: err.response?.data || { message: "No parcel data found in RedX for this tracking ID." },
|
||||
};
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 100% Live RedX Merchant Account & Pickup Store Verification + Settlement Status
|
||||
* Queries GET /pickup/stores on RedX OpenAPI v1.0.0-beta
|
||||
* RedX does not expose a live wallet balance API endpoint (T3).
|
||||
*/
|
||||
async getBalance(): Promise<BalanceResponse> {
|
||||
if (!this.enabled) {
|
||||
throw new Error("RedX credentials are not configured.");
|
||||
}
|
||||
const response = await this.client.get("/pickup/stores");
|
||||
const stores = response.data?.pickup_stores || [];
|
||||
const primaryStore = stores[0] || null;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
courier: "redx",
|
||||
current_balance: 0,
|
||||
raw_response: {
|
||||
live_api_status: "RedX OpenAPI v1.0.0-beta Authenticated & Active",
|
||||
currency: "BDT",
|
||||
settlement_cycle: "Direct Bank / bKash Automatic Daily Settlement",
|
||||
connected_stores_count: stores.length,
|
||||
active_pickup_store: primaryStore,
|
||||
pickup_stores: stores,
|
||||
},
|
||||
amount_bdt: null,
|
||||
pending_bdt: null,
|
||||
current_balance: null,
|
||||
status: "UNSUPPORTED_BY_PROVIDER",
|
||||
hint: "Use RedX merchant portal",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+45
-22
@@ -1,5 +1,6 @@
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
import { CourierAdapter } from "./base.js";
|
||||
import { McpToolError, withGetRetry } from "../envelope.js";
|
||||
import {
|
||||
BalanceResponse,
|
||||
ParcelCreateRequest,
|
||||
@@ -70,7 +71,11 @@ export class SteadfastAdapter implements CourierAdapter {
|
||||
|
||||
async trackParcel(trackingCode: string): Promise<TrackingResponse> {
|
||||
if (!this.enabled) {
|
||||
throw new Error("Steadfast Courier credentials are not configured.");
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Steadfast Courier credentials are not configured.",
|
||||
courier: "steadfast",
|
||||
});
|
||||
}
|
||||
|
||||
const endpoints = [
|
||||
@@ -82,7 +87,7 @@ export class SteadfastAdapter implements CourierAdapter {
|
||||
let lastErr: any = null;
|
||||
for (const ep of endpoints) {
|
||||
try {
|
||||
const response = await this.client.get(ep);
|
||||
const response = await withGetRetry(() => this.client.get(ep));
|
||||
const data = response.data;
|
||||
if (data && (data.status === 200 || data.delivery_status)) {
|
||||
return {
|
||||
@@ -99,38 +104,53 @@ export class SteadfastAdapter implements CourierAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
// Steadfast Packzy returns HTTP 401/404 when a consignment ID does not belong to the connected merchant account
|
||||
const status = lastErr?.response?.status;
|
||||
if (status === 401 || status === 404 || status === 400) {
|
||||
return {
|
||||
success: false,
|
||||
if (status === 404 || status === 400) {
|
||||
throw new McpToolError({
|
||||
code: "CONSIGNMENT_NOT_FOUND",
|
||||
message: `Consignment '${trackingCode}' was not found in Steadfast.`,
|
||||
retryable: false,
|
||||
courier: "steadfast",
|
||||
tracking_code: trackingCode,
|
||||
status: "not_found_in_steadfast_account",
|
||||
updated_at: new Date().toISOString(),
|
||||
raw_response: {
|
||||
live_api_status: "Packzy API Queried Live",
|
||||
http_status: status,
|
||||
message: "Consignment / tracking code was not found under this merchant's Steadfast account.",
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
if (status === 401 || status === 403) {
|
||||
throw new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: "Steadfast upstream authentication or consignment ownership check failed.",
|
||||
retryable: false,
|
||||
courier: "steadfast",
|
||||
});
|
||||
}
|
||||
|
||||
throw lastErr || new Error("Steadfast tracking lookup failed");
|
||||
throw lastErr || new McpToolError({
|
||||
code: "CONSIGNMENT_NOT_FOUND",
|
||||
message: `Consignment '${trackingCode}' was not found in Steadfast.`,
|
||||
retryable: false,
|
||||
courier: "steadfast",
|
||||
});
|
||||
}
|
||||
|
||||
async getBalance(): Promise<BalanceResponse> {
|
||||
if (!this.enabled) {
|
||||
throw new Error("Steadfast Courier credentials are not configured.");
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Steadfast Courier credentials are not configured.",
|
||||
courier: "steadfast",
|
||||
});
|
||||
}
|
||||
|
||||
const response = await this.client.get("/get_balance");
|
||||
const response = await withGetRetry(() => this.client.get("/get_balance"));
|
||||
const data = response.data;
|
||||
const bal = typeof data?.current_balance === "number" ? data.current_balance : Number(data?.current_balance ?? 0);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
courier: "steadfast",
|
||||
current_balance: Number(data.current_balance || 0),
|
||||
amount_bdt: bal,
|
||||
pending_bdt: 0,
|
||||
current_balance: bal,
|
||||
status: "OK",
|
||||
as_of: new Date().toISOString(),
|
||||
raw_response: data,
|
||||
};
|
||||
}
|
||||
@@ -138,14 +158,17 @@ export class SteadfastAdapter implements CourierAdapter {
|
||||
/**
|
||||
* 100% Real Live Steadfast Fraud Check API
|
||||
* Endpoint: GET /fraud_check/{phone}
|
||||
* Returns nationwide parcel history across Bangladesh: total_parcels, total_delivered, total_cancelled
|
||||
*/
|
||||
async fraudCheck(phone: string): Promise<any> {
|
||||
if (!this.enabled) {
|
||||
throw new Error("Steadfast Courier credentials are not configured.");
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Steadfast Courier credentials are not configured.",
|
||||
courier: "steadfast",
|
||||
});
|
||||
}
|
||||
const cleanPhone = phone.replace(/\D/g, "");
|
||||
const response = await this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`);
|
||||
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
||||
return response.data;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user