@carrierllc/mcp 0.13.62 → 0.13.64

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.
@@ -1913,7 +1913,7 @@ function storefrontScreen(input) {
1913
1913
  // package.json
1914
1914
  var package_default = {
1915
1915
  name: "@carrierllc/mcp",
1916
- version: "0.13.62",
1916
+ version: "0.13.64",
1917
1917
  description: "Carrier MCP \u2014 natural-language control of MVNO/eSIM fleets via eSIMVault OCS. Stdio mode for direct integration with Claude Desktop, Cursor, Windsurf, and MCP-compatible clients. Ships the `carrier` CLI (plugin install + white-label eSIM storefront scaffold).",
1918
1918
  license: "MIT",
1919
1919
  author: "Carrier (Lifecycle Innovations Limited)",
@@ -2065,19 +2065,19 @@ function nestsSubscriberId(method) {
2065
2065
  }
2066
2066
  function nestSubscriberIdParam(params) {
2067
2067
  if (!params || typeof params !== "object" || Array.isArray(params)) return params;
2068
- const record = params;
2069
- if (typeof record["subscriber"] !== "string") return params;
2070
- return { ...record, subscriber: { iccid: record["subscriber"] } };
2068
+ const record2 = params;
2069
+ if (typeof record2["subscriber"] !== "string") return params;
2070
+ return { ...record2, subscriber: { iccid: record2["subscriber"] } };
2071
2071
  }
2072
2072
  function packageStatusConfirmation(params) {
2073
2073
  const confirmation = { updated: true };
2074
2074
  if (!params || typeof params !== "object" || Array.isArray(params)) return confirmation;
2075
- const record = params;
2076
- const id = record["subsPrepaidPackageId"];
2075
+ const record2 = params;
2076
+ const id = record2["subsPrepaidPackageId"];
2077
2077
  if (typeof id === "number" && Number.isFinite(id)) confirmation.subsPrepaidPackageId = id;
2078
- if (typeof record["active"] === "boolean") {
2079
- confirmation.active = record["active"];
2080
- confirmation.status = record["active"] ? "ACTIVE" : "INACTIVE";
2078
+ if (typeof record2["active"] === "boolean") {
2079
+ confirmation.active = record2["active"];
2080
+ confirmation.status = record2["active"] ? "ACTIVE" : "INACTIVE";
2081
2081
  }
2082
2082
  return confirmation;
2083
2083
  }
@@ -2106,9 +2106,9 @@ function usageOverPeriodParams(iccid, start, end) {
2106
2106
  const period = clampUsagePeriod(start, end);
2107
2107
  return { subscriber: { iccid }, period };
2108
2108
  }
2109
- function imsiFromSubscriberRecord(record) {
2110
- if (!record || typeof record !== "object") return void 0;
2111
- const rec = record;
2109
+ function imsiFromSubscriberRecord(record2) {
2110
+ if (!record2 || typeof record2 !== "object") return void 0;
2111
+ const rec = record2;
2112
2112
  const inner = rec.getSingleSubscriber && typeof rec.getSingleSubscriber === "object" ? rec.getSingleSubscriber : rec;
2113
2113
  const direct = inner.imsi;
2114
2114
  if (typeof direct === "string" && direct.length > 0) return direct;
@@ -3422,12 +3422,12 @@ function applyParamRenames(method, params) {
3422
3422
  if (!renames || !params || typeof params !== "object" || Array.isArray(params)) {
3423
3423
  return params;
3424
3424
  }
3425
- const record = params;
3425
+ const record2 = params;
3426
3426
  let out;
3427
3427
  for (const [from, to] of Object.entries(renames)) {
3428
- if (!Object.prototype.hasOwnProperty.call(record, from)) continue;
3429
- out ??= { ...record };
3430
- if (!Object.prototype.hasOwnProperty.call(record, to)) out[to] = record[from];
3428
+ if (!Object.prototype.hasOwnProperty.call(record2, from)) continue;
3429
+ out ??= { ...record2 };
3430
+ if (!Object.prototype.hasOwnProperty.call(record2, to)) out[to] = record2[from];
3431
3431
  delete out[from];
3432
3432
  }
3433
3433
  return out ?? params;
@@ -3885,6 +3885,111 @@ var OcsClient = class {
3885
3885
  }
3886
3886
  };
3887
3887
 
3888
+ // ../../packages/ocs-client/dist/chunk-QYXJUFOW.js
3889
+ function buildListSubscriberParams(args) {
3890
+ const params = {};
3891
+ if (args.imsi) params.imsiPrefix = args.imsi;
3892
+ if (args.iccid) params.iccidPrefix = args.iccid;
3893
+ if (args.activationCode) params.activationCode = args.activationCode;
3894
+ if (args.accountId !== void 0) params.accountId = args.accountId;
3895
+ if (args.msisdn) params.msisdnPrefix = args.msisdn;
3896
+ return params;
3897
+ }
3898
+ function periodFrom(entry) {
3899
+ if (!entry || typeof entry !== "object") return null;
3900
+ const rec = entry;
3901
+ const name = rec.status;
3902
+ if (typeof name !== "string" || name.length === 0) return null;
3903
+ const endDate = rec.endDate;
3904
+ const open = endDate === void 0 || endDate === null || endDate === "";
3905
+ return { name, start: typeof rec.startDate === "string" ? rec.startDate : "", open };
3906
+ }
3907
+ function currentSubscriberStatus(raw) {
3908
+ if (typeof raw === "string" && raw.length > 0) return raw;
3909
+ if (!Array.isArray(raw)) return void 0;
3910
+ const periods = raw.map(periodFrom).filter((period) => period !== null);
3911
+ const open = periods.find((period) => period.open);
3912
+ if (open) return open.name;
3913
+ const latest = [...periods].sort((a, b) => b.start.localeCompare(a.start))[0];
3914
+ return latest?.name;
3915
+ }
3916
+ function isActiveStatus(status) {
3917
+ if (typeof status !== "string") return false;
3918
+ const name = status.trim().toLowerCase();
3919
+ return name === "active" || name === "1";
3920
+ }
3921
+ function subscriberStatusVerdict(status) {
3922
+ if (status === "") {
3923
+ return { severity: "info", finding: "OCS status could not be read from the subscriber record" };
3924
+ }
3925
+ if (!isActiveStatus(status)) {
3926
+ return {
3927
+ severity: "critical",
3928
+ finding: `OCS status is ${status} (not ACTIVE)`,
3929
+ action: "Reactivate subscriber via modify_subscriber_status"
3930
+ };
3931
+ }
3932
+ return { severity: "healthy" };
3933
+ }
3934
+ function extractSubscriberStatus(row) {
3935
+ if (row === null || typeof row !== "object") return null;
3936
+ const rec = row;
3937
+ const current = rec.currentStatus;
3938
+ if (typeof current === "string" && current.length > 0) return current;
3939
+ return currentSubscriberStatus(rec.status) ?? null;
3940
+ }
3941
+ function subscriberListEnvelope(raw) {
3942
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
3943
+ const envelope = raw;
3944
+ return ["subscriberList", "subscribers", "subscriber"].some((key) => Array.isArray(envelope[key])) ? envelope : null;
3945
+ }
3946
+ function unwrapSubscriberList(raw) {
3947
+ if (Array.isArray(raw)) return { rows: raw, envelope: null };
3948
+ if (raw !== null && typeof raw === "object") {
3949
+ const obj = raw;
3950
+ if (Array.isArray(obj.subscriberList)) {
3951
+ return { rows: obj.subscriberList, envelope: obj };
3952
+ }
3953
+ }
3954
+ return { rows: null, envelope: null };
3955
+ }
3956
+ function rewrapSubscriberList(raw, envelope, rows, filtered, matched) {
3957
+ if (rows === null || filtered === null) return raw;
3958
+ const total = matched ?? filtered.length;
3959
+ const dropped = total - filtered.length;
3960
+ if (envelope === null) return filtered;
3961
+ const out = {
3962
+ ...envelope,
3963
+ subscriberList: filtered,
3964
+ nbFound: total,
3965
+ hasMore: filtered.length < total
3966
+ };
3967
+ if (dropped > 0) {
3968
+ out.truncated = true;
3969
+ out.note = `${dropped} of ${total} matching subscribers omitted by offset/limit. Narrow with \`status\`, \`accountId\` or \`iccid\`, or page with \`offset\`.`;
3970
+ }
3971
+ return out;
3972
+ }
3973
+ function applySubscriberFilters(raw, args) {
3974
+ const { rows, envelope } = unwrapSubscriberList(raw);
3975
+ let filtered = rows;
3976
+ if (filtered && args.status) {
3977
+ const wanted = String(args.status).trim().toLowerCase();
3978
+ filtered = filtered.filter((row) => {
3979
+ const status = extractSubscriberStatus(row);
3980
+ return status !== null && status.toLowerCase() === wanted;
3981
+ });
3982
+ }
3983
+ const matched = filtered?.length;
3984
+ if (filtered && typeof args.offset === "number" && args.offset > 0) {
3985
+ filtered = filtered.slice(args.offset);
3986
+ }
3987
+ if (filtered && typeof args.limit === "number" && args.limit >= 0) {
3988
+ filtered = filtered.slice(0, args.limit);
3989
+ }
3990
+ return rewrapSubscriberList(raw, envelope, rows, filtered, matched);
3991
+ }
3992
+
3888
3993
  // ../../packages/ocs-spec/src/mcc-iso.ts
3889
3994
  var MCC_TO_ISO = {
3890
3995
  // Europe
@@ -4381,80 +4486,53 @@ function mccToIso(mcc) {
4381
4486
  return MCC_TO_ISO[n] ?? null;
4382
4487
  }
4383
4488
 
4384
- // ../../packages/ocs-client/dist/index.js
4385
- function buildListSubscriberParams(args) {
4386
- const params = {};
4387
- if (args.imsi) params.imsiPrefix = args.imsi;
4388
- if (args.iccid) params.iccidPrefix = args.iccid;
4389
- if (args.activationCode) params.activationCode = args.activationCode;
4390
- if (args.accountId !== void 0) params.accountId = args.accountId;
4391
- if (args.msisdn) params.msisdnPrefix = args.msisdn;
4392
- return params;
4393
- }
4394
- function extractSubscriberStatus(row) {
4395
- if (row === null || typeof row !== "object") return null;
4396
- const raw = row.status;
4397
- if (typeof raw === "string" && raw.length > 0) return raw;
4398
- if (!Array.isArray(raw)) return null;
4399
- let fallback = null;
4400
- for (const entry of raw) {
4401
- if (!entry || typeof entry !== "object") continue;
4402
- const rec = entry;
4403
- const name = rec.status;
4404
- if (typeof name !== "string" || name.length === 0) continue;
4405
- const endDate = rec.endDate;
4406
- const open = endDate === void 0 || endDate === null || endDate === "";
4407
- if (open) return name;
4408
- if (fallback === null) fallback = name;
4489
+ // ../../packages/ocs-client/dist/chunk-XAYYEDFR.js
4490
+ var OCS_LIST_KEYS = {
4491
+ subscribers: ["subscriberList"],
4492
+ templates: ["template", "prepaidPackageTemplate"],
4493
+ zones: ["listDetailedLocationZone", "locationZone", "zone", "zones"],
4494
+ resellers: ["reseller"],
4495
+ packages: ["prepaidPackage", "package", "packages"]
4496
+ };
4497
+ function ocsArray(data, keys) {
4498
+ if (Array.isArray(data)) return data;
4499
+ if (data === null || typeof data !== "object") return [];
4500
+ const candidates = typeof keys === "string" ? OCS_LIST_KEYS[keys] : keys;
4501
+ const obj = data;
4502
+ for (const key of candidates) {
4503
+ const v = obj[key];
4504
+ if (Array.isArray(v)) return v;
4409
4505
  }
4410
- return fallback;
4506
+ return [];
4411
4507
  }
4412
- function unwrapSubscriberList(raw) {
4413
- if (Array.isArray(raw)) return { rows: raw, envelope: null };
4414
- if (raw !== null && typeof raw === "object") {
4415
- const obj = raw;
4416
- if (Array.isArray(obj.subscriberList)) {
4417
- return { rows: obj.subscriberList, envelope: obj };
4508
+ function subscriberIccid(row) {
4509
+ if (row === null || typeof row !== "object") return "";
4510
+ const r = row;
4511
+ const imsiList = r.imsiList;
4512
+ if (Array.isArray(imsiList)) {
4513
+ for (const entry of imsiList) {
4514
+ if (entry && typeof entry === "object") {
4515
+ const v = entry.iccid;
4516
+ if (typeof v === "string" && v.length > 0) return v;
4517
+ if (typeof v === "number") return String(v);
4518
+ }
4418
4519
  }
4419
4520
  }
4420
- return { rows: null, envelope: null };
4421
- }
4422
- function rewrapSubscriberList(raw, envelope, rows, filtered, matched) {
4423
- if (rows === null || filtered === null) return raw;
4424
- const total = matched ?? filtered.length;
4425
- const dropped = total - filtered.length;
4426
- if (envelope === null) return filtered;
4427
- const out = {
4428
- ...envelope,
4429
- subscriberList: filtered,
4430
- nbFound: total,
4431
- hasMore: filtered.length < total
4432
- };
4433
- if (dropped > 0) {
4434
- out.truncated = true;
4435
- out.note = `${dropped} of ${total} matching subscribers omitted by offset/limit. Narrow with \`status\`, \`accountId\` or \`iccid\`, or page with \`offset\`.`;
4436
- }
4437
- return out;
4438
- }
4439
- function applySubscriberFilters(raw, args) {
4440
- const { rows, envelope } = unwrapSubscriberList(raw);
4441
- let filtered = rows;
4442
- if (filtered && args.status) {
4443
- const wanted = String(args.status).trim().toLowerCase();
4444
- filtered = filtered.filter((row) => {
4445
- const status = extractSubscriberStatus(row);
4446
- return status !== null && status.toLowerCase() === wanted;
4447
- });
4448
- }
4449
- const matched = filtered?.length;
4450
- if (filtered && typeof args.offset === "number" && args.offset > 0) {
4451
- filtered = filtered.slice(args.offset);
4521
+ for (const key of ["iccid", "ICCID"]) {
4522
+ const v = r[key];
4523
+ if (typeof v === "string" && v.length > 0) return v;
4524
+ if (typeof v === "number") return String(v);
4452
4525
  }
4453
- if (filtered && typeof args.limit === "number" && args.limit >= 0) {
4454
- filtered = filtered.slice(0, args.limit);
4526
+ const sim = r.sim;
4527
+ if (sim && typeof sim === "object") {
4528
+ const v = sim.iccid;
4529
+ if (typeof v === "string" && v.length > 0) return v;
4530
+ if (typeof v === "number") return String(v);
4455
4531
  }
4456
- return rewrapSubscriberList(raw, envelope, rows, filtered, matched);
4532
+ return "";
4457
4533
  }
4534
+
4535
+ // ../../packages/ocs-client/dist/index.js
4458
4536
  var OCS_SUBSCRIBER_SEARCH_KEYS = [
4459
4537
  "accountId",
4460
4538
  "iccid",
@@ -4603,50 +4681,6 @@ var ROUTER_RULES = `Rules:
4603
4681
  7. A tool answers the question only if its description says it does. Do not infer capability from the tool's NAME: several names share words with unrelated questions, and picking on the name alone has produced confidently wrong answers.
4604
4682
  8. Read the "Do NOT use this to \u2026" steers in a description as hard exclusions. They exist because that tool is the common wrong answer for a neighbouring question, and they name the tool to use instead.
4605
4683
  9. Prefer carrier_clarify over a tool that would return real data about a different question. Answering "which subscribers erode margin" when the user asked "what do my users' megabytes cost in total" is worse than admitting the gap, because the output looks like an answer.`;
4606
- var OCS_LIST_KEYS = {
4607
- subscribers: ["subscriberList"],
4608
- templates: ["template", "prepaidPackageTemplate"],
4609
- zones: ["listDetailedLocationZone", "locationZone", "zone", "zones"],
4610
- resellers: ["reseller"],
4611
- packages: ["prepaidPackage", "package", "packages"]
4612
- };
4613
- function ocsArray(data, keys) {
4614
- if (Array.isArray(data)) return data;
4615
- if (data === null || typeof data !== "object") return [];
4616
- const candidates = typeof keys === "string" ? OCS_LIST_KEYS[keys] : keys;
4617
- const obj = data;
4618
- for (const key of candidates) {
4619
- const v = obj[key];
4620
- if (Array.isArray(v)) return v;
4621
- }
4622
- return [];
4623
- }
4624
- function subscriberIccid(row) {
4625
- if (row === null || typeof row !== "object") return "";
4626
- const r = row;
4627
- const imsiList = r.imsiList;
4628
- if (Array.isArray(imsiList)) {
4629
- for (const entry of imsiList) {
4630
- if (entry && typeof entry === "object") {
4631
- const v = entry.iccid;
4632
- if (typeof v === "string" && v.length > 0) return v;
4633
- if (typeof v === "number") return String(v);
4634
- }
4635
- }
4636
- }
4637
- for (const key of ["iccid", "ICCID"]) {
4638
- const v = r[key];
4639
- if (typeof v === "string" && v.length > 0) return v;
4640
- if (typeof v === "number") return String(v);
4641
- }
4642
- const sim = r.sim;
4643
- if (sim && typeof sim === "object") {
4644
- const v = sim.iccid;
4645
- if (typeof v === "string" && v.length > 0) return v;
4646
- if (typeof v === "number") return String(v);
4647
- }
4648
- return "";
4649
- }
4650
4684
  var FACET_TALLY_MAX = 25;
4651
4685
  var OCS_LIST_FACETS = {
4652
4686
  templates: [
@@ -4808,7 +4842,7 @@ function formatBytes(bytes) {
4808
4842
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
4809
4843
  }
4810
4844
  function isActiveSubscriber(row) {
4811
- return (extractSubscriberStatus(row) ?? "").toUpperCase() === "ACTIVE";
4845
+ return isActiveStatus(extractSubscriberStatus(row));
4812
4846
  }
4813
4847
  function filterActiveSubscribers(rows) {
4814
4848
  return rows.filter((row) => isActiveSubscriber(row));
@@ -4826,6 +4860,305 @@ function extractResellerBalance(raw) {
4826
4860
  const parsed = Number(value);
4827
4861
  return Number.isFinite(parsed) ? parsed : null;
4828
4862
  }
4863
+ function validDate(value) {
4864
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(`${value}T00:00:00Z`)) && (/* @__PURE__ */ new Date(`${value}T00:00:00Z`)).toISOString().slice(0, 10) === value;
4865
+ }
4866
+ function regionalArpuPeriod(start, end) {
4867
+ if (start !== void 0 && !validDate(start) || end !== void 0 && !validDate(end)) {
4868
+ throw new Error("start and end must be valid YYYY-MM-DD dates");
4869
+ }
4870
+ const finish = end ?? lastNDaysPeriod().end;
4871
+ const begin = start ?? lastNDaysPeriod(7, /* @__PURE__ */ new Date(`${finish}T00:00:00Z`)).start;
4872
+ if (begin > finish) throw new Error("start must be on or before end");
4873
+ return clampUsagePeriod(begin, finish);
4874
+ }
4875
+ function record(value) {
4876
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
4877
+ }
4878
+ function charge(value) {
4879
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
4880
+ }
4881
+ function addCost(total, value) {
4882
+ if (total === null || value === null) return null;
4883
+ const sum = total + value;
4884
+ return Number.isFinite(sum) ? sum : null;
4885
+ }
4886
+ var COUNTRY_CODES = /* @__PURE__ */ new Set([
4887
+ ...Object.values(MCC_TO_ISO).filter((code) => code !== "XX"),
4888
+ ...`AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN
4889
+ BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ
4890
+ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL
4891
+ GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM
4892
+ JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME
4893
+ MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP
4894
+ NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD
4895
+ SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO
4896
+ TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW`.split(/\s+/)
4897
+ ]);
4898
+ function countryFor(row) {
4899
+ const alpha2 = typeof row.countryAlpha2 === "string" ? row.countryAlpha2.trim().toUpperCase() : "";
4900
+ if (COUNTRY_CODES.has(alpha2)) return alpha2;
4901
+ const mapped = typeof row.mcc === "number" || typeof row.mcc === "string" ? mccToIso(row.mcc) : null;
4902
+ return mapped === "XX" ? null : mapped;
4903
+ }
4904
+ function ratedRows(data) {
4905
+ const root = record(data);
4906
+ if (!root) return [];
4907
+ const usages = Array.isArray(root.usages) ? root.usages : [root];
4908
+ const rows = [];
4909
+ for (const usage of usages) {
4910
+ const usageRecord2 = record(usage);
4911
+ if (!usageRecord2) {
4912
+ rows.push(null);
4913
+ continue;
4914
+ }
4915
+ const periods = usageRecord2.subsPeriodUsages;
4916
+ if (periods === void 0) continue;
4917
+ if (!Array.isArray(periods)) {
4918
+ rows.push(null);
4919
+ continue;
4920
+ }
4921
+ for (const period of periods) {
4922
+ const daily = record(period)?.subsDailyUsages;
4923
+ if (Array.isArray(daily)) rows.push(...daily.map(record));
4924
+ else rows.push(null);
4925
+ }
4926
+ }
4927
+ return rows;
4928
+ }
4929
+ function regionalArpu(reads, options) {
4930
+ const bySubscriber = /* @__PURE__ */ new Map();
4931
+ for (const read of reads) {
4932
+ const previous = bySubscriber.get(read.subscriber) ?? [];
4933
+ previous.push(read);
4934
+ bySubscriber.set(read.subscriber, previous);
4935
+ }
4936
+ const groups = /* @__PURE__ */ new Map();
4937
+ const measured = /* @__PURE__ */ new Set();
4938
+ const seen = /* @__PURE__ */ new Set();
4939
+ let failed = 0;
4940
+ let missingCharge = 0;
4941
+ let missingCountry = 0;
4942
+ let missingCurrency = 0;
4943
+ let duplicates = 0;
4944
+ for (const [subscriber, subscriberReads] of bySubscriber) {
4945
+ const successful = subscriberReads.filter((read) => !read.error && record(read.data));
4946
+ if (successful.length === 0) {
4947
+ failed++;
4948
+ continue;
4949
+ }
4950
+ for (const read of successful) {
4951
+ for (const row of ratedRows(read.data)) {
4952
+ if (!row) {
4953
+ missingCharge++;
4954
+ continue;
4955
+ }
4956
+ const timestamp = typeof row.usageDateUtc === "string" ? Date.parse(row.usageDateUtc) : NaN;
4957
+ if (!validDate(typeof row.usageDateUtc === "string" ? row.usageDateUtc.slice(0, 10) : "") || !Number.isFinite(timestamp)) {
4958
+ missingCharge++;
4959
+ continue;
4960
+ }
4961
+ const date = new Date(timestamp).toISOString().slice(0, 10);
4962
+ if (date < options.period.start || date > options.period.end) continue;
4963
+ const identity = JSON.stringify([subscriber, Object.keys(row).sort().map((key2) => [key2, row[key2]])]);
4964
+ if (seen.has(identity)) {
4965
+ duplicates++;
4966
+ continue;
4967
+ }
4968
+ seen.add(identity);
4969
+ const subscriberCost = charge(row.subscriberCost);
4970
+ const country = countryFor(row);
4971
+ const currency = row.resellerCurrencyId;
4972
+ const validCurrency = typeof currency === "number" && Number.isSafeInteger(currency) && currency > 0;
4973
+ const rate = row.resellerConvertRate;
4974
+ const validRate = rate == null || typeof rate === "number" && Number.isFinite(rate) && rate > 0;
4975
+ if (subscriberCost === null) missingCharge++;
4976
+ if (!country) missingCountry++;
4977
+ if (!validCurrency || !validRate) missingCurrency++;
4978
+ if (subscriberCost === null || !country || !validCurrency || !validRate) continue;
4979
+ const conversionRate = typeof rate === "number" ? rate : null;
4980
+ const key = JSON.stringify([country, currency, conversionRate]);
4981
+ let group = groups.get(key);
4982
+ const nextCharge = (group?.subscriber_cost ?? 0) + subscriberCost;
4983
+ if (!Number.isFinite(nextCharge)) {
4984
+ missingCharge++;
4985
+ continue;
4986
+ }
4987
+ if (!group) {
4988
+ group = {
4989
+ country,
4990
+ currency_id: currency,
4991
+ conversion_rate: conversionRate,
4992
+ subscriber_count: 0,
4993
+ subscriber_cost: 0,
4994
+ cost: 0,
4995
+ reseller_cost: 0,
4996
+ arpu: 0,
4997
+ subscribers: /* @__PURE__ */ new Set()
4998
+ };
4999
+ groups.set(key, group);
5000
+ }
5001
+ group.subscribers.add(subscriber);
5002
+ measured.add(subscriber);
5003
+ group.subscriber_cost = nextCharge;
5004
+ const sourceCost = charge(row.cost);
5005
+ const resellerCost = charge(row.resellerCost);
5006
+ group.cost = addCost(group.cost, sourceCost);
5007
+ group.reseller_cost = addCost(group.reseller_cost, resellerCost);
5008
+ }
5009
+ }
5010
+ }
5011
+ const regions = [...groups.values()].map(({ subscribers, ...group }) => ({
5012
+ ...group,
5013
+ subscriber_count: subscribers.size,
5014
+ arpu: group.subscriber_cost / subscribers.size
5015
+ })).sort(
5016
+ (a, b) => a.country.localeCompare(b.country) || a.currency_id - b.currency_id || (a.conversion_rate ?? 0) - (b.conversion_rate ?? 0)
5017
+ );
5018
+ const sampled = bySubscriber.size;
5019
+ const total = Math.max(options.total_subscribers, sampled);
5020
+ const truncated = Boolean(options.truncated) || sampled < total;
5021
+ const incomplete = truncated || failed > 0 || measured.size < sampled || missingCharge > 0 || missingCountry > 0 || missingCurrency > 0;
5022
+ const status = regions.length === 0 ? "unavailable" : incomplete ? "partial" : "computed";
5023
+ const note = [
5024
+ "Period ARPU = explicit subscriberCost / distinct measured subscribers in each country/currency/rate group.",
5025
+ `Measured ${measured.size} of ${sampled} sampled subscribers (${total} listed).`,
5026
+ `${failed} failed reads; ${missingCharge} missing or invalid charge/date records; ${missingCountry} missing-country records; ${missingCurrency} missing-currency records; ${duplicates} duplicate records excluded.`,
5027
+ truncated ? "Subscriber coverage is truncated." : "",
5028
+ regions.length === 0 ? "No attributable subscriber charges are available for this period." : "",
5029
+ "Source cost and resellerCost cover included measured rows separately; currencies and conversion rates are never combined or converted."
5030
+ ].filter(Boolean).join(" ");
5031
+ return {
5032
+ status,
5033
+ period: options.period,
5034
+ regions,
5035
+ total_subscribers: total,
5036
+ sampled_subscribers: sampled,
5037
+ failed_subscribers: failed,
5038
+ missing_charge_records: missingCharge,
5039
+ missing_country_records: missingCountry,
5040
+ missing_currency_records: missingCurrency,
5041
+ duplicate_records: duplicates,
5042
+ truncated,
5043
+ note
5044
+ };
5045
+ }
5046
+ function renderRegionalArpu(report) {
5047
+ const lines = [
5048
+ `## ARPU by region (${report.status})`,
5049
+ `Period: ${report.period.start} to ${report.period.end}`,
5050
+ report.note
5051
+ ];
5052
+ if (report.regions.length > 0) {
5053
+ lines.push(
5054
+ "| Country | Currency ID | Conversion rate | Measured subscribers | Subscriber charges | Source cost | Reseller cost | ARPU |",
5055
+ "|---------|-------------|-----------------|----------------------|--------------------|-------------|---------------|------|"
5056
+ );
5057
+ for (const row of report.regions) {
5058
+ lines.push(`| ${row.country} | ${row.currency_id} | ${row.conversion_rate ?? "Unknown"} | ${row.subscriber_count} | ${row.subscriber_cost.toFixed(2)} | ${row.cost?.toFixed(2) ?? "Unknown"} | ${row.reseller_cost?.toFixed(2) ?? "Unknown"} | ${row.arpu.toFixed(2)} |`);
5059
+ }
5060
+ }
5061
+ return lines.join("\n");
5062
+ }
5063
+ function amount(value) {
5064
+ if (typeof value !== "number" && (typeof value !== "string" || value.trim() === "")) return null;
5065
+ const parsed = Number(value);
5066
+ return Number.isFinite(parsed) ? parsed : null;
5067
+ }
5068
+ function nativeCurrency(row) {
5069
+ const id = row.currencyId ?? row.resellerCurrencyId;
5070
+ if (typeof id === "number" && Number.isSafeInteger(id) && id > 0) return `ID ${id}`;
5071
+ const code = typeof row.currency === "string" ? row.currency.trim().toUpperCase() : "";
5072
+ return /^[A-Z]{3}$/.test(code) ? code : null;
5073
+ }
5074
+ function marketingSnapshot(subscriber, location) {
5075
+ const loc = record(location);
5076
+ const network = record(loc?.networkInfo);
5077
+ const mcc = network?.lastMcc;
5078
+ const rawCountry = loc?.countryAlpha2 ?? loc?.countryCode ?? loc?.country ?? (typeof mcc === "number" || typeof mcc === "string" ? mccToIso(mcc) : null);
5079
+ const country = typeof rawCountry === "string" && rawCountry.trim() && !["XX", "ZZ", "UNKNOWN"].includes(rawCountry.trim().toUpperCase()) ? rawCountry.trim().replace(/[|\r\n]/g, " ") : "Unknown";
5080
+ const balance = loc && "balance" in loc ? loc.balance : subscriber.balance;
5081
+ return { country, balance: amount(balance), currency: (loc && nativeCurrency(loc)) ?? nativeCurrency(subscriber) };
5082
+ }
5083
+ function renderMarketingContext(snapshots, sampled, templates) {
5084
+ const lines = [
5085
+ `## Fleet Size: ${sampled} subscribers sampled`,
5086
+ "## Subscriber Concentration by Country",
5087
+ `Current-location context for ${snapshots.length} of ${sampled} sampled subscribers. Remaining balances are current account values; historical ARPU uses only rated subscriber charges.`
5088
+ ];
5089
+ const groups = /* @__PURE__ */ new Map();
5090
+ const countries = /* @__PURE__ */ new Map();
5091
+ for (const snapshot of snapshots) {
5092
+ const key = JSON.stringify([snapshot.country, snapshot.currency]);
5093
+ const group = groups.get(key) ?? { country: snapshot.country, currency: snapshot.currency, count: 0, balance: 0 };
5094
+ group.count++;
5095
+ group.balance = addCost(group.balance, snapshot.balance);
5096
+ groups.set(key, group);
5097
+ if (snapshot.country !== "Unknown") countries.set(snapshot.country, (countries.get(snapshot.country) ?? 0) + 1);
5098
+ }
5099
+ const sorted = [...groups.values()].sort(
5100
+ (a, b) => b.count - a.count || a.country.localeCompare(b.country) || (a.currency ?? "").localeCompare(b.currency ?? "")
5101
+ );
5102
+ if (sorted.length > 0) {
5103
+ lines.push(
5104
+ "| Current country | Native currency | Subscribers | % of context sample | Avg remaining balance |",
5105
+ "|-----------------|-----------------|-------------|---------------------|-----------------------|"
5106
+ );
5107
+ for (const group of sorted) {
5108
+ const average = group.currency !== null && group.balance !== null ? (group.balance / group.count).toFixed(2) : "Unknown";
5109
+ lines.push(`| ${group.country} | ${group.currency ?? "Unknown"} | ${group.count} | ${(group.count / snapshots.length * 100).toFixed(1)}% | ${average} |`);
5110
+ }
5111
+ } else {
5112
+ lines.push("Current location and remaining-balance context is unavailable.");
5113
+ }
5114
+ lines.push("\n## Market Insights");
5115
+ const ranked = [...countries].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
5116
+ const top = ranked[0];
5117
+ if (top) {
5118
+ lines.push(`- **Largest current market**: ${top[0]} (${top[1]} subscribers in this context sample)`);
5119
+ if (top[1] > snapshots.length / 2) lines.push("- More than 50% of the current context sample is concentrated in one country.");
5120
+ const balances = sorted.filter((group) => group.currency !== null && group.balance !== null && group.count >= 3);
5121
+ if (balances.length > 0) {
5122
+ lines.push("\n### Current remaining balances by market");
5123
+ for (const group of balances) {
5124
+ lines.push(`- ${group.country}, ${group.currency}: average remaining balance ${(group.balance / group.count).toFixed(2)} (${group.count} subscribers)`);
5125
+ }
5126
+ }
5127
+ const emerging = ranked.filter(([, count]) => count <= 3);
5128
+ if (emerging.length > 0) {
5129
+ lines.push("\n### Emerging Markets (early traction, 1-3 subscribers)");
5130
+ for (const [country, count] of emerging) lines.push(`- ${country}: ${count} subscriber(s); review before targeted campaigns.`);
5131
+ }
5132
+ } else {
5133
+ lines.push("No current country could be established for market insights.");
5134
+ }
5135
+ lines.push("\n### Pricing Range");
5136
+ const prices = /* @__PURE__ */ new Map();
5137
+ for (const template of templates) {
5138
+ const price = amount(template.price ?? template.cost);
5139
+ if (price === null || price < 0) continue;
5140
+ const currency = nativeCurrency(template);
5141
+ const values = prices.get(currency) ?? [];
5142
+ values.push(price);
5143
+ prices.set(currency, values);
5144
+ }
5145
+ if (prices.size === 0) lines.push("Template pricing is unavailable.");
5146
+ for (const [currency, values] of prices) {
5147
+ const sum = values.reduce((total, value) => total + value, 0);
5148
+ if (currency === null || !Number.isFinite(sum)) {
5149
+ lines.push(`- ${values.length} template price/cost values have no comparable native-currency range.`);
5150
+ continue;
5151
+ }
5152
+ lines.push(`- ${currency}: Min ${Math.min(...values).toFixed(2)} | Avg ${(sum / values.length).toFixed(2)} | Max ${Math.max(...values).toFixed(2)}`);
5153
+ }
5154
+ lines.push(
5155
+ "\n## Recommended Actions",
5156
+ "1. Run `audit_network_coverage` to verify network quality in top markets",
5157
+ "2. Run `high_cost_subscribers` to identify margin pressure",
5158
+ "3. Consider creating regional package templates for emerging markets"
5159
+ );
5160
+ return lines.join("\n");
5161
+ }
4829
5162
  var PREPAID_PACKAGE_KEYS = ["prepaidPackage", "packages", "package"];
4830
5163
  var NETWORK_EVENT_KEYS = [
4831
5164
  "s6aAnswer",
@@ -4839,9 +5172,9 @@ function positiveSimId(raw) {
4839
5172
  const n = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
4840
5173
  return Number.isSafeInteger(n) && n > 0 ? n : void 0;
4841
5174
  }
4842
- function subscriberSimId(record) {
4843
- if (!record || typeof record !== "object") return void 0;
4844
- const rec = record;
5175
+ function subscriberSimId(record2) {
5176
+ if (!record2 || typeof record2 !== "object") return void 0;
5177
+ const rec = record2;
4845
5178
  const sim = rec.sim;
4846
5179
  if (sim && typeof sim === "object") {
4847
5180
  const simRec = sim;
@@ -4851,7 +5184,7 @@ function subscriberSimId(record) {
4851
5184
  const flat = positiveSimId(rec.simId) ?? positiveSimId(rec.sim_id);
4852
5185
  if (flat !== void 0) return flat;
4853
5186
  const nested = rec.subscriber;
4854
- if (nested && typeof nested === "object" && nested !== record) return subscriberSimId(nested);
5187
+ if (nested && typeof nested === "object" && nested !== record2) return subscriberSimId(nested);
4855
5188
  return void 0;
4856
5189
  }
4857
5190
  function simProviderStatusName(rec) {
@@ -5581,9 +5914,9 @@ async function setNetworkDefault(io, body, actor, now) {
5581
5914
  return fail(400, "VALIDATION_ERROR", `Steering list ${choice.steeringListId} was not found. Pick one from list_steering_lists.`);
5582
5915
  }
5583
5916
  }
5584
- const record = { ...choice, updatedAt: now.toISOString(), updatedBy: actor };
5585
- await io.writeStored(record);
5586
- return { ok: true, data: { orgDefault: record, appliesTo: "new_assignments_only" } };
5917
+ const record2 = { ...choice, updatedAt: now.toISOString(), updatedBy: actor };
5918
+ await io.writeStored(record2);
5919
+ return { ok: true, data: { orgDefault: record2, appliesTo: "new_assignments_only" } };
5587
5920
  }
5588
5921
  async function planNetworkDefault(io, req, now) {
5589
5922
  if (!req || !Array.isArray(req.countries) || req.countries.length === 0) {
@@ -5729,16 +6062,19 @@ export {
5729
6062
  getRateLimitWindowCounts,
5730
6063
  OcsApiError,
5731
6064
  OcsClient,
5732
- mccToIso,
5733
6065
  buildListSubscriberParams,
6066
+ subscriberStatusVerdict,
5734
6067
  extractSubscriberStatus,
6068
+ subscriberListEnvelope,
5735
6069
  applySubscriberFilters,
6070
+ OCS_LIST_KEYS,
6071
+ ocsArray,
6072
+ subscriberIccid,
6073
+ mccToIso,
5736
6074
  scopeListSubscriberParams,
5737
6075
  recordToolDescription,
5738
6076
  buildRouterCatalog,
5739
6077
  ROUTER_RULES,
5740
- OCS_LIST_KEYS,
5741
- subscriberIccid,
5742
6078
  withOcsListSummary,
5743
6079
  extractDailyUsage,
5744
6080
  daysUntil,
@@ -5746,6 +6082,11 @@ export {
5746
6082
  filterActiveSubscribers,
5747
6083
  subscriberRows,
5748
6084
  extractResellerBalance,
6085
+ regionalArpuPeriod,
6086
+ regionalArpu,
6087
+ renderRegionalArpu,
6088
+ marketingSnapshot,
6089
+ renderMarketingContext,
5749
6090
  subscriberSimId,
5750
6091
  extractSimProviderStatus,
5751
6092
  prepaidPackageRows,
@@ -5805,4 +6146,4 @@ export {
5805
6146
  package_default,
5806
6147
  CARRIER_VERSION
5807
6148
  };
5808
- //# sourceMappingURL=chunk-SZR42TUZ.js.map
6149
+ //# sourceMappingURL=chunk-2S75JA45.js.map