@carrierllc/mcp 0.13.62 → 0.13.63

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.63",
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,86 @@ var OcsClient = class {
3885
3885
  }
3886
3886
  };
3887
3887
 
3888
+ // ../../packages/ocs-client/dist/chunk-3BBVBMK2.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 extractSubscriberStatus(row) {
3899
+ if (row === null || typeof row !== "object") return null;
3900
+ const raw = row.status;
3901
+ if (typeof raw === "string" && raw.length > 0) return raw;
3902
+ if (!Array.isArray(raw)) return null;
3903
+ let fallback = null;
3904
+ for (const entry of raw) {
3905
+ if (!entry || typeof entry !== "object") continue;
3906
+ const rec = entry;
3907
+ const name = rec.status;
3908
+ if (typeof name !== "string" || name.length === 0) continue;
3909
+ const endDate = rec.endDate;
3910
+ const open = endDate === void 0 || endDate === null || endDate === "";
3911
+ if (open) return name;
3912
+ if (fallback === null) fallback = name;
3913
+ }
3914
+ return fallback;
3915
+ }
3916
+ function subscriberListEnvelope(raw) {
3917
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
3918
+ const envelope = raw;
3919
+ return ["subscriberList", "subscribers", "subscriber"].some((key) => Array.isArray(envelope[key])) ? envelope : null;
3920
+ }
3921
+ function unwrapSubscriberList(raw) {
3922
+ if (Array.isArray(raw)) return { rows: raw, envelope: null };
3923
+ if (raw !== null && typeof raw === "object") {
3924
+ const obj = raw;
3925
+ if (Array.isArray(obj.subscriberList)) {
3926
+ return { rows: obj.subscriberList, envelope: obj };
3927
+ }
3928
+ }
3929
+ return { rows: null, envelope: null };
3930
+ }
3931
+ function rewrapSubscriberList(raw, envelope, rows, filtered, matched) {
3932
+ if (rows === null || filtered === null) return raw;
3933
+ const total = matched ?? filtered.length;
3934
+ const dropped = total - filtered.length;
3935
+ if (envelope === null) return filtered;
3936
+ const out = {
3937
+ ...envelope,
3938
+ subscriberList: filtered,
3939
+ nbFound: total,
3940
+ hasMore: filtered.length < total
3941
+ };
3942
+ if (dropped > 0) {
3943
+ out.truncated = true;
3944
+ out.note = `${dropped} of ${total} matching subscribers omitted by offset/limit. Narrow with \`status\`, \`accountId\` or \`iccid\`, or page with \`offset\`.`;
3945
+ }
3946
+ return out;
3947
+ }
3948
+ function applySubscriberFilters(raw, args) {
3949
+ const { rows, envelope } = unwrapSubscriberList(raw);
3950
+ let filtered = rows;
3951
+ if (filtered && args.status) {
3952
+ const wanted = String(args.status).trim().toLowerCase();
3953
+ filtered = filtered.filter((row) => {
3954
+ const status = extractSubscriberStatus(row);
3955
+ return status !== null && status.toLowerCase() === wanted;
3956
+ });
3957
+ }
3958
+ const matched = filtered?.length;
3959
+ if (filtered && typeof args.offset === "number" && args.offset > 0) {
3960
+ filtered = filtered.slice(args.offset);
3961
+ }
3962
+ if (filtered && typeof args.limit === "number" && args.limit >= 0) {
3963
+ filtered = filtered.slice(0, args.limit);
3964
+ }
3965
+ return rewrapSubscriberList(raw, envelope, rows, filtered, matched);
3966
+ }
3967
+
3888
3968
  // ../../packages/ocs-spec/src/mcc-iso.ts
3889
3969
  var MCC_TO_ISO = {
3890
3970
  // Europe
@@ -4381,80 +4461,53 @@ function mccToIso(mcc) {
4381
4461
  return MCC_TO_ISO[n] ?? null;
4382
4462
  }
4383
4463
 
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;
4464
+ // ../../packages/ocs-client/dist/chunk-XAYYEDFR.js
4465
+ var OCS_LIST_KEYS = {
4466
+ subscribers: ["subscriberList"],
4467
+ templates: ["template", "prepaidPackageTemplate"],
4468
+ zones: ["listDetailedLocationZone", "locationZone", "zone", "zones"],
4469
+ resellers: ["reseller"],
4470
+ packages: ["prepaidPackage", "package", "packages"]
4471
+ };
4472
+ function ocsArray(data, keys) {
4473
+ if (Array.isArray(data)) return data;
4474
+ if (data === null || typeof data !== "object") return [];
4475
+ const candidates = typeof keys === "string" ? OCS_LIST_KEYS[keys] : keys;
4476
+ const obj = data;
4477
+ for (const key of candidates) {
4478
+ const v = obj[key];
4479
+ if (Array.isArray(v)) return v;
4409
4480
  }
4410
- return fallback;
4481
+ return [];
4411
4482
  }
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 };
4483
+ function subscriberIccid(row) {
4484
+ if (row === null || typeof row !== "object") return "";
4485
+ const r = row;
4486
+ const imsiList = r.imsiList;
4487
+ if (Array.isArray(imsiList)) {
4488
+ for (const entry of imsiList) {
4489
+ if (entry && typeof entry === "object") {
4490
+ const v = entry.iccid;
4491
+ if (typeof v === "string" && v.length > 0) return v;
4492
+ if (typeof v === "number") return String(v);
4493
+ }
4418
4494
  }
4419
4495
  }
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);
4496
+ for (const key of ["iccid", "ICCID"]) {
4497
+ const v = r[key];
4498
+ if (typeof v === "string" && v.length > 0) return v;
4499
+ if (typeof v === "number") return String(v);
4452
4500
  }
4453
- if (filtered && typeof args.limit === "number" && args.limit >= 0) {
4454
- filtered = filtered.slice(0, args.limit);
4501
+ const sim = r.sim;
4502
+ if (sim && typeof sim === "object") {
4503
+ const v = sim.iccid;
4504
+ if (typeof v === "string" && v.length > 0) return v;
4505
+ if (typeof v === "number") return String(v);
4455
4506
  }
4456
- return rewrapSubscriberList(raw, envelope, rows, filtered, matched);
4507
+ return "";
4457
4508
  }
4509
+
4510
+ // ../../packages/ocs-client/dist/index.js
4458
4511
  var OCS_SUBSCRIBER_SEARCH_KEYS = [
4459
4512
  "accountId",
4460
4513
  "iccid",
@@ -4603,50 +4656,6 @@ var ROUTER_RULES = `Rules:
4603
4656
  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
4657
  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
4658
  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
4659
  var FACET_TALLY_MAX = 25;
4651
4660
  var OCS_LIST_FACETS = {
4652
4661
  templates: [
@@ -4826,6 +4835,305 @@ function extractResellerBalance(raw) {
4826
4835
  const parsed = Number(value);
4827
4836
  return Number.isFinite(parsed) ? parsed : null;
4828
4837
  }
4838
+ function validDate(value) {
4839
+ 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;
4840
+ }
4841
+ function regionalArpuPeriod(start, end) {
4842
+ if (start !== void 0 && !validDate(start) || end !== void 0 && !validDate(end)) {
4843
+ throw new Error("start and end must be valid YYYY-MM-DD dates");
4844
+ }
4845
+ const finish = end ?? lastNDaysPeriod().end;
4846
+ const begin = start ?? lastNDaysPeriod(7, /* @__PURE__ */ new Date(`${finish}T00:00:00Z`)).start;
4847
+ if (begin > finish) throw new Error("start must be on or before end");
4848
+ return clampUsagePeriod(begin, finish);
4849
+ }
4850
+ function record(value) {
4851
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
4852
+ }
4853
+ function charge(value) {
4854
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
4855
+ }
4856
+ function addCost(total, value) {
4857
+ if (total === null || value === null) return null;
4858
+ const sum = total + value;
4859
+ return Number.isFinite(sum) ? sum : null;
4860
+ }
4861
+ var COUNTRY_CODES = /* @__PURE__ */ new Set([
4862
+ ...Object.values(MCC_TO_ISO).filter((code) => code !== "XX"),
4863
+ ...`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
4864
+ 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
4865
+ 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
4866
+ 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
4867
+ 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
4868
+ 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
4869
+ 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
4870
+ 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
4871
+ 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+/)
4872
+ ]);
4873
+ function countryFor(row) {
4874
+ const alpha2 = typeof row.countryAlpha2 === "string" ? row.countryAlpha2.trim().toUpperCase() : "";
4875
+ if (COUNTRY_CODES.has(alpha2)) return alpha2;
4876
+ const mapped = typeof row.mcc === "number" || typeof row.mcc === "string" ? mccToIso(row.mcc) : null;
4877
+ return mapped === "XX" ? null : mapped;
4878
+ }
4879
+ function ratedRows(data) {
4880
+ const root = record(data);
4881
+ if (!root) return [];
4882
+ const usages = Array.isArray(root.usages) ? root.usages : [root];
4883
+ const rows = [];
4884
+ for (const usage of usages) {
4885
+ const usageRecord2 = record(usage);
4886
+ if (!usageRecord2) {
4887
+ rows.push(null);
4888
+ continue;
4889
+ }
4890
+ const periods = usageRecord2.subsPeriodUsages;
4891
+ if (periods === void 0) continue;
4892
+ if (!Array.isArray(periods)) {
4893
+ rows.push(null);
4894
+ continue;
4895
+ }
4896
+ for (const period of periods) {
4897
+ const daily = record(period)?.subsDailyUsages;
4898
+ if (Array.isArray(daily)) rows.push(...daily.map(record));
4899
+ else rows.push(null);
4900
+ }
4901
+ }
4902
+ return rows;
4903
+ }
4904
+ function regionalArpu(reads, options) {
4905
+ const bySubscriber = /* @__PURE__ */ new Map();
4906
+ for (const read of reads) {
4907
+ const previous = bySubscriber.get(read.subscriber) ?? [];
4908
+ previous.push(read);
4909
+ bySubscriber.set(read.subscriber, previous);
4910
+ }
4911
+ const groups = /* @__PURE__ */ new Map();
4912
+ const measured = /* @__PURE__ */ new Set();
4913
+ const seen = /* @__PURE__ */ new Set();
4914
+ let failed = 0;
4915
+ let missingCharge = 0;
4916
+ let missingCountry = 0;
4917
+ let missingCurrency = 0;
4918
+ let duplicates = 0;
4919
+ for (const [subscriber, subscriberReads] of bySubscriber) {
4920
+ const successful = subscriberReads.filter((read) => !read.error && record(read.data));
4921
+ if (successful.length === 0) {
4922
+ failed++;
4923
+ continue;
4924
+ }
4925
+ for (const read of successful) {
4926
+ for (const row of ratedRows(read.data)) {
4927
+ if (!row) {
4928
+ missingCharge++;
4929
+ continue;
4930
+ }
4931
+ const timestamp = typeof row.usageDateUtc === "string" ? Date.parse(row.usageDateUtc) : NaN;
4932
+ if (!validDate(typeof row.usageDateUtc === "string" ? row.usageDateUtc.slice(0, 10) : "") || !Number.isFinite(timestamp)) {
4933
+ missingCharge++;
4934
+ continue;
4935
+ }
4936
+ const date = new Date(timestamp).toISOString().slice(0, 10);
4937
+ if (date < options.period.start || date > options.period.end) continue;
4938
+ const identity = JSON.stringify([subscriber, Object.keys(row).sort().map((key2) => [key2, row[key2]])]);
4939
+ if (seen.has(identity)) {
4940
+ duplicates++;
4941
+ continue;
4942
+ }
4943
+ seen.add(identity);
4944
+ const subscriberCost = charge(row.subscriberCost);
4945
+ const country = countryFor(row);
4946
+ const currency = row.resellerCurrencyId;
4947
+ const validCurrency = typeof currency === "number" && Number.isSafeInteger(currency) && currency > 0;
4948
+ const rate = row.resellerConvertRate;
4949
+ const validRate = rate == null || typeof rate === "number" && Number.isFinite(rate) && rate > 0;
4950
+ if (subscriberCost === null) missingCharge++;
4951
+ if (!country) missingCountry++;
4952
+ if (!validCurrency || !validRate) missingCurrency++;
4953
+ if (subscriberCost === null || !country || !validCurrency || !validRate) continue;
4954
+ const conversionRate = typeof rate === "number" ? rate : null;
4955
+ const key = JSON.stringify([country, currency, conversionRate]);
4956
+ let group = groups.get(key);
4957
+ const nextCharge = (group?.subscriber_cost ?? 0) + subscriberCost;
4958
+ if (!Number.isFinite(nextCharge)) {
4959
+ missingCharge++;
4960
+ continue;
4961
+ }
4962
+ if (!group) {
4963
+ group = {
4964
+ country,
4965
+ currency_id: currency,
4966
+ conversion_rate: conversionRate,
4967
+ subscriber_count: 0,
4968
+ subscriber_cost: 0,
4969
+ cost: 0,
4970
+ reseller_cost: 0,
4971
+ arpu: 0,
4972
+ subscribers: /* @__PURE__ */ new Set()
4973
+ };
4974
+ groups.set(key, group);
4975
+ }
4976
+ group.subscribers.add(subscriber);
4977
+ measured.add(subscriber);
4978
+ group.subscriber_cost = nextCharge;
4979
+ const sourceCost = charge(row.cost);
4980
+ const resellerCost = charge(row.resellerCost);
4981
+ group.cost = addCost(group.cost, sourceCost);
4982
+ group.reseller_cost = addCost(group.reseller_cost, resellerCost);
4983
+ }
4984
+ }
4985
+ }
4986
+ const regions = [...groups.values()].map(({ subscribers, ...group }) => ({
4987
+ ...group,
4988
+ subscriber_count: subscribers.size,
4989
+ arpu: group.subscriber_cost / subscribers.size
4990
+ })).sort(
4991
+ (a, b) => a.country.localeCompare(b.country) || a.currency_id - b.currency_id || (a.conversion_rate ?? 0) - (b.conversion_rate ?? 0)
4992
+ );
4993
+ const sampled = bySubscriber.size;
4994
+ const total = Math.max(options.total_subscribers, sampled);
4995
+ const truncated = Boolean(options.truncated) || sampled < total;
4996
+ const incomplete = truncated || failed > 0 || measured.size < sampled || missingCharge > 0 || missingCountry > 0 || missingCurrency > 0;
4997
+ const status = regions.length === 0 ? "unavailable" : incomplete ? "partial" : "computed";
4998
+ const note = [
4999
+ "Period ARPU = explicit subscriberCost / distinct measured subscribers in each country/currency/rate group.",
5000
+ `Measured ${measured.size} of ${sampled} sampled subscribers (${total} listed).`,
5001
+ `${failed} failed reads; ${missingCharge} missing or invalid charge/date records; ${missingCountry} missing-country records; ${missingCurrency} missing-currency records; ${duplicates} duplicate records excluded.`,
5002
+ truncated ? "Subscriber coverage is truncated." : "",
5003
+ regions.length === 0 ? "No attributable subscriber charges are available for this period." : "",
5004
+ "Source cost and resellerCost cover included measured rows separately; currencies and conversion rates are never combined or converted."
5005
+ ].filter(Boolean).join(" ");
5006
+ return {
5007
+ status,
5008
+ period: options.period,
5009
+ regions,
5010
+ total_subscribers: total,
5011
+ sampled_subscribers: sampled,
5012
+ failed_subscribers: failed,
5013
+ missing_charge_records: missingCharge,
5014
+ missing_country_records: missingCountry,
5015
+ missing_currency_records: missingCurrency,
5016
+ duplicate_records: duplicates,
5017
+ truncated,
5018
+ note
5019
+ };
5020
+ }
5021
+ function renderRegionalArpu(report) {
5022
+ const lines = [
5023
+ `## ARPU by region (${report.status})`,
5024
+ `Period: ${report.period.start} to ${report.period.end}`,
5025
+ report.note
5026
+ ];
5027
+ if (report.regions.length > 0) {
5028
+ lines.push(
5029
+ "| Country | Currency ID | Conversion rate | Measured subscribers | Subscriber charges | Source cost | Reseller cost | ARPU |",
5030
+ "|---------|-------------|-----------------|----------------------|--------------------|-------------|---------------|------|"
5031
+ );
5032
+ for (const row of report.regions) {
5033
+ 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)} |`);
5034
+ }
5035
+ }
5036
+ return lines.join("\n");
5037
+ }
5038
+ function amount(value) {
5039
+ if (typeof value !== "number" && (typeof value !== "string" || value.trim() === "")) return null;
5040
+ const parsed = Number(value);
5041
+ return Number.isFinite(parsed) ? parsed : null;
5042
+ }
5043
+ function nativeCurrency(row) {
5044
+ const id = row.currencyId ?? row.resellerCurrencyId;
5045
+ if (typeof id === "number" && Number.isSafeInteger(id) && id > 0) return `ID ${id}`;
5046
+ const code = typeof row.currency === "string" ? row.currency.trim().toUpperCase() : "";
5047
+ return /^[A-Z]{3}$/.test(code) ? code : null;
5048
+ }
5049
+ function marketingSnapshot(subscriber, location) {
5050
+ const loc = record(location);
5051
+ const network = record(loc?.networkInfo);
5052
+ const mcc = network?.lastMcc;
5053
+ const rawCountry = loc?.countryAlpha2 ?? loc?.countryCode ?? loc?.country ?? (typeof mcc === "number" || typeof mcc === "string" ? mccToIso(mcc) : null);
5054
+ const country = typeof rawCountry === "string" && rawCountry.trim() && !["XX", "ZZ", "UNKNOWN"].includes(rawCountry.trim().toUpperCase()) ? rawCountry.trim().replace(/[|\r\n]/g, " ") : "Unknown";
5055
+ const balance = loc && "balance" in loc ? loc.balance : subscriber.balance;
5056
+ return { country, balance: amount(balance), currency: (loc && nativeCurrency(loc)) ?? nativeCurrency(subscriber) };
5057
+ }
5058
+ function renderMarketingContext(snapshots, sampled, templates) {
5059
+ const lines = [
5060
+ `## Fleet Size: ${sampled} subscribers sampled`,
5061
+ "## Subscriber Concentration by Country",
5062
+ `Current-location context for ${snapshots.length} of ${sampled} sampled subscribers. Remaining balances are current account values; historical ARPU uses only rated subscriber charges.`
5063
+ ];
5064
+ const groups = /* @__PURE__ */ new Map();
5065
+ const countries = /* @__PURE__ */ new Map();
5066
+ for (const snapshot of snapshots) {
5067
+ const key = JSON.stringify([snapshot.country, snapshot.currency]);
5068
+ const group = groups.get(key) ?? { country: snapshot.country, currency: snapshot.currency, count: 0, balance: 0 };
5069
+ group.count++;
5070
+ group.balance = addCost(group.balance, snapshot.balance);
5071
+ groups.set(key, group);
5072
+ if (snapshot.country !== "Unknown") countries.set(snapshot.country, (countries.get(snapshot.country) ?? 0) + 1);
5073
+ }
5074
+ const sorted = [...groups.values()].sort(
5075
+ (a, b) => b.count - a.count || a.country.localeCompare(b.country) || (a.currency ?? "").localeCompare(b.currency ?? "")
5076
+ );
5077
+ if (sorted.length > 0) {
5078
+ lines.push(
5079
+ "| Current country | Native currency | Subscribers | % of context sample | Avg remaining balance |",
5080
+ "|-----------------|-----------------|-------------|---------------------|-----------------------|"
5081
+ );
5082
+ for (const group of sorted) {
5083
+ const average = group.currency !== null && group.balance !== null ? (group.balance / group.count).toFixed(2) : "Unknown";
5084
+ lines.push(`| ${group.country} | ${group.currency ?? "Unknown"} | ${group.count} | ${(group.count / snapshots.length * 100).toFixed(1)}% | ${average} |`);
5085
+ }
5086
+ } else {
5087
+ lines.push("Current location and remaining-balance context is unavailable.");
5088
+ }
5089
+ lines.push("\n## Market Insights");
5090
+ const ranked = [...countries].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
5091
+ const top = ranked[0];
5092
+ if (top) {
5093
+ lines.push(`- **Largest current market**: ${top[0]} (${top[1]} subscribers in this context sample)`);
5094
+ if (top[1] > snapshots.length / 2) lines.push("- More than 50% of the current context sample is concentrated in one country.");
5095
+ const balances = sorted.filter((group) => group.currency !== null && group.balance !== null && group.count >= 3);
5096
+ if (balances.length > 0) {
5097
+ lines.push("\n### Current remaining balances by market");
5098
+ for (const group of balances) {
5099
+ lines.push(`- ${group.country}, ${group.currency}: average remaining balance ${(group.balance / group.count).toFixed(2)} (${group.count} subscribers)`);
5100
+ }
5101
+ }
5102
+ const emerging = ranked.filter(([, count]) => count <= 3);
5103
+ if (emerging.length > 0) {
5104
+ lines.push("\n### Emerging Markets (early traction, 1-3 subscribers)");
5105
+ for (const [country, count] of emerging) lines.push(`- ${country}: ${count} subscriber(s); review before targeted campaigns.`);
5106
+ }
5107
+ } else {
5108
+ lines.push("No current country could be established for market insights.");
5109
+ }
5110
+ lines.push("\n### Pricing Range");
5111
+ const prices = /* @__PURE__ */ new Map();
5112
+ for (const template of templates) {
5113
+ const price = amount(template.price ?? template.cost);
5114
+ if (price === null || price < 0) continue;
5115
+ const currency = nativeCurrency(template);
5116
+ const values = prices.get(currency) ?? [];
5117
+ values.push(price);
5118
+ prices.set(currency, values);
5119
+ }
5120
+ if (prices.size === 0) lines.push("Template pricing is unavailable.");
5121
+ for (const [currency, values] of prices) {
5122
+ const sum = values.reduce((total, value) => total + value, 0);
5123
+ if (currency === null || !Number.isFinite(sum)) {
5124
+ lines.push(`- ${values.length} template price/cost values have no comparable native-currency range.`);
5125
+ continue;
5126
+ }
5127
+ lines.push(`- ${currency}: Min ${Math.min(...values).toFixed(2)} | Avg ${(sum / values.length).toFixed(2)} | Max ${Math.max(...values).toFixed(2)}`);
5128
+ }
5129
+ lines.push(
5130
+ "\n## Recommended Actions",
5131
+ "1. Run `audit_network_coverage` to verify network quality in top markets",
5132
+ "2. Run `high_cost_subscribers` to identify margin pressure",
5133
+ "3. Consider creating regional package templates for emerging markets"
5134
+ );
5135
+ return lines.join("\n");
5136
+ }
4829
5137
  var PREPAID_PACKAGE_KEYS = ["prepaidPackage", "packages", "package"];
4830
5138
  var NETWORK_EVENT_KEYS = [
4831
5139
  "s6aAnswer",
@@ -4839,9 +5147,9 @@ function positiveSimId(raw) {
4839
5147
  const n = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
4840
5148
  return Number.isSafeInteger(n) && n > 0 ? n : void 0;
4841
5149
  }
4842
- function subscriberSimId(record) {
4843
- if (!record || typeof record !== "object") return void 0;
4844
- const rec = record;
5150
+ function subscriberSimId(record2) {
5151
+ if (!record2 || typeof record2 !== "object") return void 0;
5152
+ const rec = record2;
4845
5153
  const sim = rec.sim;
4846
5154
  if (sim && typeof sim === "object") {
4847
5155
  const simRec = sim;
@@ -4851,7 +5159,7 @@ function subscriberSimId(record) {
4851
5159
  const flat = positiveSimId(rec.simId) ?? positiveSimId(rec.sim_id);
4852
5160
  if (flat !== void 0) return flat;
4853
5161
  const nested = rec.subscriber;
4854
- if (nested && typeof nested === "object" && nested !== record) return subscriberSimId(nested);
5162
+ if (nested && typeof nested === "object" && nested !== record2) return subscriberSimId(nested);
4855
5163
  return void 0;
4856
5164
  }
4857
5165
  function simProviderStatusName(rec) {
@@ -5581,9 +5889,9 @@ async function setNetworkDefault(io, body, actor, now) {
5581
5889
  return fail(400, "VALIDATION_ERROR", `Steering list ${choice.steeringListId} was not found. Pick one from list_steering_lists.`);
5582
5890
  }
5583
5891
  }
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" } };
5892
+ const record2 = { ...choice, updatedAt: now.toISOString(), updatedBy: actor };
5893
+ await io.writeStored(record2);
5894
+ return { ok: true, data: { orgDefault: record2, appliesTo: "new_assignments_only" } };
5587
5895
  }
5588
5896
  async function planNetworkDefault(io, req, now) {
5589
5897
  if (!req || !Array.isArray(req.countries) || req.countries.length === 0) {
@@ -5729,16 +6037,18 @@ export {
5729
6037
  getRateLimitWindowCounts,
5730
6038
  OcsApiError,
5731
6039
  OcsClient,
5732
- mccToIso,
5733
6040
  buildListSubscriberParams,
5734
6041
  extractSubscriberStatus,
6042
+ subscriberListEnvelope,
5735
6043
  applySubscriberFilters,
6044
+ OCS_LIST_KEYS,
6045
+ ocsArray,
6046
+ subscriberIccid,
6047
+ mccToIso,
5736
6048
  scopeListSubscriberParams,
5737
6049
  recordToolDescription,
5738
6050
  buildRouterCatalog,
5739
6051
  ROUTER_RULES,
5740
- OCS_LIST_KEYS,
5741
- subscriberIccid,
5742
6052
  withOcsListSummary,
5743
6053
  extractDailyUsage,
5744
6054
  daysUntil,
@@ -5746,6 +6056,11 @@ export {
5746
6056
  filterActiveSubscribers,
5747
6057
  subscriberRows,
5748
6058
  extractResellerBalance,
6059
+ regionalArpuPeriod,
6060
+ regionalArpu,
6061
+ renderRegionalArpu,
6062
+ marketingSnapshot,
6063
+ renderMarketingContext,
5749
6064
  subscriberSimId,
5750
6065
  extractSimProviderStatus,
5751
6066
  prepaidPackageRows,
@@ -5805,4 +6120,4 @@ export {
5805
6120
  package_default,
5806
6121
  CARRIER_VERSION
5807
6122
  };
5808
- //# sourceMappingURL=chunk-SZR42TUZ.js.map
6123
+ //# sourceMappingURL=chunk-WCIQ6OYP.js.map