aura-courier-mcp 2.3.2 → 2.7.1
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/LICENSE +192 -21
- package/README.md +359 -26
- package/README.md.metadata.json +4 -0
- package/dist/adapters/base.d.ts +1 -0
- package/dist/adapters/base.js.map +1 -0
- package/dist/adapters/fraud_engine.d.ts +8 -1
- package/dist/adapters/fraud_engine.js +137 -21
- package/dist/adapters/google_maps.d.ts +25 -0
- package/dist/adapters/google_maps.js +334 -0
- package/dist/adapters/paperfly.d.ts +14 -0
- package/dist/adapters/paperfly.js +102 -22
- package/dist/adapters/pathao.d.ts +37 -1
- package/dist/adapters/pathao.js +247 -31
- package/dist/adapters/pathao.js.map +1 -0
- package/dist/adapters/redx.d.ts +14 -0
- package/dist/adapters/redx.js +81 -12
- package/dist/adapters/registry.d.ts +20 -0
- package/dist/adapters/registry.js +34 -0
- package/dist/adapters/registry.js.map +1 -0
- package/dist/adapters/steadfast.d.ts +17 -0
- package/dist/adapters/steadfast.js +121 -12
- package/dist/adapters/steadfast.js.map +1 -0
- package/dist/config.d.ts +4 -0
- package/dist/config.js +16 -2
- package/dist/config.js.map +1 -0
- package/dist/envelope.d.ts +55 -0
- package/dist/envelope.js +159 -0
- package/dist/http.d.ts +8 -1
- package/dist/http.js +699 -58
- package/dist/http.js.map +1 -0
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -0
- package/dist/middleware/auth.d.ts +100 -0
- package/dist/middleware/auth.js +585 -0
- package/dist/middleware/oauth.d.ts +19 -0
- package/dist/middleware/oauth.js +1376 -0
- package/dist/middleware/rate_limit.d.ts +9 -0
- package/dist/middleware/rate_limit.js +71 -0
- package/dist/pages.d.ts +8 -0
- package/dist/pages.js +317 -0
- package/dist/pages.js.map +1 -0
- package/dist/registry.d.ts +51 -6
- package/dist/registry.js +625 -28
- package/dist/server.d.ts +11 -1
- package/dist/server.js +407 -51
- package/dist/server.js.map +1 -0
- package/dist/tariffs.d.ts +46 -0
- package/dist/tariffs.js +153 -0
- package/dist/test_zero_risk.js +49 -25
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +162 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/types.d.ts +188 -4
- package/dist/types.js.map +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +16 -0
- package/package.json +12 -9
|
@@ -1,38 +1,154 @@
|
|
|
1
1
|
export class FraudRiskEngine {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Real-Time Multi-Carrier Fraud & Delivery Risk Evaluation (T6)
|
|
4
|
+
* Queries Pathao Nationwide Customer Delivery Database (/aladdin/api/v1/user/success),
|
|
5
|
+
* Steadfast Nationwide Logistics Database (/fraud_check/{phone}), and BD Operator Prefix Validator.
|
|
6
|
+
*/
|
|
7
|
+
static async evaluateRisk(phoneNumber, steadfastAdapter, pathaoAdapter) {
|
|
8
|
+
const rawDigits = String(phoneNumber || "").replace(/[^0-9]/g, "");
|
|
9
|
+
const cleanPhone = rawDigits.startsWith("880") && rawDigits.length === 13 ? rawDigits.slice(2) : rawDigits;
|
|
10
|
+
// Valid BD Mobile format check (11 digits starting with 013, 014, 015, 016, 017, 018, 019)
|
|
5
11
|
const isValidBDOperator = /^01[3-9]\d{8}$/.test(cleanPhone);
|
|
6
12
|
if (!isValidBDOperator) {
|
|
7
13
|
return {
|
|
8
14
|
phone: phoneNumber,
|
|
9
|
-
risk_level: "
|
|
10
|
-
delivery_success_rate:
|
|
15
|
+
risk_level: "INVALID_NUMBER",
|
|
16
|
+
delivery_success_rate: null,
|
|
17
|
+
total_parcels: 0,
|
|
18
|
+
total_delivered: 0,
|
|
19
|
+
total_cancelled: 0,
|
|
20
|
+
cancellation_rate: null,
|
|
11
21
|
is_verified_buyer: false,
|
|
12
|
-
recommendation: "
|
|
13
|
-
|
|
22
|
+
recommendation: "🇧🇩 ভুল বা অকার্যকর বাংলাদেশি মোবাইল নম্বর। ম্যানুয়াল ভেরিফিকেশন ছাড়া পার্সেল বুক করবেন না। | 🇬🇧 Invalid Bangladesh mobile number (11 digits starting with 013–019 required). Do not dispatch without manual verification.",
|
|
23
|
+
carrier_source: "prefix_validator",
|
|
24
|
+
carrier_verified: false,
|
|
25
|
+
data_sources: ["prefix_validator"],
|
|
26
|
+
sample_size: 0,
|
|
27
|
+
coverage_note: "Validated against BTRC 11-digit mobile operator prefix rules (013–019).",
|
|
14
28
|
};
|
|
15
29
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
30
|
+
let total = 0;
|
|
31
|
+
let delivered = 0;
|
|
32
|
+
let cancelled = 0;
|
|
33
|
+
let verifiedByCarrier = false;
|
|
34
|
+
const dataSources = [];
|
|
35
|
+
let customerRating;
|
|
36
|
+
// 1. Query Steadfast Nationwide Fraud Database (GET /fraud_check/{phone})
|
|
37
|
+
if (steadfastAdapter && steadfastAdapter.isConfigured()) {
|
|
38
|
+
try {
|
|
39
|
+
const sfData = await steadfastAdapter.fraudCheck(cleanPhone);
|
|
40
|
+
const sfTotal = Number(sfData?.total_parcels ?? sfData?.data?.total_parcels ?? 0);
|
|
41
|
+
const sfDelivered = Number(sfData?.total_delivered ?? sfData?.data?.total_delivered ?? 0);
|
|
42
|
+
const sfCancelled = Number(sfData?.total_cancelled ?? sfData?.data?.total_cancelled ?? 0);
|
|
43
|
+
total += sfTotal;
|
|
44
|
+
delivered += sfDelivered;
|
|
45
|
+
cancelled += sfCancelled;
|
|
46
|
+
verifiedByCarrier = true;
|
|
47
|
+
dataSources.push("steadfast_nationwide");
|
|
48
|
+
}
|
|
49
|
+
catch (_) {
|
|
50
|
+
// Continue to Pathao check
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// 2. Query Pathao Nationwide Customer Delivery Database (POST /aladdin/api/v1/user/success)
|
|
54
|
+
if (pathaoAdapter && pathaoAdapter.isConfigured()) {
|
|
55
|
+
try {
|
|
56
|
+
const ptRes = await pathaoAdapter.fraudCheck(cleanPhone);
|
|
57
|
+
const ptData = ptRes?.data || ptRes || {};
|
|
58
|
+
const cust = ptData.customer || {};
|
|
59
|
+
const ptTotal = Number(cust.total_delivery ?? 0);
|
|
60
|
+
const ptDelivered = Number(cust.successful_delivery ?? 0);
|
|
61
|
+
const ptCancelled = Math.max(0, ptTotal - ptDelivered);
|
|
62
|
+
total += ptTotal;
|
|
63
|
+
delivered += ptDelivered;
|
|
64
|
+
cancelled += ptCancelled;
|
|
65
|
+
verifiedByCarrier = true;
|
|
66
|
+
dataSources.push("pathao_nationwide");
|
|
67
|
+
if (ptData.customer_rating) {
|
|
68
|
+
customerRating = String(ptData.customer_rating);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch (_) {
|
|
72
|
+
// Carrier lookup error handled gracefully
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
dataSources.push("prefix_validator");
|
|
76
|
+
const sourceLabel = dataSources.join("+");
|
|
77
|
+
if (verifiedByCarrier) {
|
|
78
|
+
if (total === 0) {
|
|
79
|
+
return {
|
|
80
|
+
phone: cleanPhone,
|
|
81
|
+
risk_level: "NO_HISTORY",
|
|
82
|
+
delivery_success_rate: null,
|
|
83
|
+
total_parcels: 0,
|
|
84
|
+
total_delivered: 0,
|
|
85
|
+
total_cancelled: 0,
|
|
86
|
+
cancellation_rate: null,
|
|
87
|
+
is_verified_buyer: true,
|
|
88
|
+
recommendation: "🇧🇩 কুরিয়ার ডেটাবেজে পূর্বে কোনো অর্ডার বা রিটার্ন রেকর্ড নেই (নতুন ক্রেতা)। ফোনে ঠিকানা কনফার্ম করে পাঠানো যেতে পারে। | 🇬🇧 No prior delivery or return history found in queried courier databases. Confirm via phone call before COD dispatch.",
|
|
89
|
+
carrier_source: sourceLabel,
|
|
90
|
+
carrier_verified: true,
|
|
91
|
+
data_sources: dataSources,
|
|
92
|
+
sample_size: 0,
|
|
93
|
+
coverage_note: `Queried ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")} live databases; 0 prior consignments recorded.`,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const successRatio = (delivered / total) * 100;
|
|
97
|
+
const cancelRatio = (cancelled / total) * 100;
|
|
98
|
+
const successRateStr = `${successRatio.toFixed(1)}%`;
|
|
99
|
+
const cancelRateStr = `${cancelRatio.toFixed(1)}%`;
|
|
100
|
+
const ratingNote = customerRating ? ` [Carrier Rating: ${customerRating}]` : "";
|
|
101
|
+
let riskLevel = "LOW";
|
|
102
|
+
let rec = "";
|
|
103
|
+
if (successRatio >= 80) {
|
|
104
|
+
riskLevel = "LOW";
|
|
105
|
+
rec = `🇧🇩 কাস্টমার অত্যন্ত নির্ভরযোগ্য (সফল ডেলিভারি: ${delivered}/${total}টি, সাকসেস রেট: ${successRateStr})। নির্দ্বিধায় ক্যাশ অন ডেলিভারি (COD) পাঠান। | 🇬🇧 Highly reliable buyer (${delivered}/${total} delivered, ${successRateStr} success rate)${ratingNote}. Safe for immediate COD dispatch.`;
|
|
106
|
+
}
|
|
107
|
+
else if (successRatio >= 55) {
|
|
108
|
+
riskLevel = "MEDIUM";
|
|
109
|
+
rec = `🇧🇩 মাঝারি ঝুঁকি (সফল: ${delivered}টি, ক্যানসেল/রিটার্ন: ${cancelled}টি, ক্যানসেলেশন রেট: ${cancelRateStr})। পার্সেল পাঠানোর আগে কাস্টমারকে ফোন দিয়ে অর্ডার কনফার্ম করুন। | 🇬🇧 Medium risk (${delivered} delivered, ${cancelled} returned, ${cancelRateStr} return rate)${ratingNote}. Confirm order via phone call before dispatch.`;
|
|
110
|
+
}
|
|
111
|
+
else if (successRatio >= 25) {
|
|
112
|
+
riskLevel = "HIGH";
|
|
113
|
+
rec = `🇧🇩 উচ্চ ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} ক্যানসেল/রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। ডেলিভারি চার্জ অগ্রিম নেওয়ার সুপারিশ করা হচ্ছে। | 🇬🇧 High fraud risk! Buyer cancelled/returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Collect advance delivery charge before shipping.`;
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
riskLevel = "CRITICAL";
|
|
117
|
+
rec = `🇧🇩 মারাত্মক ঝুঁকির ক্রেতা! পূর্ববর্তী অর্ডারের ${cancelRateStr} রিটার্ন করেছেন (${cancelled}/${total}টি রিটার্ন)। অগ্রিম পেমেন্ট ছাড়া পার্সেল পাঠাবেন না। | 🇬🇧 Critical return risk! Buyer returned ${cancelRateStr} of past orders (${cancelled}/${total} returned)${ratingNote}. Require advance payment before dispatch.`;
|
|
118
|
+
}
|
|
19
119
|
return {
|
|
20
120
|
phone: cleanPhone,
|
|
21
|
-
risk_level:
|
|
22
|
-
delivery_success_rate:
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
121
|
+
risk_level: riskLevel,
|
|
122
|
+
delivery_success_rate: successRateStr,
|
|
123
|
+
total_parcels: total,
|
|
124
|
+
total_delivered: delivered,
|
|
125
|
+
total_cancelled: cancelled,
|
|
126
|
+
cancellation_rate: cancelRateStr,
|
|
127
|
+
is_verified_buyer: riskLevel === "LOW" || riskLevel === "MEDIUM",
|
|
128
|
+
recommendation: rec,
|
|
129
|
+
carrier_source: sourceLabel,
|
|
130
|
+
carrier_verified: true,
|
|
131
|
+
data_sources: dataSources,
|
|
132
|
+
sample_size: total,
|
|
133
|
+
coverage_note: `Aggregated ${total} historical consignments from ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")}.`,
|
|
26
134
|
};
|
|
27
135
|
}
|
|
28
|
-
//
|
|
136
|
+
// Honest fallback when no carrier database returned history
|
|
29
137
|
return {
|
|
30
138
|
phone: cleanPhone,
|
|
31
|
-
risk_level: "
|
|
32
|
-
delivery_success_rate:
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
139
|
+
risk_level: "NO_HISTORY",
|
|
140
|
+
delivery_success_rate: null,
|
|
141
|
+
total_parcels: 0,
|
|
142
|
+
total_delivered: 0,
|
|
143
|
+
total_cancelled: 0,
|
|
144
|
+
cancellation_rate: null,
|
|
145
|
+
is_verified_buyer: false,
|
|
146
|
+
recommendation: "🇧🇩 সঠিক বাংলাদেশি মোবাইল নম্বর, তবে কুরিয়ার হিস্ট্রি পাওয়া যায়নি। ফোনে নিশ্চিত হয়ে ডিসপ্যাচ করুন। | 🇬🇧 Valid BD mobile number, but no live carrier history was returned. Verify via phone call before dispatch.",
|
|
147
|
+
carrier_source: "prefix_validator",
|
|
148
|
+
carrier_verified: false,
|
|
149
|
+
data_sources: ["prefix_validator"],
|
|
150
|
+
sample_size: 0,
|
|
151
|
+
coverage_note: "Validated format via BTRC prefix rules only; no upstream carrier history available.",
|
|
36
152
|
};
|
|
37
153
|
}
|
|
38
154
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { AddressValidationRequest, AddressValidationResponse, CourierRateComparisonRequest, CourierRateComparisonResponse, ZoneRateRequest, ZoneRateResponse } from "../types.js";
|
|
2
|
+
export declare class GoogleMapsAdapter {
|
|
3
|
+
private apiKey;
|
|
4
|
+
private defaultHub;
|
|
5
|
+
constructor(apiKey?: string);
|
|
6
|
+
isConfigured(): boolean;
|
|
7
|
+
/**
|
|
8
|
+
* Evaluate road/house/area token match quality and review warnings (T5)
|
|
9
|
+
*/
|
|
10
|
+
private buildQualityAssessment;
|
|
11
|
+
/**
|
|
12
|
+
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API (T5)
|
|
13
|
+
*/
|
|
14
|
+
validateAndGeocode(req: AddressValidationRequest): Promise<AddressValidationResponse>;
|
|
15
|
+
/**
|
|
16
|
+
* Compute Road Distance & Classify Delivery Zone from Single Tariff Source of Truth (T4)
|
|
17
|
+
*/
|
|
18
|
+
calculateDeliveryZoneAndFee(req: ZoneRateRequest): Promise<ZoneRateResponse>;
|
|
19
|
+
/**
|
|
20
|
+
* Multi-Carrier Rate Comparison backed by Single Tariff Source of Truth (T4)
|
|
21
|
+
*/
|
|
22
|
+
compareRates(req: CourierRateComparisonRequest): Promise<CourierRateComparisonResponse>;
|
|
23
|
+
private fallbackAddressParse;
|
|
24
|
+
private haversineDistance;
|
|
25
|
+
}
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import { withGetRetry } from "../envelope.js";
|
|
3
|
+
import { classifyZoneFromAddressAndDistance, computeCourierQuote, } from "../tariffs.js";
|
|
4
|
+
export class GoogleMapsAdapter {
|
|
5
|
+
apiKey;
|
|
6
|
+
defaultHub = {
|
|
7
|
+
lat: 23.7925,
|
|
8
|
+
lng: 90.4078,
|
|
9
|
+
name: "Aura Central Sorting Hub, Dhaka",
|
|
10
|
+
};
|
|
11
|
+
constructor(apiKey = "") {
|
|
12
|
+
this.apiKey = apiKey || process.env.GOOGLE_MAPS_API_KEY || "";
|
|
13
|
+
}
|
|
14
|
+
isConfigured() {
|
|
15
|
+
return Boolean(this.apiKey);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Evaluate road/house/area token match quality and review warnings (T5)
|
|
19
|
+
*/
|
|
20
|
+
buildQualityAssessment(req, formattedAddress, locType, rawConfidence, thanaResolved) {
|
|
21
|
+
const addrIn = String(req.address || "");
|
|
22
|
+
const fmtLower = String(formattedAddress || "").toLowerCase();
|
|
23
|
+
// Check road token
|
|
24
|
+
const roadMatch = addrIn.match(/road\s*#?\s*(\d+[a-z]?)/i);
|
|
25
|
+
let roadOk = true;
|
|
26
|
+
if (roadMatch) {
|
|
27
|
+
const roadNum = roadMatch[1].toLowerCase();
|
|
28
|
+
roadOk =
|
|
29
|
+
fmtLower.includes(`road ${roadNum}`) ||
|
|
30
|
+
fmtLower.includes(`rd ${roadNum}`) ||
|
|
31
|
+
fmtLower.includes(`road-${roadNum}`) ||
|
|
32
|
+
fmtLower.includes(`road #${roadNum}`);
|
|
33
|
+
}
|
|
34
|
+
// Check house token
|
|
35
|
+
const houseMatch = addrIn.match(/house\s*#?\s*(\d+[a-z]?)/i);
|
|
36
|
+
let houseOk = true;
|
|
37
|
+
if (houseMatch) {
|
|
38
|
+
const houseNum = houseMatch[1].toLowerCase();
|
|
39
|
+
houseOk =
|
|
40
|
+
fmtLower.includes(`house ${houseNum}`) ||
|
|
41
|
+
fmtLower.includes(`house-${houseNum}`) ||
|
|
42
|
+
fmtLower.includes(`house #${houseNum}`) ||
|
|
43
|
+
(locType === "ROOFTOP" && fmtLower.includes(houseNum));
|
|
44
|
+
}
|
|
45
|
+
// Check area token
|
|
46
|
+
const areaTokens = addrIn
|
|
47
|
+
.toLowerCase()
|
|
48
|
+
.replace(/road\s*#?\s*\d+[a-z]?/gi, "")
|
|
49
|
+
.replace(/house\s*#?\s*\d+[a-z]?/gi, "")
|
|
50
|
+
.split(/[,.-]+/)
|
|
51
|
+
.map((s) => s.trim())
|
|
52
|
+
.filter((s) => s.length >= 4 && s !== "dhaka" && s !== "bangladesh");
|
|
53
|
+
const areaOk = areaTokens.length === 0 || areaTokens.some((tok) => fmtLower.includes(tok));
|
|
54
|
+
// Cap confidence at 60 whenever location_type !== "ROOFTOP" (T5)
|
|
55
|
+
let confidence = locType === "ROOFTOP" ? rawConfidence : Math.min(60, rawConfidence);
|
|
56
|
+
if (!roadOk || !houseOk) {
|
|
57
|
+
confidence = Math.min(confidence, 55);
|
|
58
|
+
}
|
|
59
|
+
const warnings = [];
|
|
60
|
+
if (locType !== "ROOFTOP") {
|
|
61
|
+
warnings.push(`Geocode precision is ${locType} (not ROOFTOP); confidence capped at 60.`);
|
|
62
|
+
}
|
|
63
|
+
if (thanaResolved === null) {
|
|
64
|
+
warnings.push("Thana/sublocality could not be resolved from geocoder components.");
|
|
65
|
+
}
|
|
66
|
+
if (req.thana && thanaResolved === null) {
|
|
67
|
+
warnings.push(`Input thana '${req.thana}' was not independently verified by geocoder.`);
|
|
68
|
+
}
|
|
69
|
+
if (!roadOk) {
|
|
70
|
+
warnings.push("Input road number was not cleanly matched in formatted address.");
|
|
71
|
+
}
|
|
72
|
+
if (!houseOk) {
|
|
73
|
+
warnings.push("Input house number was not cleanly matched as a rooftop premise in formatted address.");
|
|
74
|
+
}
|
|
75
|
+
const needsReview = confidence < 70 || thanaResolved === null || !roadOk || !houseOk;
|
|
76
|
+
return {
|
|
77
|
+
confidence,
|
|
78
|
+
matchQuality: { road: roadOk, house: houseOk, area: areaOk },
|
|
79
|
+
needsReview,
|
|
80
|
+
warnings,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Validate and Geocode Bangladesh Address using Google Maps Geocoding API (T5)
|
|
85
|
+
*/
|
|
86
|
+
async validateAndGeocode(req) {
|
|
87
|
+
const thanaInput = req.thana ? String(req.thana) : null;
|
|
88
|
+
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"]
|
|
89
|
+
.filter(Boolean)
|
|
90
|
+
.join(", ");
|
|
91
|
+
if (!this.apiKey) {
|
|
92
|
+
return this.fallbackAddressParse(req);
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
const url = `https://maps.googleapis.com/maps/api/geocode/json`;
|
|
96
|
+
const res = await withGetRetry(() => axios.get(url, {
|
|
97
|
+
params: {
|
|
98
|
+
address: fullQuery,
|
|
99
|
+
components: "country:BD",
|
|
100
|
+
language: "en",
|
|
101
|
+
key: this.apiKey,
|
|
102
|
+
},
|
|
103
|
+
timeout: 8000,
|
|
104
|
+
}));
|
|
105
|
+
const data = res.data;
|
|
106
|
+
if (data.status !== "OK" || !data.results || !data.results.length) {
|
|
107
|
+
return this.fallbackAddressParse(req);
|
|
108
|
+
}
|
|
109
|
+
const result = data.results[0];
|
|
110
|
+
const components = result.address_components || [];
|
|
111
|
+
const location = result.geometry?.location || { lat: 23.8103, lng: 90.4125 };
|
|
112
|
+
const locType = String(result.geometry?.location_type || "APPROXIMATE");
|
|
113
|
+
// Derive thana_resolved strictly from Google address_components; NEVER echo thana_input!
|
|
114
|
+
let thanaResolved = null;
|
|
115
|
+
let district = "";
|
|
116
|
+
let division = "";
|
|
117
|
+
for (const c of components) {
|
|
118
|
+
const types = c.types || [];
|
|
119
|
+
if (types.includes("sublocality") ||
|
|
120
|
+
types.includes("sublocality_level_1") ||
|
|
121
|
+
types.includes("administrative_area_level_3") ||
|
|
122
|
+
types.includes("neighborhood")) {
|
|
123
|
+
if (!thanaResolved && c.long_name) {
|
|
124
|
+
thanaResolved = String(c.long_name);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
else if (types.includes("administrative_area_level_2")) {
|
|
128
|
+
district = c.long_name;
|
|
129
|
+
}
|
|
130
|
+
else if (types.includes("administrative_area_level_1")) {
|
|
131
|
+
division = c.long_name;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
let rawConf = 50;
|
|
135
|
+
if (locType === "ROOFTOP")
|
|
136
|
+
rawConf = 95;
|
|
137
|
+
else if (locType === "RANGE_INTERPOLATED")
|
|
138
|
+
rawConf = 60;
|
|
139
|
+
else if (locType === "GEOMETRIC_CENTER")
|
|
140
|
+
rawConf = 55;
|
|
141
|
+
const qa = this.buildQualityAssessment(req, result.formatted_address, locType, rawConf, thanaResolved);
|
|
142
|
+
return {
|
|
143
|
+
success: true,
|
|
144
|
+
formatted_address: result.formatted_address,
|
|
145
|
+
thana_input: thanaInput,
|
|
146
|
+
thana_resolved: thanaResolved,
|
|
147
|
+
thana: thanaResolved || "",
|
|
148
|
+
district: district || req.district || "Dhaka",
|
|
149
|
+
division: division || "Dhaka Division",
|
|
150
|
+
coordinates: {
|
|
151
|
+
lat: location.lat,
|
|
152
|
+
lng: location.lng,
|
|
153
|
+
},
|
|
154
|
+
location_type: locType,
|
|
155
|
+
is_deliverable: qa.confidence >= 50,
|
|
156
|
+
confidence_score: qa.confidence,
|
|
157
|
+
match_quality: qa.matchQuality,
|
|
158
|
+
needs_review: qa.needsReview,
|
|
159
|
+
warnings: qa.warnings,
|
|
160
|
+
place_id: result.place_id,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
catch (_) {
|
|
164
|
+
return this.fallbackAddressParse(req);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Compute Road Distance & Classify Delivery Zone from Single Tariff Source of Truth (T4)
|
|
169
|
+
*/
|
|
170
|
+
async calculateDeliveryZoneAndFee(req) {
|
|
171
|
+
let destLat = req.destination_coords?.lat;
|
|
172
|
+
let destLng = req.destination_coords?.lng;
|
|
173
|
+
if (!destLat || !destLng) {
|
|
174
|
+
const geo = await this.validateAndGeocode({ address: req.recipient_address });
|
|
175
|
+
destLat = geo.coordinates.lat;
|
|
176
|
+
destLng = geo.coordinates.lng;
|
|
177
|
+
}
|
|
178
|
+
let roadDistanceKm = 0;
|
|
179
|
+
let routeSummary = "";
|
|
180
|
+
if (this.apiKey && destLat && destLng) {
|
|
181
|
+
try {
|
|
182
|
+
const routesUrl = "https://routes.googleapis.com/directions/v2:computeRoutes";
|
|
183
|
+
const routesRes = await axios.post(routesUrl, {
|
|
184
|
+
origin: { location: { latLng: { latitude: this.defaultHub.lat, longitude: this.defaultHub.lng } } },
|
|
185
|
+
destination: { location: { latLng: { latitude: destLat, longitude: destLng } } },
|
|
186
|
+
travelMode: "DRIVE",
|
|
187
|
+
}, {
|
|
188
|
+
headers: {
|
|
189
|
+
"Content-Type": "application/json",
|
|
190
|
+
"X-Goog-Api-Key": this.apiKey,
|
|
191
|
+
"X-Goog-FieldMask": "routes.distanceMeters,routes.duration,routes.description",
|
|
192
|
+
},
|
|
193
|
+
timeout: 8000,
|
|
194
|
+
});
|
|
195
|
+
const route = routesRes.data?.routes?.[0];
|
|
196
|
+
if (route && route.distanceMeters) {
|
|
197
|
+
roadDistanceKm = Math.round((route.distanceMeters / 1000) * 10) / 10;
|
|
198
|
+
routeSummary = route.description || "";
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
catch (_) {
|
|
205
|
+
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
else if (destLat && destLng) {
|
|
209
|
+
roadDistanceKm = this.haversineDistance(this.defaultHub.lat, this.defaultHub.lng, destLat, destLng);
|
|
210
|
+
}
|
|
211
|
+
const zoneDef = classifyZoneFromAddressAndDistance(req.recipient_address, roadDistanceKm);
|
|
212
|
+
return {
|
|
213
|
+
success: true,
|
|
214
|
+
zone: zoneDef.zone,
|
|
215
|
+
zone_title: zoneDef.zone_title,
|
|
216
|
+
distance_km: roadDistanceKm,
|
|
217
|
+
road_distance_km: roadDistanceKm,
|
|
218
|
+
sla_hours: zoneDef.sla_hours,
|
|
219
|
+
estimated_delivery_hours: zoneDef.sla_label,
|
|
220
|
+
standard_fee_bdt: zoneDef.standard_fee_bdt,
|
|
221
|
+
standard_delivery_fee: zoneDef.standard_fee_bdt,
|
|
222
|
+
cod_percent: zoneDef.cod_percent,
|
|
223
|
+
cod_charge_percentage: zoneDef.cod_percent,
|
|
224
|
+
route_summary: routeSummary || `Hub to Destination (~${roadDistanceKm} km)`,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Multi-Carrier Rate Comparison backed by Single Tariff Source of Truth (T4)
|
|
229
|
+
*/
|
|
230
|
+
async compareRates(req) {
|
|
231
|
+
const zoneInfo = await this.calculateDeliveryZoneAndFee({
|
|
232
|
+
recipient_address: req.recipient_address,
|
|
233
|
+
weight_kg: req.weight_kg || 0.5,
|
|
234
|
+
});
|
|
235
|
+
const weight = req.weight_kg || 0.5;
|
|
236
|
+
const cod = req.cod_amount || 0;
|
|
237
|
+
const couriers = ["steadfast", "pathao", "redx", "paperfly"];
|
|
238
|
+
const rawQuotes = couriers.map((c) => computeCourierQuote(c, zoneInfo.zone, weight, cod));
|
|
239
|
+
let recommended = "steadfast";
|
|
240
|
+
let reason = "Balanced nationwide coverage and cost efficiency.";
|
|
241
|
+
if (req.priority === "cheapest") {
|
|
242
|
+
const sorted = [...rawQuotes].sort((a, b) => a.total_cost - b.total_cost);
|
|
243
|
+
recommended = sorted[0].courier;
|
|
244
|
+
reason = `${sorted[0].courier_name} offers the lowest total tariff on this route (৳${sorted[0].total_cost}).`;
|
|
245
|
+
}
|
|
246
|
+
else if (zoneInfo.zone === "inside_dhaka") {
|
|
247
|
+
recommended = "pathao";
|
|
248
|
+
reason = "Lowest base rate and high-density rider pickup within Inside Dhaka.";
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
recommended = "steadfast";
|
|
252
|
+
reason = "Lowest inter-district base tariff and 64-district doorstep COD coverage.";
|
|
253
|
+
}
|
|
254
|
+
const quotes = rawQuotes.map((rq) => ({
|
|
255
|
+
...rq,
|
|
256
|
+
is_recommended: rq.courier === recommended,
|
|
257
|
+
}));
|
|
258
|
+
return {
|
|
259
|
+
success: true,
|
|
260
|
+
zone: zoneInfo.zone,
|
|
261
|
+
zone_title: zoneInfo.zone_title,
|
|
262
|
+
distance_km: zoneInfo.distance_km,
|
|
263
|
+
road_distance_km: zoneInfo.road_distance_km,
|
|
264
|
+
sla_hours: zoneInfo.sla_hours,
|
|
265
|
+
weight_kg: weight,
|
|
266
|
+
cod_amount: cod,
|
|
267
|
+
recommended_courier: recommended,
|
|
268
|
+
recommendation_reason: reason,
|
|
269
|
+
quotes,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
async fallbackAddressParse(req) {
|
|
273
|
+
const thanaInput = req.thana ? String(req.thana) : null;
|
|
274
|
+
const fullQuery = [req.address, req.thana, req.district, "Bangladesh"].filter(Boolean).join(", ");
|
|
275
|
+
const lower = fullQuery.toLowerCase();
|
|
276
|
+
const BD_DISTRICTS = [
|
|
277
|
+
{ match: /chattogram|chittagong|চট্টগ্রাম/, district: "Chattogram", division: "Chattogram Division", lat: 22.3569, lng: 91.7832 },
|
|
278
|
+
{ match: /sylhet|সিলেট/, district: "Sylhet", division: "Sylhet Division", lat: 24.8949, lng: 91.8687 },
|
|
279
|
+
{ match: /rajshahi|রাজশাহী/, district: "Rajshahi", division: "Rajshahi Division", lat: 24.3745, lng: 88.6042 },
|
|
280
|
+
{ match: /khulna|খুলনা/, district: "Khulna", division: "Khulna Division", lat: 22.8456, lng: 89.5403 },
|
|
281
|
+
{ match: /barishal|barisal|বরিশাল/, district: "Barishal", division: "Barishal Division", lat: 22.7010, lng: 90.3535 },
|
|
282
|
+
{ match: /rangpur|রংপুর/, district: "Rangpur", division: "Rangpur Division", lat: 25.7439, lng: 89.2752 },
|
|
283
|
+
{ match: /mymensingh|ময়মনসিংহ/, district: "Mymensingh", division: "Mymensingh Division", lat: 24.7471, lng: 90.4203 },
|
|
284
|
+
{ match: /cumilla|comilla|কুমিল্লা/, district: "Cumilla", division: "Chattogram Division", lat: 23.4607, lng: 91.1809 },
|
|
285
|
+
{ match: /gazipur|গাজীপুর|tongi|টঙ্গী/, district: "Gazipur", division: "Dhaka Division", lat: 23.9999, lng: 90.4203 },
|
|
286
|
+
{ match: /narayanganj|নারায়ণগঞ্জ/, district: "Narayanganj", division: "Dhaka Division", lat: 23.6238, lng: 90.5000 },
|
|
287
|
+
{ match: /savar|সাভার|ashulia|আশুলিয়া/, district: "Dhaka", division: "Dhaka Division", lat: 23.8583, lng: 90.2667 },
|
|
288
|
+
{ match: /keraniganj|কেরানীগঞ্জ|ati bazar|atibazar/, district: "Dhaka", division: "Dhaka Division", lat: 23.7196, lng: 90.3125 },
|
|
289
|
+
{ match: /uttara|উত্তরা/, district: "Dhaka", division: "Dhaka Division", lat: 23.8759, lng: 90.3795 },
|
|
290
|
+
{ match: /mirpur|মিরপুর/, district: "Dhaka", division: "Dhaka Division", lat: 23.8042, lng: 90.3667 },
|
|
291
|
+
{ match: /dhanmondi|ধানমন্ডি/, district: "Dhaka", division: "Dhaka Division", lat: 23.7461, lng: 90.3742 },
|
|
292
|
+
{ match: /gulshan|গুলশান|banani|বনানী/, district: "Dhaka", division: "Dhaka Division", lat: 23.7925, lng: 90.4078 },
|
|
293
|
+
];
|
|
294
|
+
const matched = BD_DISTRICTS.find((d) => d.match.test(lower)) || {
|
|
295
|
+
district: req.district || "Dhaka",
|
|
296
|
+
division: "Dhaka Division",
|
|
297
|
+
lat: 23.7805,
|
|
298
|
+
lng: 90.4078,
|
|
299
|
+
};
|
|
300
|
+
// Never echo thana_input into thana_resolved in fallback mode
|
|
301
|
+
const thanaResolved = null;
|
|
302
|
+
const locType = "APPROXIMATE";
|
|
303
|
+
const qa = this.buildQualityAssessment(req, fullQuery, locType, 55, thanaResolved);
|
|
304
|
+
return {
|
|
305
|
+
success: true,
|
|
306
|
+
formatted_address: fullQuery,
|
|
307
|
+
thana_input: thanaInput,
|
|
308
|
+
thana_resolved: thanaResolved,
|
|
309
|
+
thana: "",
|
|
310
|
+
district: matched.district,
|
|
311
|
+
division: matched.division,
|
|
312
|
+
coordinates: { lat: matched.lat, lng: matched.lng },
|
|
313
|
+
location_type: locType,
|
|
314
|
+
is_deliverable: true,
|
|
315
|
+
confidence_score: qa.confidence,
|
|
316
|
+
match_quality: qa.matchQuality,
|
|
317
|
+
needs_review: true,
|
|
318
|
+
warnings: qa.warnings,
|
|
319
|
+
place_id: `bd_gazetteer_${matched.district.toLowerCase()}`,
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
haversineDistance(lat1, lon1, lat2, lon2) {
|
|
323
|
+
const R = 6371;
|
|
324
|
+
const dLat = ((lat2 - lat1) * Math.PI) / 180;
|
|
325
|
+
const dLon = ((lon2 - lon1) * Math.PI) / 180;
|
|
326
|
+
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
|
327
|
+
Math.cos((lat1 * Math.PI) / 180) *
|
|
328
|
+
Math.cos((lat2 * Math.PI) / 180) *
|
|
329
|
+
Math.sin(dLon / 2) *
|
|
330
|
+
Math.sin(dLon / 2);
|
|
331
|
+
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
|
332
|
+
return Math.round(R * c * 1.25 * 10) / 10;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
@@ -12,5 +12,19 @@ export declare class PaperflyAdapter implements CourierAdapter {
|
|
|
12
12
|
isConfigured(): boolean;
|
|
13
13
|
createParcel(req: ParcelCreateRequest): Promise<ParcelResponse>;
|
|
14
14
|
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
|
15
|
+
/**
|
|
16
|
+
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
|
17
|
+
*/
|
|
15
18
|
getBalance(): Promise<BalanceResponse>;
|
|
19
|
+
/**
|
|
20
|
+
* Authentic Upstream Paperfly Cancellation
|
|
21
|
+
* Endpoint: POST /api/v1/cancel-order
|
|
22
|
+
*/
|
|
23
|
+
cancelParcel(orderId: string, reason?: string): Promise<{
|
|
24
|
+
success: boolean;
|
|
25
|
+
courier: SupportedCourier;
|
|
26
|
+
consignment_id: string;
|
|
27
|
+
message: string;
|
|
28
|
+
raw_response?: any;
|
|
29
|
+
}>;
|
|
16
30
|
}
|