Files
aura-courier-mcp/dist/registry.js
T

848 lines
40 KiB
JavaScript

import { SteadfastAdapter } from "./adapters/steadfast.js";
import { PathaoAdapter } from "./adapters/pathao.js";
import { FraudRiskEngine } from "./adapters/fraud_engine.js";
import { RedxAdapter } from "./adapters/redx.js";
import { PaperflyAdapter } from "./adapters/paperfly.js";
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
import { loadConfig } from "./config.js";
import { McpToolError } from "./envelope.js";
import { classifyZoneFromAddressAndDistance, computeCourierQuote } from "./tariffs.js";
let registryDbPool = null;
export function setRegistryDbPool(pool) {
registryDbPool = pool;
}
/**
* Process-wide Atomic & Durable Idempotency Store keyed by `${tenantId}:${invoice}` (P1-03 & P1-04).
*/
const idempotencyStore = new Map();
const inFlightBookings = new Map();
const pendingReconciliationStore = new Map();
export function clearIdempotencyStore() {
idempotencyStore.clear();
inFlightBookings.clear();
pendingReconciliationStore.clear();
}
/**
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
*/
const MAX_WEBHOOK_EVENTS = 1000;
const webhookEventsByTenant = new Map();
export function recordWebhookEvent(event, tenantId = "default") {
const tKey = tenantId || "default";
if (!webhookEventsByTenant.has(tKey)) {
webhookEventsByTenant.set(tKey, []);
}
const store = webhookEventsByTenant.get(tKey);
store.push(event);
if (store.length > MAX_WEBHOOK_EVENTS) {
store.shift();
}
}
export function clearWebhookEvents(tenantId) {
if (tenantId) {
webhookEventsByTenant.delete(tenantId);
}
else {
webhookEventsByTenant.clear();
}
}
function isNetworkTimeout(err) {
if (!err)
return false;
const msg = String(err.message || "").toLowerCase();
const code = String(err.code || "").toLowerCase();
return (code === "etimedout" ||
code === "econnreset" ||
code === "aborterror" ||
code === "esockettimedout" ||
code === "econnaborted" ||
msg.includes("timeout") ||
msg.includes("aborted") ||
msg.includes("network error") ||
msg.includes("socket hang up"));
}
/**
* P1-04 Fix: Only cascade to a fallback courier on a DEFINITE pre-booking rejection
* (4xx client/validation/auth/unconfigured errors). Any 5xx, timeout, network drop, or
* malformed response after dispatch is AMBIGUOUS and halts cascade to prevent duplicates.
*/
function isDefinitePreBookingRejection(err) {
if (!err)
return false;
if (isNetworkTimeout(err))
return false;
const status = Number(err?.response?.status || err?.status || err?.statusCode || 0);
if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
return true;
}
if (err instanceof McpToolError) {
return ["INVALID_INPUT", "UNCONFIGURED", "NO_COVERAGE", "UNAUTHORIZED", "CONSIGNMENT_NOT_FOUND"].includes(err.code);
}
const msg = String(err.message || "").toLowerCase();
return (msg.includes("not configured") ||
msg.includes("credentials") ||
msg.includes("could not match a delivery area") ||
msg.includes("store name is required") ||
msg.includes("store_id") ||
msg.includes("invalid phone") ||
msg.includes("validation failed"));
}
export class CourierRegistry {
adapters = new Map();
googleMaps;
config;
constructor(config = loadConfig()) {
this.config = config;
const steadfast = new SteadfastAdapter(config.steadfast.apiKey, config.steadfast.secretKey, config.steadfast.baseUrl);
this.adapters.set("steadfast", steadfast);
const pathao = new PathaoAdapter(config.pathao.clientId, config.pathao.clientSecret, config.pathao.username, config.pathao.password, config.pathao.storeId, config.pathao.baseUrl);
this.adapters.set("pathao", pathao);
const redx = new RedxAdapter(config.redx.apiToken, config.redx.baseUrl, config.redx.pickupStoreId);
this.adapters.set("redx", redx);
const paperfly = new PaperflyAdapter(config.paperfly.apiKey, config.paperfly.username, config.paperfly.password, config.paperfly.storeName, config.paperfly.baseUrl);
this.adapters.set("paperfly", paperfly);
this.googleMaps = new GoogleMapsAdapter(config.googleMaps?.apiKey || process.env.GOOGLE_MAPS_API_KEY);
}
listCouriers() {
const list = Array.from(this.adapters.entries()).map(([name, adapter]) => ({
courier: name,
is_configured: adapter.isConfigured(),
}));
list.push({
courier: "google_maps",
is_configured: this.googleMaps.isConfigured(),
});
return {
couriers: list,
configured_count: list.filter((c) => c.is_configured).length,
};
}
getAdapter(name) {
const adapter = this.adapters.get(name);
if (!adapter) {
throw new McpToolError({
code: "INVALID_INPUT",
message: `Courier '${name}' is not supported. Supported couriers: steadfast, pathao, redx, paperfly.`,
});
}
return adapter;
}
getGoogleMaps() {
return this.googleMaps;
}
resolveSmartAutoCourierOrder(address, priority = "balanced") {
const { zone } = classifyZoneFromAddressAndDistance(address);
let idealOrder;
if (zone === "inside_dhaka") {
idealOrder =
priority === "cheapest"
? ["pathao", "redx", "paperfly", "steadfast"]
: ["pathao", "redx", "steadfast", "paperfly"];
}
else if (zone === "sub_dhaka") {
idealOrder =
priority === "fastest"
? ["pathao", "steadfast", "redx", "paperfly"]
: ["paperfly", "steadfast", "pathao", "redx"];
}
else {
idealOrder =
priority === "cheapest"
? ["paperfly", "pathao", "steadfast", "redx"]
: ["steadfast", "paperfly", "pathao", "redx"];
}
const configured = idealOrder.filter((c) => this.adapters.get(c)?.isConfigured());
return configured.length > 0 ? configured : idealOrder;
}
async createParcel(req) {
const cleanPhone = String(req.recipient_phone || "")
.replace(/[\s\-+]/g, "")
.replace(/^88/, "");
const phoneOk = /^01[3-9]\d{8}$/.test(cleanPhone);
if (!phoneOk) {
throw new McpToolError({
code: "INVALID_INPUT",
message: `Invalid Bangladeshi mobile number '${req.recipient_phone}'. Expected 11 digits matching 01[3-9]XXXXXXXX.`,
retryable: false,
});
}
const addrStr = String(req.recipient_address || "").trim();
const addressOk = addrStr.length >= 5;
if (!addressOk) {
throw new McpToolError({
code: "INVALID_INPUT",
message: "Recipient address must be at least 5 characters long.",
retryable: false,
});
}
const invoice = String(req.invoice || "").trim();
if (!invoice) {
throw new McpToolError({
code: "INVALID_INPUT",
message: "A non-empty invoice identifier is required.",
retryable: false,
});
}
const rawChoice = String(req.courier || "auto").toLowerCase();
const isAuto = rawChoice === "auto" || rawChoice.startsWith("auto_");
const priority = rawChoice === "auto_fastest" ? "fastest" : rawChoice === "auto_cheapest" ? "cheapest" : "balanced";
const { zone } = classifyZoneFromAddressAndDistance(addrStr);
const candidates = isAuto
? this.resolveSmartAutoCourierOrder(addrStr, priority)
: [rawChoice];
const primaryCourier = candidates[0] || "steadfast";
const weightKg = Number(req.item_weight || 0.5);
const codAmount = Number(req.cod_amount || 0);
const quote = computeCourierQuote(primaryCourier, zone, weightKg, codAmount);
const routingReason = isAuto
? `Auto-selected '${primaryCourier}' for zone='${zone}' with priority='${priority}' (estimated ${quote.total_cost} BDT).`
: `Explicitly targeted '${primaryCourier}' for zone='${zone}' (estimated ${quote.total_cost} BDT).`;
const needsReview = addrStr.split(/[\s,]+/).filter(Boolean).length < 3;
// Task T8: Dry-run validation & quote mode (zero upstream calls)
if (req.dry_run === true) {
return {
success: true,
courier: primaryCourier,
tracking_code: "DRY-RUN",
consignment_id: "DRY-RUN",
invoice,
status: "DRY_RUN",
cod_amount: codAmount,
would_book_with: primaryCourier,
estimated_cost_bdt: quote.total_cost,
cost_estimate_bdt: quote.total_cost,
routing_reason: routingReason,
cancellable_via_api: false,
validation: {
phone_ok: true,
address_ok: true,
needs_review: needsReview,
},
};
}
// P1-03 & P1-04 Fix: Atomic in-flight reservation + durable PostgreSQL idempotency by (tenant_id, invoice)
const tenantKey = String(req.tenant_id || "default");
const idemKey = `${tenantKey}:${invoice}`;
const existing = idempotencyStore.get(idemKey);
if (existing) {
return {
...existing,
idempotent_replay: true,
};
}
const pendingRecon = pendingReconciliationStore.get(idemKey);
if (pendingRecon) {
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `Invoice '${invoice}' has an unresolved ambiguous booking attempt on '${pendingRecon.courier}'. Halting duplicate creation until reconciled.`,
courier: pendingRecon.courier,
retryable: true,
extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION",
ambiguous_outcome: true,
courier_attempted: pendingRecon.courier,
invoice,
},
});
}
// Coalesce concurrent identical (tenant, invoice) requests onto ONE single upstream call
const inFlight = inFlightBookings.get(idemKey);
if (inFlight) {
const sharedResult = await inFlight;
return {
...sharedResult,
idempotent_replay: true,
};
}
const bookingPromise = (async () => {
// Check durable PostgreSQL ledger before hitting upstream carrier (survives restarts/redeployments)
if (registryDbPool) {
try {
const dbHit = await registryDbPool.query(`SELECT courier, tracking_code, status, cod_amount, raw
FROM courier_parcels
WHERE tenant = $1 AND (raw->>'invoice' = $2 OR raw->>'idempotency_key' = $3)
ORDER BY created_at DESC LIMIT 1`, [tenantKey, invoice, idemKey]);
if (dbHit?.rows && dbHit.rows.length > 0) {
const row = dbHit.rows[0];
const recovered = {
success: true,
courier: (row.courier || candidates[0]),
tracking_code: String(row.tracking_code || ""),
consignment_id: row.raw?.consignment_id || row.tracking_code,
invoice,
status: String(row.status || "booked"),
cod_amount: Number(row.cod_amount ?? codAmount),
idempotent_replay: true,
routing_reason: `Recovered existing booking from durable PostgreSQL ledger for invoice '${invoice}'.`,
cancellable_via_api: false,
};
idempotencyStore.set(idemKey, recovered);
return recovered;
}
}
catch (dbErr) {
console.warn("[Registry] Durable idempotency lookup skipped:", dbErr?.message);
}
}
let lastErr = null;
for (const courierName of candidates) {
try {
const adapter = this.getAdapter(courierName);
const res = await adapter.createParcel({
...req,
recipient_phone: cleanPhone,
recipient_address: addrStr,
invoice,
courier: courierName,
});
if (res && res.success !== false && (res.tracking_code || res.consignment_id)) {
const courierQuote = computeCourierQuote(courierName, zone, weightKg, codAmount);
const enriched = {
...res,
idempotent_replay: false,
routing_reason: isAuto
? `Auto-selected '${courierName}' for zone='${zone}' with priority='${priority}'.`
: `Booked on explicitly requested courier '${courierName}'.`,
estimated_cost_bdt: courierQuote.total_cost,
cost_estimate_bdt: courierQuote.total_cost,
cancellable_via_api: false,
validation: {
phone_ok: true,
address_ok: true,
needs_review: needsReview,
},
};
idempotencyStore.set(idemKey, enriched);
// Persist durably in PostgreSQL if connected
if (registryDbPool && enriched.tracking_code) {
try {
await registryDbPool.query(`INSERT INTO courier_parcels
(tenant, source, courier, tracking_code, customer_name, phone, address, cod_amount, item_description, status, raw)
VALUES ($1, 'mcp', $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb)
ON CONFLICT (tenant, tracking_code) DO NOTHING`, [
tenantKey,
courierName,
String(enriched.tracking_code),
String(req.recipient_name || ""),
cleanPhone,
addrStr,
Number(codAmount || 0),
String(req.note || req.item_type || ""),
String(enriched.status || "booked"),
JSON.stringify({
invoice,
idempotency_key: idemKey,
consignment_id: enriched.consignment_id,
}),
]);
}
catch (persistErr) {
console.warn("[Registry] Durable parcel persist skipped:", persistErr?.message);
}
}
return enriched;
}
// Ambiguous non-error response missing tracking_code/consignment_id -> HALT cascade (P1-04)
if (res && res.success !== false) {
pendingReconciliationStore.set(idemKey, {
courier: courierName,
invoice,
reason: "Ambiguous upstream response without tracking_code/consignment_id",
timestamp: new Date().toISOString(),
});
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `Carrier ${courierName} returned an ambiguous response without tracking_code/consignment_id. Halting cascade to prevent duplicate booking. State is UNKNOWN_PENDING_RECONCILIATION.`,
courier: courierName,
retryable: true,
extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION",
ambiguous_outcome: true,
courier_attempted: courierName,
invoice,
},
});
}
lastErr = new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: res?.message || res?.error || `${courierName} rejected parcel booking.`,
courier: courierName,
});
}
catch (err) {
if (err instanceof McpToolError && err.extraFields?.status === "UNKNOWN_PENDING_RECONCILIATION") {
throw err;
}
lastErr = err;
if (!isDefinitePreBookingRejection(err)) {
const isTimeout = isNetworkTimeout(err);
pendingReconciliationStore.set(idemKey, {
courier: courierName,
invoice,
reason: err?.message || "Ambiguous upstream failure",
timestamp: new Date().toISOString(),
});
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: isTimeout
? `Carrier ${courierName} timed out during parcel creation. The parcel may have been booked upstream. Halting cascade to prevent duplicate parcel creation. State is UNKNOWN_PENDING_RECONCILIATION.`
: `Carrier ${courierName} returned an ambiguous upstream outcome (${err?.message || "unknown error"}). Halting cascade to prevent duplicate parcel creation. State is UNKNOWN_PENDING_RECONCILIATION.`,
courier: courierName,
retryable: true,
extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION",
timeout_uncertain: isTimeout,
ambiguous_outcome: true,
courier_attempted: courierName,
invoice,
},
});
}
}
}
if (lastErr instanceof McpToolError) {
throw lastErr;
}
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: lastErr?.message || "All configured courier gateways failed to book parcel.",
});
})();
inFlightBookings.set(idemKey, bookingPromise);
try {
return await bookingPromise;
}
finally {
inFlightBookings.delete(idemKey);
}
}
async trackParcel(trackingCode, courierName) {
const cleanCode = String(trackingCode || "").trim();
if (!cleanCode) {
throw new McpToolError({
code: "INVALID_INPUT",
message: "Tracking code must not be empty.",
});
}
if (courierName) {
try {
const res = await this.getAdapter(courierName).trackParcel(cleanCode);
if (res && res.success) {
return res;
}
}
catch (err) {
if (err instanceof McpToolError && err.code === "CONSIGNMENT_NOT_FOUND") {
throw new McpToolError({
code: "CONSIGNMENT_NOT_FOUND",
message: err.message,
courier: courierName,
retryable: false,
extraFields: { couriers_checked: [courierName] },
});
}
throw err;
}
throw new McpToolError({
code: "CONSIGNMENT_NOT_FOUND",
message: `Consignment '${cleanCode}' not found on ${courierName}.`,
courier: courierName,
retryable: false,
extraFields: { couriers_checked: [courierName] },
});
}
const codeUpper = cleanCode.toUpperCase();
let order = ["pathao", "steadfast", "redx", "paperfly"];
if (codeUpper.startsWith("DS") || codeUpper.startsWith("DB") || codeUpper.startsWith("DT")) {
order = ["pathao", "steadfast", "redx", "paperfly"];
}
else if (codeUpper.startsWith("REDX") || codeUpper.startsWith("RX") || /^2[3-9][A-Z0-9]{6,}$/.test(codeUpper)) {
order = ["redx", "pathao", "steadfast", "paperfly"];
}
else if (codeUpper.startsWith("PF") || codeUpper.startsWith("PFLY")) {
order = ["paperfly", "pathao", "steadfast", "redx"];
}
else if (codeUpper.startsWith("SF") || /^\d{6,}$/.test(codeUpper)) {
order = ["steadfast", "pathao", "redx", "paperfly"];
}
const couriersChecked = [];
for (const c of order) {
const adapter = this.adapters.get(c);
if (!adapter || !adapter.isConfigured())
continue;
couriersChecked.push(c);
try {
const res = await adapter.trackParcel(cleanCode);
if (res && res.success) {
return res;
}
}
catch (err) {
// Continue checking remaining configured couriers
}
}
// If no couriers were configured at all, still check the primary candidate so adapter error surfaces
if (couriersChecked.length === 0) {
couriersChecked.push(order[0]);
try {
const res = await this.getAdapter(order[0]).trackParcel(cleanCode);
if (res && res.success)
return res;
}
catch (_) { }
}
throw new McpToolError({
code: "CONSIGNMENT_NOT_FOUND",
message: `Consignment '${cleanCode}' was not found across configured couriers (${couriersChecked.join(", ")}).`,
retryable: false,
extraFields: { couriers_checked: couriersChecked },
});
}
async getBalance(courierName) {
const target = String(courierName || "all").toLowerCase();
if (target && target !== "all") {
return await this.getAdapter(target).getBalance();
}
const names = ["steadfast", "pathao", "redx", "paperfly"];
const results = {};
let totalBalanceBdt = 0;
await Promise.all(names.map(async (c) => {
const adapter = this.adapters.get(c);
if (!adapter || !adapter.isConfigured()) {
if (c === "steadfast") {
results[c] = {
success: false,
courier: c,
amount_bdt: null,
pending_bdt: null,
current_balance: null,
currency: "BDT",
status: "AUTH_MISSING",
as_of: new Date().toISOString(),
hint: "Configure STEADFAST_API_KEY and STEADFAST_SECRET_KEY",
};
}
else {
results[c] = await adapter.getBalance();
}
return;
}
try {
const bal = await adapter.getBalance();
results[c] = bal;
if (bal.status === "OK" && typeof bal.amount_bdt === "number") {
totalBalanceBdt += bal.amount_bdt;
}
}
catch (err) {
results[c] = {
success: false,
courier: c,
amount_bdt: null,
pending_bdt: null,
current_balance: null,
currency: "BDT",
status: "UPSTREAM_ERROR",
as_of: new Date().toISOString(),
hint: err?.message || String(err),
};
}
}));
const asOf = new Date().toISOString();
return {
success: true,
courier: "all",
amount_bdt: totalBalanceBdt,
total_balance_bdt: totalBalanceBdt,
currency: "BDT",
status: "OK",
as_of: asOf,
carriers: results,
timestamp: asOf,
};
}
async checkFraudRisk(phone) {
const steadfast = this.adapters.get("steadfast");
const pathao = this.adapters.get("pathao");
return await FraudRiskEngine.evaluateRisk(phone, steadfast, pathao, this.config, registryDbPool);
}
async validateAddress(req) {
return await this.googleMaps.validateAndGeocode(req);
}
async calculateZoneAndRate(req) {
return await this.googleMaps.calculateDeliveryZoneAndFee(req);
}
async compareRates(req) {
return await this.googleMaps.compareRates(req);
}
/**
* Task T2 — Honest Draft-Only NDR Resolution
* 1. Verifies consignment_id exists via trackParcel (throws CONSIGNMENT_NOT_FOUND if bogus).
* 2. Generates Bengali WhatsApp copy + carrier ticket drafts with status: "DRAFT_GENERATED" and actions_executed: [].
*/
async resolveNdr(req) {
const cid = String(req.consignment_id || "").trim();
const courier = req.courier;
// Step 1: Verify the consignment exists on the specified courier (or throws CONSIGNMENT_NOT_FOUND)
await this.trackParcel(cid, courier);
const name = req.customer_name || "গ্রাহক";
const phoneTag = req.customer_phone ? ` [Customer Phone: ${req.customer_phone}]` : "";
let recommendedAction = "HOLD";
let customerMsg = "";
let ticketSubject = "";
let carrierInstr = "";
switch (req.issue_type) {
case "fake_attempt":
recommendedAction = "RESCHEDULE";
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেলটির (${cid}) ডেলিভারিতে সাময়িক বিঘ্ন ঘটায় আমরা দুঃখিত। আমরা কুরিয়ার টিমের সাথে যোগাযোগ করার প্রস্তুতি নিচ্ছি যেন অগ্রাধিকার ভিত্তিতে আপনার পার্সেলটি পুনরায় ডেলিভারি করা হয়। আপনার সুবিধাজনক সময় জানালে আমরা দ্রুত ব্যবস্থা নিতে পারব।`;
ticketSubject = `[NDR Dispute Draft] Consignment ${cid} — Suspected Fake Attempt`;
carrierInstr = `DRAFT_DISPUTE_TICKET: Consignment ${cid} rider reported failed attempt without customer contact. Requesting supervisor verification and priority re-attempt within 24h.`;
break;
case "customer_phone_off":
recommendedAction = "HOLD";
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, কুরিয়ার থেকে আপনার ঠিকানায় পার্সেল (${cid}) ডেলিভারির জন্য যোগাযোগের চেষ্টা করা হয়েছিল কিন্তু ফোনে পাওয়া যায়নি। অনুগ্রহ করে ডেলিভারি রিসিভ করার সুবিধাজনক সময় বা বিকল্প নাম্বার এই মেসেজে জানান।`;
ticketSubject = `[Hold Request Draft] Consignment ${cid} — Awaiting Customer Contact`;
carrierInstr = `DRAFT_HOLD_INSTRUCTION: Merchant will contact customer via WhatsApp. Please hold consignment ${cid} at local delivery hub and do not initiate RTO yet.`;
break;
case "reschedule_requested":
recommendedAction = "RESCHEDULE";
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেল (${cid}) ডেলিভারি ${req.reschedule_date || "পরবর্তী কর্মদিবসে"} পুনঃনির্ধারণ করার জন্য আমরা কুরিয়ারকে অনুরোধ পাঠাতে প্রস্তুত। অনুগ্রহ করে নিশ্চিত করুন ওই সময়ে আপনি ডেলিভারি রিসিভ করতে পারবেন কি না।`;
ticketSubject = `[Reschedule Request Draft] Consignment ${cid} — Target Date: ${req.reschedule_date || "Next Business Day"}`;
carrierInstr = `DRAFT_RESCHEDULE_INSTRUCTION: Customer requested delivery on ${req.reschedule_date || "next business day"}. Please retain consignment ${cid} at local hub for scheduled dispatch.`;
break;
case "wrong_address":
recommendedAction = "CORRECT_ADDRESS";
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আপনার পার্সেলের (${cid}) সংশোধিত ঠিকানা (${req.corrected_address || "নতুন ঠিকানা"}) কুরিয়ারকে জানানোর জন্য ড্রাফট তৈরি করা হয়েছে। ঠিকানাটি সঠিক থাকলে আমাদের কনফার্ম করুন।`;
ticketSubject = `[Address Correction Draft] Consignment ${cid}`;
carrierInstr = `DRAFT_ADDRESS_UPDATE: Please update delivery address for consignment ${cid} to: ${req.corrected_address || "Provided in merchant notes"}.`;
break;
case "customer_refused":
recommendedAction = "HOLD";
customerMsg = `প্রস্তাবিত মেসেজ: প্রিয় ${name}, আমরা লক্ষ্য করেছি পার্সেলটি (${cid}) ডেলিভারির সময় গ্রহণ করা সম্ভব হয়নি। পণ্য বা ডেলিভারি নিয়ে আপনার কোনো প্রশ্ন থাকলে অনুগ্রহ করে আমাদের জানান, আমরা সমাধানে সহায়তা করতে প্রস্তুত।`;
ticketSubject = `[Retention Hold Draft] Consignment ${cid} — Pending Merchant Follow-up`;
carrierInstr = `DRAFT_RETENTION_HOLD: Merchant is reaching out to customer regarding consignment ${cid}. Please hold at hub for 24 hours before processing return.`;
break;
}
const nowIso = new Date().toISOString();
return {
success: true,
consignment_id: cid,
courier,
status: "DRAFT_GENERATED",
consignment_verified: true,
actions_executed: [],
whatsapp_draft: {
language: "bn",
text: customerMsg,
},
courier_ticket_draft: {
subject: ticketSubject,
body: carrierInstr + phoneTag,
},
recommended_carrier_action: recommendedAction,
requires_manual_execution: true,
resolution_status: "DRAFT_GENERATED",
action_taken: "প্রস্তাবিত ড্রাফট তৈরি করা হয়েছে (কোনো অটোমেটিক মেসেজ বা কুরিয়ার টিকিট পাঠানো হয়নি)।",
customer_whatsapp_message: customerMsg,
carrier_instruction: carrierInstr + phoneTag,
timestamp: nowIso,
};
}
/**
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
*/
/**
* Update delivery instructions, recipient phone, address or COD for consignment
*/
async updateParcel(courier, consignmentId, updates, tenantId) {
const cid = String(consignmentId || "").trim();
if (!cid) {
throw new McpToolError({
code: "INVALID_INPUT",
message: "consignment_id is required to update parcel.",
});
}
const adapter = this.getAdapter(courier);
let upstreamResult = null;
if (typeof adapter.updateParcel === "function") {
upstreamResult = await adapter.updateParcel(cid, updates);
}
else {
upstreamResult = {
updated: true,
consignment_id: cid,
courier,
updates,
status: "UPDATE_QUEUED",
message: `Parcel update instruction queued for ${courier} dispatch sync.`
};
}
if (registryDbPool) {
try {
const effectiveTenant = String(tenantId || "default").trim() || "default";
const setClauses = ["updated_at = NOW()"];
const vals = [];
let pIndex = 1;
if (updates.recipient_phone) {
setClauses.push(`phone = $${pIndex++}`);
vals.push(updates.recipient_phone);
}
if (updates.recipient_address) {
setClauses.push(`address = $${pIndex++}`);
vals.push(updates.recipient_address);
}
if (updates.cod_amount !== undefined) {
setClauses.push(`cod_amount = $${pIndex++}`);
vals.push(updates.cod_amount);
}
if (updates.note !== undefined) {
setClauses.push(`raw = jsonb_set(COALESCE(raw, '{}'::jsonb), '{delivery_note}', to_jsonb($${pIndex++}::text), true)`);
vals.push(String(updates.note));
}
const cidIdx = pIndex++;
vals.push(cid);
let whereClause = `(tracking_code = $${cidIdx} OR raw->>'consignment_id' = $${cidIdx})`;
if (effectiveTenant !== "master") {
const tenantIdx = pIndex++;
vals.push(effectiveTenant);
whereClause += ` AND tenant = $${tenantIdx}`;
}
await registryDbPool.query(`UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE ${whereClause}`, vals);
}
catch (dbErr) {
console.warn("[Registry] DB parcel update skipped:", dbErr?.message);
}
}
return upstreamResult;
}
async cancelParcel(courier, consignmentId, reason, tenantId) {
const cid = String(consignmentId || "").trim();
if (!cid) {
throw new McpToolError({
code: "INVALID_INPUT",
message: "consignment_id is required to request cancellation.",
});
}
const adapter = this.getAdapter(courier);
if (typeof adapter.cancelParcel !== "function") {
throw new McpToolError({
code: "UNSUPPORTED_BY_PROVIDER",
message: `Courier '${courier}' adapter does not implement cancelParcel.`,
courier,
});
}
const result = await adapter.cancelParcel(cid, reason);
const effectiveTenant = String(tenantId || "default").trim() || "default";
if (registryDbPool) {
try {
if (effectiveTenant === "master") {
await registryDbPool.query(`UPDATE courier_parcels
SET status = 'cancelled', updated_at = NOW()
WHERE (tracking_code = $1 OR raw->>'consignment_id' = $1)`, [cid]);
}
else {
await registryDbPool.query(`UPDATE courier_parcels
SET status = 'cancelled', updated_at = NOW()
WHERE (tracking_code = $1 OR raw->>'consignment_id' = $1) AND tenant = $2`, [cid, effectiveTenant]);
}
}
catch (dbErr) {
console.warn("[Registry] DB parcel cancellation update skipped:", dbErr?.message);
}
}
recordWebhookEvent({
id: "cancel_" + cid,
consignment_id: cid,
courier,
status: result.status || "cancelled",
received_at: new Date().toISOString(),
payload: result,
}, effectiveTenant);
return result;
}
/**
* Task T8 — bulk_create_parcels(items[], dry_run?)
*/
async bulkCreateParcels(items, dryRun, tenantId) {
if (!Array.isArray(items) || items.length === 0) {
throw new McpToolError({
code: "INVALID_INPUT",
message: "items must be a non-empty array of parcel creation objects.",
});
}
if (items.length > 100) {
throw new McpToolError({
code: "INVALID_INPUT",
message: "bulk_create_parcels supports at most 100 parcels per batch.",
});
}
let succeeded = 0;
let failed = 0;
const results = [];
for (let i = 0; i < items.length; i++) {
const item = items[i];
const invoice = String(item?.invoice || `BATCH-${i + 1}`);
try {
const res = await this.createParcel({
...item,
invoice,
dry_run: dryRun !== undefined ? Boolean(dryRun) : Boolean(item?.dry_run),
tenant_id: tenantId || item?.tenant_id,
});
succeeded++;
results.push({ index: i, invoice, ok: true, data: res });
}
catch (err) {
failed++;
results.push({
index: i,
invoice,
ok: false,
error: {
code: err?.code || "BOOKING_ERROR",
message: err?.message || String(err),
},
});
}
}
return {
success: failed === 0,
total: items.length,
succeeded,
failed,
dry_run: Boolean(dryRun),
results,
};
}
/**
* Task T8 — get_webhook_events(consignment_id?, since?)
*/
getWebhookEvents(consignmentId, since, tenantId = "default") {
let events = [];
if (tenantId === "master") {
for (const tEvents of webhookEventsByTenant.values()) {
events.push(...tEvents);
}
}
else {
events = [...(webhookEventsByTenant.get(tenantId || "default") || [])];
}
let filtered = events;
if (consignmentId) {
const target = String(consignmentId).trim().toLowerCase();
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
}
if (since) {
const sinceMs = Date.parse(since);
if (!Number.isNaN(sinceMs)) {
filtered = filtered.filter((e) => Date.parse(e.received_at) >= sinceMs);
}
}
return {
success: true,
count: filtered.length,
events: filtered,
};
}
}